blob: 0c7b00c2c31f781a1fd6cfafa0f5ed6b0c7d5288 [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
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
20#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
21# include <utime.h> /* for struct utimbuf */
22#endif
23
24#define BUFSIZE 8192 /* size of normal write buffer */
25#define SMBUFSIZE 256 /* size of emergency write buffer */
26
27#ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +020028/* crypt_magic[0] is pkzip crypt, crypt_magic[1] is sha2+blowfish */
Bram Moolenaarf50a2532010-05-21 15:36:08 +020029static char *crypt_magic[] = {"VimCrypt~01!", "VimCrypt~02!"};
30static char crypt_magic_head[] = "VimCrypt~";
31# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
Bram Moolenaar80794b12010-06-13 05:20:42 +020032
33/* For blowfish, after the magic header, we store 8 bytes of salt and then 8
34 * bytes of seed (initialisation vector). */
35static int crypt_salt_len[] = {0, 8};
Bram Moolenaarf50a2532010-05-21 15:36:08 +020036static int crypt_seed_len[] = {0, 8};
Bram Moolenaar80794b12010-06-13 05:20:42 +020037#define CRYPT_SALT_LEN_MAX 8
Bram Moolenaar40e6a712010-05-16 22:32:54 +020038#define CRYPT_SEED_LEN_MAX 8
Bram Moolenaar071d4272004-06-13 20:20:40 +000039#endif
40
41/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000042#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000043
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000044#if defined(sun) && defined(S_ISCHR)
45# define OPEN_CHR_FILES
46static int is_dev_fd_file(char_u *fname);
47#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000048#ifdef FEAT_MBYTE
49static char_u *next_fenc __ARGS((char_u **pp));
50# ifdef FEAT_EVAL
51static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
52# endif
53#endif
54#ifdef FEAT_VIMINFO
55static void check_marks_read __ARGS((void));
56#endif
57#ifdef FEAT_CRYPT
Bram Moolenaar49771f42010-07-20 17:32:38 +020058static int crypt_method_from_magic __ARGS((char *ptr, int len));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +020059static char_u *check_for_cryptkey __ARGS((char_u *cryptkey, char_u *ptr, long *sizep, off_t *filesizep, int newfile, char_u *fname, int *did_ask));
Bram Moolenaar071d4272004-06-13 20:20:40 +000060#endif
61#ifdef UNIX
62static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
63#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000064static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000065static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000066static void msg_add_eol __ARGS((void));
67static int check_mtime __ARGS((buf_T *buf, struct stat *s));
68static int time_differs __ARGS((long t1, long t2));
69#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000070static int apply_autocmds_exarg __ARGS((event_T event, char_u *fname, char_u *fname_io, int force, buf_T *buf, exarg_T *eap));
Bram Moolenaar70836c82006-02-20 21:28:49 +000071static int au_find_group __ARGS((char_u *name));
72
73# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000074# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000075# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000076#endif
77
78#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
79# define HAS_BW_FLAGS
80# define FIO_LATIN1 0x01 /* convert Latin1 */
81# define FIO_UTF8 0x02 /* convert UTF-8 */
82# define FIO_UCS2 0x04 /* convert UCS-2 */
83# define FIO_UCS4 0x08 /* convert UCS-4 */
84# define FIO_UTF16 0x10 /* convert UTF-16 */
85# ifdef WIN3264
86# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
87# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
88# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
89# endif
90# ifdef MACOS_X
91# define FIO_MACROMAN 0x20 /* convert MacRoman */
92# endif
93# define FIO_ENDIAN_L 0x80 /* little endian */
94# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
95# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
96# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
97# define FIO_ALL -1 /* allow all formats */
98#endif
99
100/* When converting, a read() or write() may leave some bytes to be converted
101 * for the next call. The value is guessed... */
102#define CONV_RESTLEN 30
103
104/* We have to guess how much a sequence of bytes may expand when converting
105 * with iconv() to be able to allocate a buffer. */
106#define ICONV_MULT 8
107
108/*
109 * Structure to pass arguments from buf_write() to buf_write_bytes().
110 */
111struct bw_info
112{
113 int bw_fd; /* file descriptor */
114 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000115 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116#ifdef HAS_BW_FLAGS
117 int bw_flags; /* FIO_ flags */
118#endif
119#ifdef FEAT_MBYTE
120 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
121 int bw_restlen; /* nr of bytes in bw_rest[] */
122 int bw_first; /* first write call */
123 char_u *bw_conv_buf; /* buffer for writing converted chars */
124 int bw_conv_buflen; /* size of bw_conv_buf */
125 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000126 linenr_T bw_conv_error_lnum; /* first line with error or zero */
127 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000128# ifdef USE_ICONV
129 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
130# endif
131#endif
132};
133
134static int buf_write_bytes __ARGS((struct bw_info *ip));
135
136#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000137static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000138static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000139static int need_conversion __ARGS((char_u *fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000140static int get_fio_flags __ARGS((char_u *ptr));
141static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
142static int make_bom __ARGS((char_u *buf, char_u *name));
143# ifdef WIN3264
144static int get_win_fio_flags __ARGS((char_u *ptr));
145# endif
146# ifdef MACOS_X
147static int get_mac_fio_flags __ARGS((char_u *ptr));
148# endif
149#endif
150static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000151#ifdef TEMPDIRNAMES
Bram Moolenaareaf03392009-11-17 11:08:52 +0000152static void vim_settempdir __ARGS((char_u *tempdir));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000153#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000154#ifdef FEAT_AUTOCMD
155static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
156#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000157
Bram Moolenaar071d4272004-06-13 20:20:40 +0000158 void
159filemess(buf, name, s, attr)
160 buf_T *buf;
161 char_u *name;
162 char_u *s;
163 int attr;
164{
165 int msg_scroll_save;
166
167 if (msg_silent != 0)
168 return;
169 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
170 /* If it's extremely long, truncate it. */
171 if (STRLEN(IObuff) > IOSIZE - 80)
172 IObuff[IOSIZE - 80] = NUL;
173 STRCAT(IObuff, s);
174 /*
175 * For the first message may have to start a new line.
176 * For further ones overwrite the previous one, reset msg_scroll before
177 * calling filemess().
178 */
179 msg_scroll_save = msg_scroll;
180 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
181 msg_scroll = FALSE;
182 if (!msg_scroll) /* wait a bit when overwriting an error msg */
183 check_for_delay(FALSE);
184 msg_start();
185 msg_scroll = msg_scroll_save;
186 msg_scrolled_ign = TRUE;
187 /* may truncate the message to avoid a hit-return prompt */
188 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
189 msg_clr_eos();
190 out_flush();
191 msg_scrolled_ign = FALSE;
192}
193
194/*
195 * Read lines from file "fname" into the buffer after line "from".
196 *
197 * 1. We allocate blocks with lalloc, as big as possible.
198 * 2. Each block is filled with characters from the file with a single read().
199 * 3. The lines are inserted in the buffer with ml_append().
200 *
201 * (caller must check that fname != NULL, unless READ_STDIN is used)
202 *
203 * "lines_to_skip" is the number of lines that must be skipped
204 * "lines_to_read" is the number of lines that are appended
205 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
206 *
207 * flags:
208 * READ_NEW starting to edit a new buffer
209 * READ_FILTER reading filter output
210 * READ_STDIN read from stdin instead of a file
211 * READ_BUFFER read from curbuf instead of a file (converting after reading
212 * stdin)
213 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200214 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215 *
216 * return FAIL for failure, OK otherwise
217 */
218 int
219readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
220 char_u *fname;
221 char_u *sfname;
222 linenr_T from;
223 linenr_T lines_to_skip;
224 linenr_T lines_to_read;
225 exarg_T *eap; /* can be NULL! */
226 int flags;
227{
228 int fd = 0;
229 int newfile = (flags & READ_NEW);
230 int check_readonly;
231 int filtering = (flags & READ_FILTER);
232 int read_stdin = (flags & READ_STDIN);
233 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000234 int set_options = newfile || read_buffer
235 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000236 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
237 colnr_T read_buf_col = 0; /* next char to read from this line */
238 char_u c;
239 linenr_T lnum = from;
240 char_u *ptr = NULL; /* pointer into read buffer */
241 char_u *buffer = NULL; /* read buffer */
242 char_u *new_buffer = NULL; /* init to shut up gcc */
243 char_u *line_start = NULL; /* init to shut up gcc */
244 int wasempty; /* buffer was empty before reading */
245 colnr_T len;
246 long size = 0;
247 char_u *p;
Bram Moolenaar914703b2010-05-31 21:59:46 +0200248 off_t filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000249 int skip_read = FALSE;
250#ifdef FEAT_CRYPT
251 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200252 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000253#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200254#ifdef FEAT_PERSISTENT_UNDO
255 context_sha256_T sha_ctx;
256 int read_undo_file = FALSE;
257#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000258 int split = 0; /* number of split lines */
259#define UNKNOWN 0x0fffffff /* file size is unknown */
260 linenr_T linecnt;
261 int error = FALSE; /* errors encountered */
262 int ff_error = EOL_UNKNOWN; /* file format with errors */
263 long linerest = 0; /* remaining chars in line */
264#ifdef UNIX
265 int perm = 0;
266 int swap_mode = -1; /* protection bits for swap file */
267#else
268 int perm;
269#endif
270 int fileformat = 0; /* end-of-line format */
271 int keep_fileformat = FALSE;
272 struct stat st;
273 int file_readonly;
274 linenr_T skip_count = 0;
275 linenr_T read_count = 0;
276 int msg_save = msg_scroll;
277 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
278 * last read was missing the eol */
279 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
280 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
281 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
282 int file_rewind = FALSE;
283#ifdef FEAT_MBYTE
284 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000285 linenr_T conv_error = 0; /* line nr with conversion error */
286 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000287 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
288 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000289 int bad_char_behavior = BAD_REPLACE;
290 /* BAD_KEEP, BAD_DROP or character to
291 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000292 char_u *tmpname = NULL; /* name of 'charconvert' output file */
293 int fio_flags = 0;
294 char_u *fenc; /* fileencoding to use */
295 int fenc_alloced; /* fenc_next is in allocated memory */
296 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
297 int advance_fenc = FALSE;
298 long real_size = 0;
299# ifdef USE_ICONV
300 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
301# ifdef FEAT_EVAL
302 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
303 'charconvert' next */
304# endif
305# endif
306 int converted = FALSE; /* TRUE if conversion done */
307 int notconverted = FALSE; /* TRUE if conversion wanted but it
308 wasn't possible */
309 char_u conv_rest[CONV_RESTLEN];
310 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
311#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000312#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200313 buf_T *old_curbuf;
314 char_u *old_b_ffname;
315 char_u *old_b_fname;
316 int using_b_ffname;
317 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000318#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200319
Bram Moolenaar071d4272004-06-13 20:20:40 +0000320 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000321
322 /*
323 * If there is no file name yet, use the one for the read file.
324 * BF_NOTEDITED is set to reflect this.
325 * Don't do this for a read from a filter.
326 * Only do this when 'cpoptions' contains the 'f' flag.
327 */
328 if (curbuf->b_ffname == NULL
329 && !filtering
330 && fname != NULL
331 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
332 && !(flags & READ_DUMMY))
333 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000334 if (set_rw_fname(fname, sfname) == FAIL)
335 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000336 }
337
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200338#ifdef FEAT_AUTOCMD
339 /* Remember the initial values of curbuf, curbuf->b_ffname and
340 * curbuf->b_fname to detect whether they are altered as a result of
341 * executing nasty autocommands. Also check if "fname" and "sfname"
342 * point to one of these values. */
343 old_curbuf = curbuf;
344 old_b_ffname = curbuf->b_ffname;
345 old_b_fname = curbuf->b_fname;
346 using_b_ffname = (fname == curbuf->b_ffname)
347 || (sfname == curbuf->b_ffname);
348 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
349#endif
350
Bram Moolenaardf177f62005-02-22 08:39:57 +0000351 /* After reading a file the cursor line changes but we don't want to
352 * display the line. */
353 ex_no_reprint = TRUE;
354
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000355 /* don't display the file info for another buffer now */
356 need_fileinfo = FALSE;
357
Bram Moolenaar071d4272004-06-13 20:20:40 +0000358 /*
359 * For Unix: Use the short file name whenever possible.
360 * Avoids problems with networks and when directory names are changed.
361 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
362 * another directory, which we don't detect.
363 */
364 if (sfname == NULL)
365 sfname = fname;
366#if defined(UNIX) || defined(__EMX__)
367 fname = sfname;
368#endif
369
370#ifdef FEAT_AUTOCMD
371 /*
372 * The BufReadCmd and FileReadCmd events intercept the reading process by
373 * executing the associated commands instead.
374 */
375 if (!filtering && !read_stdin && !read_buffer)
376 {
377 pos_T pos;
378
379 pos = curbuf->b_op_start;
380
381 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
382 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
383 curbuf->b_op_start.col = 0;
384
385 if (newfile)
386 {
387 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
388 FALSE, curbuf, eap))
389#ifdef FEAT_EVAL
390 return aborting() ? FAIL : OK;
391#else
392 return OK;
393#endif
394 }
395 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
396 FALSE, NULL, eap))
397#ifdef FEAT_EVAL
398 return aborting() ? FAIL : OK;
399#else
400 return OK;
401#endif
402
403 curbuf->b_op_start = pos;
404 }
405#endif
406
407 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
408 msg_scroll = FALSE; /* overwrite previous file message */
409 else
410 msg_scroll = TRUE; /* don't overwrite previous file message */
411
412 /*
413 * If the name ends in a path separator, we can't open it. Check here,
414 * because reading the file may actually work, but then creating the swap
415 * file may destroy it! Reported on MS-DOS and Win 95.
416 * If the name is too long we might crash further on, quit here.
417 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000418 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000419 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000420 p = fname + STRLEN(fname);
421 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000422 {
423 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
424 msg_end();
425 msg_scroll = msg_save;
426 return FAIL;
427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000428 }
429
430#ifdef UNIX
431 /*
432 * On Unix it is possible to read a directory, so we have to
433 * check for it before the mch_open().
434 */
435 if (!read_stdin && !read_buffer)
436 {
437 perm = mch_getperm(fname);
438 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
439# ifdef S_ISFIFO
440 && !S_ISFIFO(perm) /* ... or fifo */
441# endif
442# ifdef S_ISSOCK
443 && !S_ISSOCK(perm) /* ... or socket */
444# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000445# ifdef OPEN_CHR_FILES
446 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
447 /* ... or a character special file named /dev/fd/<n> */
448# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000449 )
450 {
451 if (S_ISDIR(perm))
452 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
453 else
454 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
455 msg_end();
456 msg_scroll = msg_save;
457 return FAIL;
458 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000459
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000460# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
461 /*
462 * MS-Windows allows opening a device, but we will probably get stuck
463 * trying to read it.
464 */
465 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
466 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000467 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000468 msg_end();
469 msg_scroll = msg_save;
470 return FAIL;
471 }
472# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000473 }
474#endif
475
Bram Moolenaar071d4272004-06-13 20:20:40 +0000476 /* set default 'fileformat' */
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000477 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 {
479 if (eap != NULL && eap->force_ff != 0)
480 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
481 else if (*p_ffs != NUL)
482 set_fileformat(default_fileformat(), OPT_LOCAL);
483 }
484
485 /* set or reset 'binary' */
486 if (eap != NULL && eap->force_bin != 0)
487 {
488 int oldval = curbuf->b_p_bin;
489
490 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
491 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
492 }
493
494 /*
495 * When opening a new file we take the readonly flag from the file.
496 * Default is r/w, can be set to r/o below.
497 * Don't reset it when in readonly mode
498 * Only set/reset b_p_ro when BF_CHECK_RO is set.
499 */
500 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000501 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000502 curbuf->b_p_ro = FALSE;
503
504 if (newfile && !read_stdin && !read_buffer)
505 {
506 /* Remember time of file.
507 * For RISCOS, also remember the filetype.
508 */
509 if (mch_stat((char *)fname, &st) >= 0)
510 {
511 buf_store_time(curbuf, &st, fname);
512 curbuf->b_mtime_read = curbuf->b_mtime;
513
514#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
515 /* Read the filetype into the buffer local filetype option. */
516 mch_read_filetype(fname);
517#endif
518#ifdef UNIX
519 /*
520 * Use the protection bits of the original file for the swap file.
521 * This makes it possible for others to read the name of the
522 * edited file from the swapfile, but only if they can read the
523 * edited file.
524 * Remove the "write" and "execute" bits for group and others
525 * (they must not write the swapfile).
526 * Add the "read" and "write" bits for the user, otherwise we may
527 * not be able to write to the file ourselves.
528 * Setting the bits is done below, after creating the swap file.
529 */
530 swap_mode = (st.st_mode & 0644) | 0600;
531#endif
532#ifdef FEAT_CW_EDITOR
533 /* Get the FSSpec on MacOS
534 * TODO: Update it properly when the buffer name changes
535 */
536 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
537#endif
538#ifdef VMS
539 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000540 curbuf->b_fab_rat = st.st_fab_rat;
541 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000542#endif
543 }
544 else
545 {
546 curbuf->b_mtime = 0;
547 curbuf->b_mtime_read = 0;
548 curbuf->b_orig_size = 0;
549 curbuf->b_orig_mode = 0;
550 }
551
552 /* Reset the "new file" flag. It will be set again below when the
553 * file doesn't exist. */
554 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
555 }
556
557/*
558 * for UNIX: check readonly with perm and mch_access()
559 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
560 * for MSDOS and Amiga: check readonly by trying to open the file for writing
561 */
562 file_readonly = FALSE;
563 if (read_stdin)
564 {
565#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
566 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
567 setmode(0, O_BINARY);
568#endif
569 }
570 else if (!read_buffer)
571 {
572#ifdef USE_MCH_ACCESS
573 if (
574# ifdef UNIX
575 !(perm & 0222) ||
576# endif
577 mch_access((char *)fname, W_OK))
578 file_readonly = TRUE;
579 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
580#else
581 if (!newfile
582 || readonlymode
583 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
584 {
585 file_readonly = TRUE;
586 /* try to open ro */
587 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
588 }
589#endif
590 }
591
592 if (fd < 0) /* cannot open at all */
593 {
594#ifndef UNIX
595 int isdir_f;
596#endif
597 msg_scroll = msg_save;
598#ifndef UNIX
599 /*
600 * On MSDOS and Amiga we can't open a directory, check here.
601 */
602 isdir_f = (mch_isdir(fname));
603 perm = mch_getperm(fname); /* check if the file exists */
604 if (isdir_f)
605 {
606 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
607 curbuf->b_p_ro = TRUE; /* must use "w!" now */
608 }
609 else
610#endif
611 if (newfile)
612 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200613 if (perm < 0
614#ifdef ENOENT
615 && errno == ENOENT
616#endif
617 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000618 {
619 /*
620 * Set the 'new-file' flag, so that when the file has
621 * been created by someone else, a ":w" will complain.
622 */
623 curbuf->b_flags |= BF_NEW;
624
625 /* Create a swap file now, so that other Vims are warned
626 * that we are editing this file. Don't do this for a
627 * "nofile" or "nowrite" buffer type. */
628#ifdef FEAT_QUICKFIX
629 if (!bt_dontwrite(curbuf))
630#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000631 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000632 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000633#ifdef FEAT_AUTOCMD
634 /* SwapExists autocommand may mess things up */
635 if (curbuf != old_curbuf
636 || (using_b_ffname
637 && (old_b_ffname != curbuf->b_ffname))
638 || (using_b_fname
639 && (old_b_fname != curbuf->b_fname)))
640 {
641 EMSG(_(e_auchangedbuf));
642 return FAIL;
643 }
644#endif
645 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000646 if (dir_of_file_exists(fname))
647 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
648 else
649 filemess(curbuf, sfname,
650 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000651#ifdef FEAT_VIMINFO
652 /* Even though this is a new file, it might have been
653 * edited before and deleted. Get the old marks. */
654 check_marks_read();
655#endif
656#ifdef FEAT_MBYTE
657 if (eap != NULL && eap->force_enc != 0)
658 {
659 /* set forced 'fileencoding' */
660 fenc = enc_canonize(eap->cmd + eap->force_enc);
661 if (fenc != NULL)
662 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000663 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000664 vim_free(fenc);
665 }
666#endif
667#ifdef FEAT_AUTOCMD
668 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
669 FALSE, curbuf, eap);
670#endif
671 /* remember the current fileformat */
672 save_file_ff(curbuf);
673
674#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
675 if (aborting()) /* autocmds may abort script processing */
676 return FAIL;
677#endif
678 return OK; /* a new file is not an error */
679 }
680 else
681 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000682 filemess(curbuf, sfname, (char_u *)(
683# ifdef EFBIG
684 (errno == EFBIG) ? _("[File too big]") :
685# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200686# ifdef EOVERFLOW
687 (errno == EOVERFLOW) ? _("[File too big]") :
688# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000689 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690 curbuf->b_p_ro = TRUE; /* must use "w!" now */
691 }
692 }
693
694 return FAIL;
695 }
696
697 /*
698 * Only set the 'ro' flag for readonly files the first time they are
699 * loaded. Help files always get readonly mode
700 */
701 if ((check_readonly && file_readonly) || curbuf->b_help)
702 curbuf->b_p_ro = TRUE;
703
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000704 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000706 /* Don't change 'eol' if reading from buffer as it will already be
707 * correctly set when reading stdin. */
708 if (!read_buffer)
709 {
710 curbuf->b_p_eol = TRUE;
711 curbuf->b_start_eol = TRUE;
712 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713#ifdef FEAT_MBYTE
714 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000715 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000716#endif
717 }
718
719 /* Create a swap file now, so that other Vims are warned that we are
720 * editing this file.
721 * Don't do this for a "nofile" or "nowrite" buffer type. */
722#ifdef FEAT_QUICKFIX
723 if (!bt_dontwrite(curbuf))
724#endif
725 {
726 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000727#ifdef FEAT_AUTOCMD
728 if (!read_stdin && (curbuf != old_curbuf
729 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
730 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
731 {
732 EMSG(_(e_auchangedbuf));
733 if (!read_buffer)
734 close(fd);
735 return FAIL;
736 }
737#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738#ifdef UNIX
739 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000740 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
741 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
743#endif
744 }
745
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000746#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000747 /* If "Quit" selected at ATTENTION dialog, don't load the file */
748 if (swap_exists_action == SEA_QUIT)
749 {
750 if (!read_buffer && !read_stdin)
751 close(fd);
752 return FAIL;
753 }
754#endif
755
756 ++no_wait_return; /* don't wait for return yet */
757
758 /*
759 * Set '[ mark to the line above where the lines go (line 1 if zero).
760 */
761 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
762 curbuf->b_op_start.col = 0;
763
764#ifdef FEAT_AUTOCMD
765 if (!read_buffer)
766 {
767 int m = msg_scroll;
768 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769
770 /*
771 * The file must be closed again, the autocommands may want to change
772 * the file before reading it.
773 */
774 if (!read_stdin)
775 close(fd); /* ignore errors */
776
777 /*
778 * The output from the autocommands should not overwrite anything and
779 * should not be overwritten: Set msg_scroll, restore its value if no
780 * output was done.
781 */
782 msg_scroll = TRUE;
783 if (filtering)
784 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
785 FALSE, curbuf, eap);
786 else if (read_stdin)
787 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
788 FALSE, curbuf, eap);
789 else if (newfile)
790 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
791 FALSE, curbuf, eap);
792 else
793 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
794 FALSE, NULL, eap);
795 if (msg_scrolled == n)
796 msg_scroll = m;
797
798#ifdef FEAT_EVAL
799 if (aborting()) /* autocmds may abort script processing */
800 {
801 --no_wait_return;
802 msg_scroll = msg_save;
803 curbuf->b_p_ro = TRUE; /* must use "w!" now */
804 return FAIL;
805 }
806#endif
807 /*
808 * Don't allow the autocommands to change the current buffer.
809 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000810 *
811 * Don't allow the autocommands to change the buffer name either
812 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000813 */
814 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000815 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
816 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
818 {
819 --no_wait_return;
820 msg_scroll = msg_save;
821 if (fd < 0)
822 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
823 else
824 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
825 curbuf->b_p_ro = TRUE; /* must use "w!" now */
826 return FAIL;
827 }
828 }
829#endif /* FEAT_AUTOCMD */
830
831 /* Autocommands may add lines to the file, need to check if it is empty */
832 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
833
834 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
835 {
836 /*
837 * Show the user that we are busy reading the input. Sometimes this
838 * may take a while. When reading from stdin another program may
839 * still be running, don't move the cursor to the last line, unless
840 * always using the GUI.
841 */
842 if (read_stdin)
843 {
844#ifndef ALWAYS_USE_GUI
845 mch_msg(_("Vim: Reading from stdin...\n"));
846#endif
847#ifdef FEAT_GUI
848 /* Also write a message in the GUI window, if there is one. */
849 if (gui.in_use && !gui.dying && !gui.starting)
850 {
851 p = (char_u *)_("Reading from stdin...");
852 gui_write(p, (int)STRLEN(p));
853 }
854#endif
855 }
856 else if (!read_buffer)
857 filemess(curbuf, sfname, (char_u *)"", 0);
858 }
859
860 msg_scroll = FALSE; /* overwrite the file message */
861
862 /*
863 * Set linecnt now, before the "retry" caused by a wrong guess for
864 * fileformat, and after the autocommands, which may change them.
865 */
866 linecnt = curbuf->b_ml.ml_line_count;
867
868#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000869 /* "++bad=" argument. */
870 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000871 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000872 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000873 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000874 curbuf->b_bad_char = eap->bad_char;
875 }
876 else
877 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000878
Bram Moolenaar071d4272004-06-13 20:20:40 +0000879 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000880 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000881 */
882 if (eap != NULL && eap->force_enc != 0)
883 {
884 fenc = enc_canonize(eap->cmd + eap->force_enc);
885 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000886 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887 }
888 else if (curbuf->b_p_bin)
889 {
890 fenc = (char_u *)""; /* binary: don't convert */
891 fenc_alloced = FALSE;
892 }
893 else if (curbuf->b_help)
894 {
895 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000896 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000897
898 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
899 * fails it must be latin1.
900 * Always do this when 'encoding' is "utf-8". Otherwise only do
901 * this when needed to avoid [converted] remarks all the time.
902 * It is needed when the first line contains non-ASCII characters.
903 * That is only in *.??x files. */
904 fenc = (char_u *)"latin1";
905 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000906 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000907 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000908 fc = fname[STRLEN(fname) - 1];
909 if (TOLOWER_ASC(fc) == 'x')
910 {
911 /* Read the first line (and a bit more). Immediately rewind to
912 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100913 len = read_eintr(fd, firstline, 80);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000914 lseek(fd, (off_t)0L, SEEK_SET);
915 for (p = firstline; p < firstline + len; ++p)
916 if (*p >= 0x80)
917 {
918 c = TRUE;
919 break;
920 }
921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922 }
923
924 if (c)
925 {
926 fenc_next = fenc;
927 fenc = (char_u *)"utf-8";
928
929 /* When the file is utf-8 but a character doesn't fit in
930 * 'encoding' don't retry. In help text editing utf-8 bytes
931 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000932 if (!enc_utf8)
933 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000934 }
935 fenc_alloced = FALSE;
936 }
937 else if (*p_fencs == NUL)
938 {
939 fenc = curbuf->b_p_fenc; /* use format from buffer */
940 fenc_alloced = FALSE;
941 }
942 else
943 {
944 fenc_next = p_fencs; /* try items in 'fileencodings' */
945 fenc = next_fenc(&fenc_next);
946 fenc_alloced = TRUE;
947 }
948#endif
949
950 /*
951 * Jump back here to retry reading the file in different ways.
952 * Reasons to retry:
953 * - encoding conversion failed: try another one from "fenc_next"
954 * - BOM detected and fenc was set, need to setup conversion
955 * - "fileformat" check failed: try another
956 *
957 * Variables set for special retry actions:
958 * "file_rewind" Rewind the file to start reading it again.
959 * "advance_fenc" Advance "fenc" using "fenc_next".
960 * "skip_read" Re-use already read bytes (BOM detected).
961 * "did_iconv" iconv() conversion failed, try 'charconvert'.
962 * "keep_fileformat" Don't reset "fileformat".
963 *
964 * Other status indicators:
965 * "tmpname" When != NULL did conversion with 'charconvert'.
966 * Output file has to be deleted afterwards.
967 * "iconv_fd" When != -1 did conversion with iconv().
968 */
969retry:
970
971 if (file_rewind)
972 {
973 if (read_buffer)
974 {
975 read_buf_lnum = 1;
976 read_buf_col = 0;
977 }
978 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
979 {
980 /* Can't rewind the file, give up. */
981 error = TRUE;
982 goto failed;
983 }
984 /* Delete the previously read lines. */
985 while (lnum > from)
986 ml_delete(lnum--, FALSE);
987 file_rewind = FALSE;
988#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000989 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000990 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000991 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000992 curbuf->b_start_bomb = FALSE;
993 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000994 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000995#endif
996 }
997
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +0200998#ifdef FEAT_CRYPT
999 if (cryptkey != NULL)
1000 /* Need to reset the state, but keep the key, don't want to ask for it
1001 * again. */
1002 crypt_pop_state();
1003#endif
1004
Bram Moolenaar071d4272004-06-13 20:20:40 +00001005 /*
1006 * When retrying with another "fenc" and the first time "fileformat"
1007 * will be reset.
1008 */
1009 if (keep_fileformat)
1010 keep_fileformat = FALSE;
1011 else
1012 {
1013 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001014 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001015 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001016 try_unix = try_dos = try_mac = FALSE;
1017 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018 else if (curbuf->b_p_bin)
1019 fileformat = EOL_UNIX; /* binary: use Unix format */
1020 else if (*p_ffs == NUL)
1021 fileformat = get_fileformat(curbuf);/* use format from buffer */
1022 else
1023 fileformat = EOL_UNKNOWN; /* detect from file */
1024 }
1025
1026#ifdef FEAT_MBYTE
1027# ifdef USE_ICONV
1028 if (iconv_fd != (iconv_t)-1)
1029 {
1030 /* aborted conversion with iconv(), close the descriptor */
1031 iconv_close(iconv_fd);
1032 iconv_fd = (iconv_t)-1;
1033 }
1034# endif
1035
1036 if (advance_fenc)
1037 {
1038 /*
1039 * Try the next entry in 'fileencodings'.
1040 */
1041 advance_fenc = FALSE;
1042
1043 if (eap != NULL && eap->force_enc != 0)
1044 {
1045 /* Conversion given with "++cc=" wasn't possible, read
1046 * without conversion. */
1047 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001048 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001049 if (fenc_alloced)
1050 vim_free(fenc);
1051 fenc = (char_u *)"";
1052 fenc_alloced = FALSE;
1053 }
1054 else
1055 {
1056 if (fenc_alloced)
1057 vim_free(fenc);
1058 if (fenc_next != NULL)
1059 {
1060 fenc = next_fenc(&fenc_next);
1061 fenc_alloced = (fenc_next != NULL);
1062 }
1063 else
1064 {
1065 fenc = (char_u *)"";
1066 fenc_alloced = FALSE;
1067 }
1068 }
1069 if (tmpname != NULL)
1070 {
1071 mch_remove(tmpname); /* delete converted file */
1072 vim_free(tmpname);
1073 tmpname = NULL;
1074 }
1075 }
1076
1077 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001078 * Conversion may be required when the encoding of the file is different
1079 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080 */
1081 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001082 converted = need_conversion(fenc);
1083 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001084 {
1085
1086 /* "ucs-bom" means we need to check the first bytes of the file
1087 * for a BOM. */
1088 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1089 fio_flags = FIO_UCSBOM;
1090
1091 /*
1092 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1093 * done. This is handled below after read(). Prepare the
1094 * fio_flags to avoid having to parse the string each time.
1095 * Also check for Unicode to Latin1 conversion, because iconv()
1096 * appears not to handle this correctly. This works just like
1097 * conversion to UTF-8 except how the resulting character is put in
1098 * the buffer.
1099 */
1100 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1101 fio_flags = get_fio_flags(fenc);
1102
1103# ifdef WIN3264
1104 /*
1105 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1106 * is handled with MultiByteToWideChar().
1107 */
1108 if (fio_flags == 0)
1109 fio_flags = get_win_fio_flags(fenc);
1110# endif
1111
1112# ifdef MACOS_X
1113 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1114 if (fio_flags == 0)
1115 fio_flags = get_mac_fio_flags(fenc);
1116# endif
1117
1118# ifdef USE_ICONV
1119 /*
1120 * Try using iconv() if we can't convert internally.
1121 */
1122 if (fio_flags == 0
1123# ifdef FEAT_EVAL
1124 && !did_iconv
1125# endif
1126 )
1127 iconv_fd = (iconv_t)my_iconv_open(
1128 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1129# endif
1130
1131# ifdef FEAT_EVAL
1132 /*
1133 * Use the 'charconvert' expression when conversion is required
1134 * and we can't do it internally or with iconv().
1135 */
1136 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1137# ifdef USE_ICONV
1138 && iconv_fd == (iconv_t)-1
1139# endif
1140 )
1141 {
1142# ifdef USE_ICONV
1143 did_iconv = FALSE;
1144# endif
1145 /* Skip conversion when it's already done (retry for wrong
1146 * "fileformat"). */
1147 if (tmpname == NULL)
1148 {
1149 tmpname = readfile_charconvert(fname, fenc, &fd);
1150 if (tmpname == NULL)
1151 {
1152 /* Conversion failed. Try another one. */
1153 advance_fenc = TRUE;
1154 if (fd < 0)
1155 {
1156 /* Re-opening the original file failed! */
1157 EMSG(_("E202: Conversion made file unreadable!"));
1158 error = TRUE;
1159 goto failed;
1160 }
1161 goto retry;
1162 }
1163 }
1164 }
1165 else
1166# endif
1167 {
1168 if (fio_flags == 0
1169# ifdef USE_ICONV
1170 && iconv_fd == (iconv_t)-1
1171# endif
1172 )
1173 {
1174 /* Conversion wanted but we can't.
1175 * Try the next conversion in 'fileencodings' */
1176 advance_fenc = TRUE;
1177 goto retry;
1178 }
1179 }
1180 }
1181
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001182 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001183 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001184 * stdin or fixed at a specific encoding. */
1185 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001186#endif
1187
1188 if (!skip_read)
1189 {
1190 linerest = 0;
1191 filesize = 0;
1192 skip_count = lines_to_skip;
1193 read_count = lines_to_read;
1194#ifdef FEAT_MBYTE
1195 conv_restlen = 0;
1196#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001197#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001198 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1199 && curbuf->b_ffname != NULL
1200 && curbuf->b_p_udf
1201 && !filtering
1202 && !read_stdin
1203 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001204 if (read_undo_file)
1205 sha256_start(&sha_ctx);
1206#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001207 }
1208
1209 while (!error && !got_int)
1210 {
1211 /*
1212 * We allocate as much space for the file as we can get, plus
1213 * space for the old line plus room for one terminating NUL.
1214 * The amount is limited by the fact that read() only can read
1215 * upto max_unsigned characters (and other things).
1216 */
1217#if SIZEOF_INT <= 2
1218 if (linerest >= 0x7ff0)
1219 {
1220 ++split;
1221 *ptr = NL; /* split line by inserting a NL */
1222 size = 1;
1223 }
1224 else
1225#endif
1226 {
1227 if (!skip_read)
1228 {
1229#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001230# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001231 size = SSIZE_MAX; /* use max I/O size, 52K */
1232# else
1233 size = 0x10000L; /* use buffer >= 64K */
1234# endif
1235#else
1236 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1237#endif
1238
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001239 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001240 {
1241 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1242 FALSE)) != NULL)
1243 break;
1244 }
1245 if (new_buffer == NULL)
1246 {
1247 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1248 error = TRUE;
1249 break;
1250 }
1251 if (linerest) /* copy characters from the previous buffer */
1252 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1253 vim_free(buffer);
1254 buffer = new_buffer;
1255 ptr = buffer + linerest;
1256 line_start = buffer;
1257
1258#ifdef FEAT_MBYTE
1259 /* May need room to translate into.
1260 * For iconv() we don't really know the required space, use a
1261 * factor ICONV_MULT.
1262 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1263 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1264 * become up to 4 bytes, size must be multiple of 2
1265 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1266 * multiple of 2
1267 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1268 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001269 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001270# ifdef USE_ICONV
1271 if (iconv_fd != (iconv_t)-1)
1272 size = size / ICONV_MULT;
1273 else
1274# endif
1275 if (fio_flags & FIO_LATIN1)
1276 size = size / 2;
1277 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1278 size = (size * 2 / 3) & ~1;
1279 else if (fio_flags & FIO_UCS4)
1280 size = (size * 2 / 3) & ~3;
1281 else if (fio_flags == FIO_UCSBOM)
1282 size = size / ICONV_MULT; /* worst case */
1283# ifdef WIN3264
1284 else if (fio_flags & FIO_CODEPAGE)
1285 size = size / ICONV_MULT; /* also worst case */
1286# endif
1287# ifdef MACOS_X
1288 else if (fio_flags & FIO_MACROMAN)
1289 size = size / ICONV_MULT; /* also worst case */
1290# endif
1291#endif
1292
1293#ifdef FEAT_MBYTE
1294 if (conv_restlen > 0)
1295 {
1296 /* Insert unconverted bytes from previous line. */
1297 mch_memmove(ptr, conv_rest, conv_restlen);
1298 ptr += conv_restlen;
1299 size -= conv_restlen;
1300 }
1301#endif
1302
1303 if (read_buffer)
1304 {
1305 /*
1306 * Read bytes from curbuf. Used for converting text read
1307 * from stdin.
1308 */
1309 if (read_buf_lnum > from)
1310 size = 0;
1311 else
1312 {
1313 int n, ni;
1314 long tlen;
1315
1316 tlen = 0;
1317 for (;;)
1318 {
1319 p = ml_get(read_buf_lnum) + read_buf_col;
1320 n = (int)STRLEN(p);
1321 if ((int)tlen + n + 1 > size)
1322 {
1323 /* Filled up to "size", append partial line.
1324 * Change NL to NUL to reverse the effect done
1325 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001326 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001327 for (ni = 0; ni < n; ++ni)
1328 {
1329 if (p[ni] == NL)
1330 ptr[tlen++] = NUL;
1331 else
1332 ptr[tlen++] = p[ni];
1333 }
1334 read_buf_col += n;
1335 break;
1336 }
1337 else
1338 {
1339 /* Append whole line and new-line. Change NL
1340 * to NUL to reverse the effect done below. */
1341 for (ni = 0; ni < n; ++ni)
1342 {
1343 if (p[ni] == NL)
1344 ptr[tlen++] = NUL;
1345 else
1346 ptr[tlen++] = p[ni];
1347 }
1348 ptr[tlen++] = NL;
1349 read_buf_col = 0;
1350 if (++read_buf_lnum > from)
1351 {
1352 /* When the last line didn't have an
1353 * end-of-line don't add it now either. */
1354 if (!curbuf->b_p_eol)
1355 --tlen;
1356 size = tlen;
1357 break;
1358 }
1359 }
1360 }
1361 }
1362 }
1363 else
1364 {
1365 /*
1366 * Read bytes from the file.
1367 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001368 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001369 }
1370
1371 if (size <= 0)
1372 {
1373 if (size < 0) /* read error */
1374 error = TRUE;
1375#ifdef FEAT_MBYTE
1376 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001377 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001378 /*
1379 * Reached end-of-file but some trailing bytes could
1380 * not be converted. Truncated file?
1381 */
1382
1383 /* When we did a conversion report an error. */
1384 if (fio_flags != 0
1385# ifdef USE_ICONV
1386 || iconv_fd != (iconv_t)-1
1387# endif
1388 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001389 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001390 if (conv_error == 0)
1391 conv_error = curbuf->b_ml.ml_line_count
1392 - linecnt + 1;
1393 }
1394 /* Remember the first linenr with an illegal byte */
1395 else if (illegal_byte == 0)
1396 illegal_byte = curbuf->b_ml.ml_line_count
1397 - linecnt + 1;
1398 if (bad_char_behavior == BAD_DROP)
1399 {
1400 *(ptr - conv_restlen) = NUL;
1401 conv_restlen = 0;
1402 }
1403 else
1404 {
1405 /* Replace the trailing bytes with the replacement
1406 * character if we were converting; if we weren't,
1407 * leave the UTF8 checking code to do it, as it
1408 * works slightly differently. */
1409 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1410# ifdef USE_ICONV
1411 || iconv_fd != (iconv_t)-1
1412# endif
1413 ))
1414 {
1415 while (conv_restlen > 0)
1416 {
1417 *(--ptr) = bad_char_behavior;
1418 --conv_restlen;
1419 }
1420 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001421 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001422# ifdef USE_ICONV
1423 if (iconv_fd != (iconv_t)-1)
1424 {
1425 iconv_close(iconv_fd);
1426 iconv_fd = (iconv_t)-1;
1427 }
1428# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001429 }
1430 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001431#endif
1432 }
1433
1434#ifdef FEAT_CRYPT
1435 /*
1436 * At start of file: Check for magic number of encryption.
1437 */
1438 if (filesize == 0)
1439 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001440 &filesize, newfile, sfname,
1441 &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001442 /*
1443 * Decrypt the read bytes.
1444 */
1445 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001446 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447#endif
1448 }
1449 skip_read = FALSE;
1450
1451#ifdef FEAT_MBYTE
1452 /*
1453 * At start of file (or after crypt magic number): Check for BOM.
1454 * Also check for a BOM for other Unicode encodings, but not after
1455 * converting with 'charconvert' or when a BOM has already been
1456 * found.
1457 */
1458 if ((filesize == 0
1459# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001460 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001461 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001462 + crypt_seed_len[use_crypt_method])
1463 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001464# endif
1465 )
1466 && (fio_flags == FIO_UCSBOM
1467 || (!curbuf->b_p_bomb
1468 && tmpname == NULL
1469 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1470 {
1471 char_u *ccname;
1472 int blen;
1473
1474 /* no BOM detection in a short file or in binary mode */
1475 if (size < 2 || curbuf->b_p_bin)
1476 ccname = NULL;
1477 else
1478 ccname = check_for_bom(ptr, size, &blen,
1479 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1480 if (ccname != NULL)
1481 {
1482 /* Remove BOM from the text */
1483 filesize += blen;
1484 size -= blen;
1485 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001486 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001487 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001488 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001489 curbuf->b_start_bomb = TRUE;
1490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001491 }
1492
1493 if (fio_flags == FIO_UCSBOM)
1494 {
1495 if (ccname == NULL)
1496 {
1497 /* No BOM detected: retry with next encoding. */
1498 advance_fenc = TRUE;
1499 }
1500 else
1501 {
1502 /* BOM detected: set "fenc" and jump back */
1503 if (fenc_alloced)
1504 vim_free(fenc);
1505 fenc = ccname;
1506 fenc_alloced = FALSE;
1507 }
1508 /* retry reading without getting new bytes or rewinding */
1509 skip_read = TRUE;
1510 goto retry;
1511 }
1512 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001513
1514 /* Include not converted bytes. */
1515 ptr -= conv_restlen;
1516 size += conv_restlen;
1517 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518#endif
1519 /*
1520 * Break here for a read error or end-of-file.
1521 */
1522 if (size <= 0)
1523 break;
1524
1525#ifdef FEAT_MBYTE
1526
Bram Moolenaar071d4272004-06-13 20:20:40 +00001527# ifdef USE_ICONV
1528 if (iconv_fd != (iconv_t)-1)
1529 {
1530 /*
1531 * Attempt conversion of the read bytes to 'encoding' using
1532 * iconv().
1533 */
1534 const char *fromp;
1535 char *top;
1536 size_t from_size;
1537 size_t to_size;
1538
1539 fromp = (char *)ptr;
1540 from_size = size;
1541 ptr += size;
1542 top = (char *)ptr;
1543 to_size = real_size - size;
1544
1545 /*
1546 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001547 * another conversion. Except for when there is no
1548 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001549 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001550 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1551 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1553 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001554 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001555 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001556 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001557 if (conv_error == 0)
1558 conv_error = readfile_linenr(linecnt,
1559 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001560
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001561 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001562 ++fromp;
1563 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001564 if (bad_char_behavior == BAD_KEEP)
1565 {
1566 *top++ = *(fromp - 1);
1567 --to_size;
1568 }
1569 else if (bad_char_behavior != BAD_DROP)
1570 {
1571 *top++ = bad_char_behavior;
1572 --to_size;
1573 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001574 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575
1576 if (from_size > 0)
1577 {
1578 /* Some remaining characters, keep them for the next
1579 * round. */
1580 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1581 conv_restlen = (int)from_size;
1582 }
1583
1584 /* move the linerest to before the converted characters */
1585 line_start = ptr - linerest;
1586 mch_memmove(line_start, buffer, (size_t)linerest);
1587 size = (long)((char_u *)top - ptr);
1588 }
1589# endif
1590
1591# ifdef WIN3264
1592 if (fio_flags & FIO_CODEPAGE)
1593 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001594 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001595 WCHAR ucs2buf[3];
1596 int ucs2len;
1597 int codepage = FIO_GET_CP(fio_flags);
1598 int bytelen;
1599 int found_bad;
1600 char replstr[2];
1601
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 /*
1603 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001604 * a codepage, using standard MS-Windows functions. This
1605 * requires two steps:
1606 * 1. convert from 'fileencoding' to ucs-2
1607 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001608 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001609 * Because there may be illegal bytes AND an incomplete byte
1610 * sequence at the end, we may have to do the conversion one
1611 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001612 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001613
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001614 /* Replacement string for WideCharToMultiByte(). */
1615 if (bad_char_behavior > 0)
1616 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001618 replstr[0] = '?';
1619 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620
1621 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001622 * Move the bytes to the end of the buffer, so that we have
1623 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001625 src = ptr + real_size - size;
1626 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001628 /*
1629 * Do the conversion.
1630 */
1631 dst = ptr;
1632 size = size;
1633 while (size > 0)
1634 {
1635 found_bad = FALSE;
1636
1637# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1638 if (codepage == CP_UTF8)
1639 {
1640 /* Handle CP_UTF8 input ourselves to be able to handle
1641 * trailing bytes properly.
1642 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001643 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001644 if (bytelen > size)
1645 {
1646 /* Only got some bytes of a character. Normally
1647 * it's put in "conv_rest", but if it's too long
1648 * deal with it as if they were illegal bytes. */
1649 if (bytelen <= CONV_RESTLEN)
1650 break;
1651
1652 /* weird overlong byte sequence */
1653 bytelen = size;
1654 found_bad = TRUE;
1655 }
1656 else
1657 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001658 int u8c = utf_ptr2char(src);
1659
Bram Moolenaar86e01082005-12-29 22:45:34 +00001660 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001661 found_bad = TRUE;
1662 ucs2buf[0] = u8c;
1663 ucs2len = 1;
1664 }
1665 }
1666 else
1667# endif
1668 {
1669 /* We don't know how long the byte sequence is, try
1670 * from one to three bytes. */
1671 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1672 ++bytelen)
1673 {
1674 ucs2len = MultiByteToWideChar(codepage,
1675 MB_ERR_INVALID_CHARS,
1676 (LPCSTR)src, bytelen,
1677 ucs2buf, 3);
1678 if (ucs2len > 0)
1679 break;
1680 }
1681 if (ucs2len == 0)
1682 {
1683 /* If we have only one byte then it's probably an
1684 * incomplete byte sequence. Otherwise discard
1685 * one byte as a bad character. */
1686 if (size == 1)
1687 break;
1688 found_bad = TRUE;
1689 bytelen = 1;
1690 }
1691 }
1692
1693 if (!found_bad)
1694 {
1695 int i;
1696
1697 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1698 if (enc_utf8)
1699 {
1700 /* From UCS-2 to UTF-8. Cannot fail. */
1701 for (i = 0; i < ucs2len; ++i)
1702 dst += utf_char2bytes(ucs2buf[i], dst);
1703 }
1704 else
1705 {
1706 BOOL bad = FALSE;
1707 int dstlen;
1708
1709 /* From UCS-2 to "enc_codepage". If the
1710 * conversion uses the default character "?",
1711 * the data doesn't fit in this encoding. */
1712 dstlen = WideCharToMultiByte(enc_codepage, 0,
1713 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001714 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001715 replstr, &bad);
1716 if (bad)
1717 found_bad = TRUE;
1718 else
1719 dst += dstlen;
1720 }
1721 }
1722
1723 if (found_bad)
1724 {
1725 /* Deal with bytes we can't convert. */
1726 if (can_retry)
1727 goto rewind_retry;
1728 if (conv_error == 0)
1729 conv_error = readfile_linenr(linecnt, ptr, dst);
1730 if (bad_char_behavior != BAD_DROP)
1731 {
1732 if (bad_char_behavior == BAD_KEEP)
1733 {
1734 mch_memmove(dst, src, bytelen);
1735 dst += bytelen;
1736 }
1737 else
1738 *dst++ = bad_char_behavior;
1739 }
1740 }
1741
1742 src += bytelen;
1743 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001744 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001745
1746 if (size > 0)
1747 {
1748 /* An incomplete byte sequence remaining. */
1749 mch_memmove(conv_rest, src, size);
1750 conv_restlen = size;
1751 }
1752
1753 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001754 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001755 }
1756 else
1757# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001758# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001759 if (fio_flags & FIO_MACROMAN)
1760 {
1761 /*
1762 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001763 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001764 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001765 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001766 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 }
1768 else
1769# endif
1770 if (fio_flags != 0)
1771 {
1772 int u8c;
1773 char_u *dest;
1774 char_u *tail = NULL;
1775
1776 /*
1777 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1778 * "enc_utf8" not set: Convert Unicode to Latin1.
1779 * Go from end to start through the buffer, because the number
1780 * of bytes may increase.
1781 * "dest" points to after where the UTF-8 bytes go, "p" points
1782 * to after the next character to convert.
1783 */
1784 dest = ptr + real_size;
1785 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1786 {
1787 p = ptr + size;
1788 if (fio_flags == FIO_UTF8)
1789 {
1790 /* Check for a trailing incomplete UTF-8 sequence */
1791 tail = ptr + size - 1;
1792 while (tail > ptr && (*tail & 0xc0) == 0x80)
1793 --tail;
1794 if (tail + utf_byte2len(*tail) <= ptr + size)
1795 tail = NULL;
1796 else
1797 p = tail;
1798 }
1799 }
1800 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1801 {
1802 /* Check for a trailing byte */
1803 p = ptr + (size & ~1);
1804 if (size & 1)
1805 tail = p;
1806 if ((fio_flags & FIO_UTF16) && p > ptr)
1807 {
1808 /* Check for a trailing leading word */
1809 if (fio_flags & FIO_ENDIAN_L)
1810 {
1811 u8c = (*--p << 8);
1812 u8c += *--p;
1813 }
1814 else
1815 {
1816 u8c = *--p;
1817 u8c += (*--p << 8);
1818 }
1819 if (u8c >= 0xd800 && u8c <= 0xdbff)
1820 tail = p;
1821 else
1822 p += 2;
1823 }
1824 }
1825 else /* FIO_UCS4 */
1826 {
1827 /* Check for trailing 1, 2 or 3 bytes */
1828 p = ptr + (size & ~3);
1829 if (size & 3)
1830 tail = p;
1831 }
1832
1833 /* If there is a trailing incomplete sequence move it to
1834 * conv_rest[]. */
1835 if (tail != NULL)
1836 {
1837 conv_restlen = (int)((ptr + size) - tail);
1838 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1839 size -= conv_restlen;
1840 }
1841
1842
1843 while (p > ptr)
1844 {
1845 if (fio_flags & FIO_LATIN1)
1846 u8c = *--p;
1847 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1848 {
1849 if (fio_flags & FIO_ENDIAN_L)
1850 {
1851 u8c = (*--p << 8);
1852 u8c += *--p;
1853 }
1854 else
1855 {
1856 u8c = *--p;
1857 u8c += (*--p << 8);
1858 }
1859 if ((fio_flags & FIO_UTF16)
1860 && u8c >= 0xdc00 && u8c <= 0xdfff)
1861 {
1862 int u16c;
1863
1864 if (p == ptr)
1865 {
1866 /* Missing leading word. */
1867 if (can_retry)
1868 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001869 if (conv_error == 0)
1870 conv_error = readfile_linenr(linecnt,
1871 ptr, p);
1872 if (bad_char_behavior == BAD_DROP)
1873 continue;
1874 if (bad_char_behavior != BAD_KEEP)
1875 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001876 }
1877
1878 /* found second word of double-word, get the first
1879 * word and compute the resulting character */
1880 if (fio_flags & FIO_ENDIAN_L)
1881 {
1882 u16c = (*--p << 8);
1883 u16c += *--p;
1884 }
1885 else
1886 {
1887 u16c = *--p;
1888 u16c += (*--p << 8);
1889 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001890 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1891 + (u8c & 0x3ff);
1892
Bram Moolenaar071d4272004-06-13 20:20:40 +00001893 /* Check if the word is indeed a leading word. */
1894 if (u16c < 0xd800 || u16c > 0xdbff)
1895 {
1896 if (can_retry)
1897 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001898 if (conv_error == 0)
1899 conv_error = readfile_linenr(linecnt,
1900 ptr, p);
1901 if (bad_char_behavior == BAD_DROP)
1902 continue;
1903 if (bad_char_behavior != BAD_KEEP)
1904 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001906 }
1907 }
1908 else if (fio_flags & FIO_UCS4)
1909 {
1910 if (fio_flags & FIO_ENDIAN_L)
1911 {
1912 u8c = (*--p << 24);
1913 u8c += (*--p << 16);
1914 u8c += (*--p << 8);
1915 u8c += *--p;
1916 }
1917 else /* big endian */
1918 {
1919 u8c = *--p;
1920 u8c += (*--p << 8);
1921 u8c += (*--p << 16);
1922 u8c += (*--p << 24);
1923 }
1924 }
1925 else /* UTF-8 */
1926 {
1927 if (*--p < 0x80)
1928 u8c = *p;
1929 else
1930 {
1931 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001932 p -= len;
1933 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001934 if (len == 0)
1935 {
1936 /* Not a valid UTF-8 character, retry with
1937 * another fenc when possible, otherwise just
1938 * report the error. */
1939 if (can_retry)
1940 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001941 if (conv_error == 0)
1942 conv_error = readfile_linenr(linecnt,
1943 ptr, p);
1944 if (bad_char_behavior == BAD_DROP)
1945 continue;
1946 if (bad_char_behavior != BAD_KEEP)
1947 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001948 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001949 }
1950 }
1951 if (enc_utf8) /* produce UTF-8 */
1952 {
1953 dest -= utf_char2len(u8c);
1954 (void)utf_char2bytes(u8c, dest);
1955 }
1956 else /* produce Latin1 */
1957 {
1958 --dest;
1959 if (u8c >= 0x100)
1960 {
1961 /* character doesn't fit in latin1, retry with
1962 * another fenc when possible, otherwise just
1963 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001964 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001966 if (conv_error == 0)
1967 conv_error = readfile_linenr(linecnt, ptr, p);
1968 if (bad_char_behavior == BAD_DROP)
1969 ++dest;
1970 else if (bad_char_behavior == BAD_KEEP)
1971 *dest = u8c;
1972 else if (eap != NULL && eap->bad_char != 0)
1973 *dest = bad_char_behavior;
1974 else
1975 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001976 }
1977 else
1978 *dest = u8c;
1979 }
1980 }
1981
1982 /* move the linerest to before the converted characters */
1983 line_start = dest - linerest;
1984 mch_memmove(line_start, buffer, (size_t)linerest);
1985 size = (long)((ptr + real_size) - dest);
1986 ptr = dest;
1987 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001988 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001989 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001990 int incomplete_tail = FALSE;
1991
1992 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1993 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001995 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001996 int l;
1997
1998 if (todo <= 0)
1999 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002000 if (*p >= 0x80)
2001 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002 /* A length of 1 means it's an illegal byte. Accept
2003 * an incomplete character at the end though, the next
2004 * read() will get the next bytes, we'll check it
2005 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002006 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002007 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002009 /* Avoid retrying with a different encoding when
2010 * a truncated file is more likely, or attempting
2011 * to read the rest of an incomplete sequence when
2012 * we have already done so. */
2013 if (p > ptr || filesize > 0)
2014 incomplete_tail = TRUE;
2015 /* Incomplete byte sequence, move it to conv_rest[]
2016 * and try to read the rest of it, unless we've
2017 * already done so. */
2018 if (p > ptr)
2019 {
2020 conv_restlen = todo;
2021 mch_memmove(conv_rest, p, conv_restlen);
2022 size -= conv_restlen;
2023 break;
2024 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002025 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002026 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002027 {
2028 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002029 * do that, unless at EOF where a truncated
2030 * file is more likely than a conversion error. */
2031 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002032 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002033# ifdef USE_ICONV
2034 /* When we did a conversion report an error. */
2035 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2036 conv_error = readfile_linenr(linecnt, ptr, p);
2037# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002038 /* Remember the first linenr with an illegal byte */
2039 if (conv_error == 0 && illegal_byte == 0)
2040 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002041
2042 /* Drop, keep or replace the bad byte. */
2043 if (bad_char_behavior == BAD_DROP)
2044 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002045 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002046 --p;
2047 --size;
2048 }
2049 else if (bad_char_behavior != BAD_KEEP)
2050 *p = bad_char_behavior;
2051 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002052 else
2053 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002054 }
2055 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002056 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 {
2058 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002059rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002060 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002062 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2063 /* iconv() failed, try 'charconvert' */
2064 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 else
2066# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002067 /* use next item from 'fileencodings' */
2068 advance_fenc = TRUE;
2069 file_rewind = TRUE;
2070 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002071 }
2072 }
2073#endif
2074
2075 /* count the number of characters (after conversion!) */
2076 filesize += size;
2077
2078 /*
2079 * when reading the first part of a file: guess EOL type
2080 */
2081 if (fileformat == EOL_UNKNOWN)
2082 {
2083 /* First try finding a NL, for Dos and Unix */
2084 if (try_dos || try_unix)
2085 {
2086 for (p = ptr; p < ptr + size; ++p)
2087 {
2088 if (*p == NL)
2089 {
2090 if (!try_unix
2091 || (try_dos && p > ptr && p[-1] == CAR))
2092 fileformat = EOL_DOS;
2093 else
2094 fileformat = EOL_UNIX;
2095 break;
2096 }
2097 }
2098
2099 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2100 if (fileformat == EOL_UNIX && try_mac)
2101 {
2102 /* Need to reset the counters when retrying fenc. */
2103 try_mac = 1;
2104 try_unix = 1;
2105 for (; p >= ptr && *p != CAR; p--)
2106 ;
2107 if (p >= ptr)
2108 {
2109 for (p = ptr; p < ptr + size; ++p)
2110 {
2111 if (*p == NL)
2112 try_unix++;
2113 else if (*p == CAR)
2114 try_mac++;
2115 }
2116 if (try_mac > try_unix)
2117 fileformat = EOL_MAC;
2118 }
2119 }
2120 }
2121
2122 /* No NL found: may use Mac format */
2123 if (fileformat == EOL_UNKNOWN && try_mac)
2124 fileformat = EOL_MAC;
2125
2126 /* Still nothing found? Use first format in 'ffs' */
2127 if (fileformat == EOL_UNKNOWN)
2128 fileformat = default_fileformat();
2129
2130 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002131 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132 set_fileformat(fileformat, OPT_LOCAL);
2133 }
2134 }
2135
2136 /*
2137 * This loop is executed once for every character read.
2138 * Keep it fast!
2139 */
2140 if (fileformat == EOL_MAC)
2141 {
2142 --ptr;
2143 while (++ptr, --size >= 0)
2144 {
2145 /* catch most common case first */
2146 if ((c = *ptr) != NUL && c != CAR && c != NL)
2147 continue;
2148 if (c == NUL)
2149 *ptr = NL; /* NULs are replaced by newlines! */
2150 else if (c == NL)
2151 *ptr = CAR; /* NLs are replaced by CRs! */
2152 else
2153 {
2154 if (skip_count == 0)
2155 {
2156 *ptr = NUL; /* end of line */
2157 len = (colnr_T) (ptr - line_start + 1);
2158 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2159 {
2160 error = TRUE;
2161 break;
2162 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002163#ifdef FEAT_PERSISTENT_UNDO
2164 if (read_undo_file)
2165 sha256_update(&sha_ctx, line_start, len);
2166#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002167 ++lnum;
2168 if (--read_count == 0)
2169 {
2170 error = TRUE; /* break loop */
2171 line_start = ptr; /* nothing left to write */
2172 break;
2173 }
2174 }
2175 else
2176 --skip_count;
2177 line_start = ptr + 1;
2178 }
2179 }
2180 }
2181 else
2182 {
2183 --ptr;
2184 while (++ptr, --size >= 0)
2185 {
2186 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2187 continue;
2188 if (c == NUL)
2189 *ptr = NL; /* NULs are replaced by newlines! */
2190 else
2191 {
2192 if (skip_count == 0)
2193 {
2194 *ptr = NUL; /* end of line */
2195 len = (colnr_T)(ptr - line_start + 1);
2196 if (fileformat == EOL_DOS)
2197 {
2198 if (ptr[-1] == CAR) /* remove CR */
2199 {
2200 ptr[-1] = NUL;
2201 --len;
2202 }
2203 /*
2204 * Reading in Dos format, but no CR-LF found!
2205 * When 'fileformats' includes "unix", delete all
2206 * the lines read so far and start all over again.
2207 * Otherwise give an error message later.
2208 */
2209 else if (ff_error != EOL_DOS)
2210 {
2211 if ( try_unix
2212 && !read_stdin
2213 && (read_buffer
2214 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2215 {
2216 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002217 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218 set_fileformat(EOL_UNIX, OPT_LOCAL);
2219 file_rewind = TRUE;
2220 keep_fileformat = TRUE;
2221 goto retry;
2222 }
2223 ff_error = EOL_DOS;
2224 }
2225 }
2226 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2227 {
2228 error = TRUE;
2229 break;
2230 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002231#ifdef FEAT_PERSISTENT_UNDO
2232 if (read_undo_file)
2233 sha256_update(&sha_ctx, line_start, len);
2234#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002235 ++lnum;
2236 if (--read_count == 0)
2237 {
2238 error = TRUE; /* break loop */
2239 line_start = ptr; /* nothing left to write */
2240 break;
2241 }
2242 }
2243 else
2244 --skip_count;
2245 line_start = ptr + 1;
2246 }
2247 }
2248 }
2249 linerest = (long)(ptr - line_start);
2250 ui_breakcheck();
2251 }
2252
2253failed:
2254 /* not an error, max. number of lines reached */
2255 if (error && read_count == 0)
2256 error = FALSE;
2257
2258 /*
2259 * If we get EOF in the middle of a line, note the fact and
2260 * complete the line ourselves.
2261 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2262 */
2263 if (!error
2264 && !got_int
2265 && linerest != 0
2266 && !(!curbuf->b_p_bin
2267 && fileformat == EOL_DOS
2268 && *line_start == Ctrl_Z
2269 && ptr == line_start + 1))
2270 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002271 /* remember for when writing */
2272 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 curbuf->b_p_eol = FALSE;
2274 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002275 len = (colnr_T)(ptr - line_start + 1);
2276 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002277 error = TRUE;
2278 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002279 {
2280#ifdef FEAT_PERSISTENT_UNDO
2281 if (read_undo_file)
2282 sha256_update(&sha_ctx, line_start, len);
2283#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002284 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002285 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002286 }
2287
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002288 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289 save_file_ff(curbuf); /* remember the current file format */
2290
2291#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002292 if (cryptkey != NULL)
2293 {
2294 crypt_pop_state();
2295 if (cryptkey != curbuf->b_p_key)
2296 free_crypt_key(cryptkey);
2297 /* don't set cryptkey to NULL, it's used below as a flag that
2298 * encryption was used */
2299 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300#endif
2301
2302#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002303 /* If editing a new file: set 'fenc' for the current buffer.
2304 * Also for ":read ++edit file". */
2305 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002306 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002307 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308 if (fenc_alloced)
2309 vim_free(fenc);
2310# ifdef USE_ICONV
2311 if (iconv_fd != (iconv_t)-1)
2312 {
2313 iconv_close(iconv_fd);
2314 iconv_fd = (iconv_t)-1;
2315 }
2316# endif
2317#endif
2318
2319 if (!read_buffer && !read_stdin)
2320 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002321#ifdef HAVE_FD_CLOEXEC
2322 else
2323 {
2324 int fdflags = fcntl(fd, F_GETFD);
2325 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2326 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2327 }
2328#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002329 vim_free(buffer);
2330
2331#ifdef HAVE_DUP
2332 if (read_stdin)
2333 {
2334 /* Use stderr for stdin, makes shell commands work. */
2335 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002336 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 }
2338#endif
2339
2340#ifdef FEAT_MBYTE
2341 if (tmpname != NULL)
2342 {
2343 mch_remove(tmpname); /* delete converted file */
2344 vim_free(tmpname);
2345 }
2346#endif
2347 --no_wait_return; /* may wait for return now */
2348
2349 /*
2350 * In recovery mode everything but autocommands is skipped.
2351 */
2352 if (!recoverymode)
2353 {
2354 /* need to delete the last line, which comes from the empty buffer */
2355 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2356 {
2357#ifdef FEAT_NETBEANS_INTG
2358 netbeansFireChanges = 0;
2359#endif
2360 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2361#ifdef FEAT_NETBEANS_INTG
2362 netbeansFireChanges = 1;
2363#endif
2364 --linecnt;
2365 }
2366 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2367 if (filesize == 0)
2368 linecnt = 0;
2369 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002370 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002371 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002372#ifdef FEAT_DIFF
2373 /* After reading the text into the buffer the diff info needs to
2374 * be updated. */
2375 diff_invalidate(curbuf);
2376#endif
2377#ifdef FEAT_FOLDING
2378 /* All folds in the window are invalid now. Mark them for update
2379 * before triggering autocommands. */
2380 foldUpdateAll(curwin);
2381#endif
2382 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002383 else if (linecnt) /* appended at least one line */
2384 appended_lines_mark(from, linecnt);
2385
Bram Moolenaar071d4272004-06-13 20:20:40 +00002386#ifndef ALWAYS_USE_GUI
2387 /*
2388 * If we were reading from the same terminal as where messages go,
2389 * the screen will have been messed up.
2390 * Switch on raw mode now and clear the screen.
2391 */
2392 if (read_stdin)
2393 {
2394 settmode(TMODE_RAW); /* set to raw mode */
2395 starttermcap();
2396 screenclear();
2397 }
2398#endif
2399
2400 if (got_int)
2401 {
2402 if (!(flags & READ_DUMMY))
2403 {
2404 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2405 if (newfile)
2406 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2407 }
2408 msg_scroll = msg_save;
2409#ifdef FEAT_VIMINFO
2410 check_marks_read();
2411#endif
2412 return OK; /* an interrupt isn't really an error */
2413 }
2414
2415 if (!filtering && !(flags & READ_DUMMY))
2416 {
2417 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2418 c = FALSE;
2419
2420#ifdef UNIX
2421# ifdef S_ISFIFO
2422 if (S_ISFIFO(perm)) /* fifo or socket */
2423 {
2424 STRCAT(IObuff, _("[fifo/socket]"));
2425 c = TRUE;
2426 }
2427# else
2428# ifdef S_IFIFO
2429 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2430 {
2431 STRCAT(IObuff, _("[fifo]"));
2432 c = TRUE;
2433 }
2434# endif
2435# ifdef S_IFSOCK
2436 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2437 {
2438 STRCAT(IObuff, _("[socket]"));
2439 c = TRUE;
2440 }
2441# endif
2442# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002443# ifdef OPEN_CHR_FILES
2444 if (S_ISCHR(perm)) /* or character special */
2445 {
2446 STRCAT(IObuff, _("[character special]"));
2447 c = TRUE;
2448 }
2449# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450#endif
2451 if (curbuf->b_p_ro)
2452 {
2453 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2454 c = TRUE;
2455 }
2456 if (read_no_eol_lnum)
2457 {
2458 msg_add_eol();
2459 c = TRUE;
2460 }
2461 if (ff_error == EOL_DOS)
2462 {
2463 STRCAT(IObuff, _("[CR missing]"));
2464 c = TRUE;
2465 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002466 if (split)
2467 {
2468 STRCAT(IObuff, _("[long lines split]"));
2469 c = TRUE;
2470 }
2471#ifdef FEAT_MBYTE
2472 if (notconverted)
2473 {
2474 STRCAT(IObuff, _("[NOT converted]"));
2475 c = TRUE;
2476 }
2477 else if (converted)
2478 {
2479 STRCAT(IObuff, _("[converted]"));
2480 c = TRUE;
2481 }
2482#endif
2483#ifdef FEAT_CRYPT
2484 if (cryptkey != NULL)
2485 {
2486 STRCAT(IObuff, _("[crypted]"));
2487 c = TRUE;
2488 }
2489#endif
2490#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002491 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002492 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002493 sprintf((char *)IObuff + STRLEN(IObuff),
2494 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 c = TRUE;
2496 }
2497 else if (illegal_byte > 0)
2498 {
2499 sprintf((char *)IObuff + STRLEN(IObuff),
2500 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2501 c = TRUE;
2502 }
2503 else
2504#endif
2505 if (error)
2506 {
2507 STRCAT(IObuff, _("[READ ERRORS]"));
2508 c = TRUE;
2509 }
2510 if (msg_add_fileformat(fileformat))
2511 c = TRUE;
2512#ifdef FEAT_CRYPT
2513 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002514 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002515 - CRYPT_MAGIC_LEN
2516 - crypt_salt_len[use_crypt_method]
2517 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002518 else
2519#endif
2520 msg_add_lines(c, (long)linecnt, filesize);
2521
2522 vim_free(keep_msg);
2523 keep_msg = NULL;
2524 msg_scrolled_ign = TRUE;
2525#ifdef ALWAYS_USE_GUI
2526 /* Don't show the message when reading stdin, it would end up in a
2527 * message box (which might be shown when exiting!) */
2528 if (read_stdin || read_buffer)
2529 p = msg_may_trunc(FALSE, IObuff);
2530 else
2531#endif
2532 p = msg_trunc_attr(IObuff, FALSE, 0);
2533 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002534 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002535 /* Need to repeat the message after redrawing when:
2536 * - When reading from stdin (the screen will be cleared next).
2537 * - When restart_edit is set (otherwise there will be a delay
2538 * before redrawing).
2539 * - When the screen was scrolled but there is no wait-return
2540 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002541 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002542 msg_scrolled_ign = FALSE;
2543 }
2544
2545 /* with errors writing the file requires ":w!" */
2546 if (newfile && (error
2547#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002548 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002549 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550#endif
2551 ))
2552 curbuf->b_p_ro = TRUE;
2553
2554 u_clearline(); /* cannot use "U" command after adding lines */
2555
2556 /*
2557 * In Ex mode: cursor at last new line.
2558 * Otherwise: cursor at first new line.
2559 */
2560 if (exmode_active)
2561 curwin->w_cursor.lnum = from + linecnt;
2562 else
2563 curwin->w_cursor.lnum = from + 1;
2564 check_cursor_lnum();
2565 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2566
2567 /*
2568 * Set '[ and '] marks to the newly read lines.
2569 */
2570 curbuf->b_op_start.lnum = from + 1;
2571 curbuf->b_op_start.col = 0;
2572 curbuf->b_op_end.lnum = from + linecnt;
2573 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002574
2575#ifdef WIN32
2576 /*
2577 * Work around a weird problem: When a file has two links (only
2578 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002579 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002580 * It's correct again after reading the file, thus reset the timestamp
2581 * here.
2582 */
2583 if (newfile && !read_stdin && !read_buffer
2584 && mch_stat((char *)fname, &st) >= 0)
2585 {
2586 buf_store_time(curbuf, &st, fname);
2587 curbuf->b_mtime_read = curbuf->b_mtime;
2588 }
2589#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 }
2591 msg_scroll = msg_save;
2592
2593#ifdef FEAT_VIMINFO
2594 /*
2595 * Get the marks before executing autocommands, so they can be used there.
2596 */
2597 check_marks_read();
2598#endif
2599
Bram Moolenaar071d4272004-06-13 20:20:40 +00002600 /*
2601 * Trick: We remember if the last line of the read didn't have
2602 * an eol for when writing it again. This is required for
2603 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2604 */
2605 write_no_eol_lnum = read_no_eol_lnum;
2606
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002607 /* When reloading a buffer put the cursor at the first line that is
2608 * different. */
2609 if (flags & READ_KEEP_UNDO)
2610 u_find_first_changed();
2611
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002612#ifdef FEAT_PERSISTENT_UNDO
2613 /*
2614 * When opening a new file locate undo info and read it.
2615 */
2616 if (read_undo_file)
2617 {
2618 char_u hash[UNDO_HASH_SIZE];
2619
2620 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002621 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002622 }
2623#endif
2624
Bram Moolenaardf177f62005-02-22 08:39:57 +00002625#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626 if (!read_stdin && !read_buffer)
2627 {
2628 int m = msg_scroll;
2629 int n = msg_scrolled;
2630
2631 /* Save the fileformat now, otherwise the buffer will be considered
2632 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002633 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 save_file_ff(curbuf);
2635
2636 /*
2637 * The output from the autocommands should not overwrite anything and
2638 * should not be overwritten: Set msg_scroll, restore its value if no
2639 * output was done.
2640 */
2641 msg_scroll = TRUE;
2642 if (filtering)
2643 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2644 FALSE, curbuf, eap);
2645 else if (newfile)
2646 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2647 FALSE, curbuf, eap);
2648 else
2649 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2650 FALSE, NULL, eap);
2651 if (msg_scrolled == n)
2652 msg_scroll = m;
2653#ifdef FEAT_EVAL
2654 if (aborting()) /* autocmds may abort script processing */
2655 return FAIL;
2656#endif
2657 }
2658#endif
2659
2660 if (recoverymode && error)
2661 return FAIL;
2662 return OK;
2663}
2664
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002665#ifdef OPEN_CHR_FILES
2666/*
2667 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2668 * which is the name of files used for process substitution output by
2669 * some shells on some operating systems, e.g., bash on SunOS.
2670 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2671 */
2672 static int
2673is_dev_fd_file(fname)
2674 char_u *fname;
2675{
2676 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2677 && VIM_ISDIGIT(fname[8])
2678 && *skipdigits(fname + 9) == NUL
2679 && (fname[9] != NUL
2680 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2681}
2682#endif
2683
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002684#ifdef FEAT_MBYTE
2685
2686/*
2687 * From the current line count and characters read after that, estimate the
2688 * line number where we are now.
2689 * Used for error messages that include a line number.
2690 */
2691 static linenr_T
2692readfile_linenr(linecnt, p, endp)
2693 linenr_T linecnt; /* line count before reading more bytes */
2694 char_u *p; /* start of more bytes read */
2695 char_u *endp; /* end of more bytes read */
2696{
2697 char_u *s;
2698 linenr_T lnum;
2699
2700 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2701 for (s = p; s < endp; ++s)
2702 if (*s == '\n')
2703 ++lnum;
2704 return lnum;
2705}
2706#endif
2707
Bram Moolenaar071d4272004-06-13 20:20:40 +00002708/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002709 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2710 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002711 * Returns OK or FAIL.
2712 */
2713 int
2714prep_exarg(eap, buf)
2715 exarg_T *eap;
2716 buf_T *buf;
2717{
2718 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2719#ifdef FEAT_MBYTE
2720 + STRLEN(buf->b_p_fenc)
2721#endif
2722 + 15));
2723 if (eap->cmd == NULL)
2724 return FAIL;
2725
2726#ifdef FEAT_MBYTE
2727 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2728 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002729 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002730#else
2731 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2732#endif
2733 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002734
2735 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002736 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002737 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738 return OK;
2739}
2740
2741#ifdef FEAT_MBYTE
2742/*
2743 * Find next fileencoding to use from 'fileencodings'.
2744 * "pp" points to fenc_next. It's advanced to the next item.
2745 * When there are no more items, an empty string is returned and *pp is set to
2746 * NULL.
2747 * When *pp is not set to NULL, the result is in allocated memory.
2748 */
2749 static char_u *
2750next_fenc(pp)
2751 char_u **pp;
2752{
2753 char_u *p;
2754 char_u *r;
2755
2756 if (**pp == NUL)
2757 {
2758 *pp = NULL;
2759 return (char_u *)"";
2760 }
2761 p = vim_strchr(*pp, ',');
2762 if (p == NULL)
2763 {
2764 r = enc_canonize(*pp);
2765 *pp += STRLEN(*pp);
2766 }
2767 else
2768 {
2769 r = vim_strnsave(*pp, (int)(p - *pp));
2770 *pp = p + 1;
2771 if (r != NULL)
2772 {
2773 p = enc_canonize(r);
2774 vim_free(r);
2775 r = p;
2776 }
2777 }
2778 if (r == NULL) /* out of memory */
2779 {
2780 r = (char_u *)"";
2781 *pp = NULL;
2782 }
2783 return r;
2784}
2785
2786# ifdef FEAT_EVAL
2787/*
2788 * Convert a file with the 'charconvert' expression.
2789 * This closes the file which is to be read, converts it and opens the
2790 * resulting file for reading.
2791 * Returns name of the resulting converted file (the caller should delete it
2792 * after reading it).
2793 * Returns NULL if the conversion failed ("*fdp" is not set) .
2794 */
2795 static char_u *
2796readfile_charconvert(fname, fenc, fdp)
2797 char_u *fname; /* name of input file */
2798 char_u *fenc; /* converted from */
2799 int *fdp; /* in/out: file descriptor of file */
2800{
2801 char_u *tmpname;
2802 char_u *errmsg = NULL;
2803
2804 tmpname = vim_tempname('r');
2805 if (tmpname == NULL)
2806 errmsg = (char_u *)_("Can't find temp file for conversion");
2807 else
2808 {
2809 close(*fdp); /* close the input file, ignore errors */
2810 *fdp = -1;
2811 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2812 fname, tmpname) == FAIL)
2813 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2814 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2815 O_RDONLY | O_EXTRA, 0)) < 0)
2816 errmsg = (char_u *)_("can't read output of 'charconvert'");
2817 }
2818
2819 if (errmsg != NULL)
2820 {
2821 /* Don't use emsg(), it breaks mappings, the retry with
2822 * another type of conversion might still work. */
2823 MSG(errmsg);
2824 if (tmpname != NULL)
2825 {
2826 mch_remove(tmpname); /* delete converted file */
2827 vim_free(tmpname);
2828 tmpname = NULL;
2829 }
2830 }
2831
2832 /* If the input file is closed, open it (caller should check for error). */
2833 if (*fdp < 0)
2834 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2835
2836 return tmpname;
2837}
2838# endif
2839
2840#endif
2841
2842#ifdef FEAT_VIMINFO
2843/*
2844 * Read marks for the current buffer from the viminfo file, when we support
2845 * buffer marks and the buffer has a name.
2846 */
2847 static void
2848check_marks_read()
2849{
2850 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2851 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002852 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002853
2854 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2855 * the ' parameter after opening a buffer. */
2856 curbuf->b_marks_read = TRUE;
2857}
2858#endif
2859
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002860#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002862 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2863 * start of the file.
2864 * Returns -1 when no encryption used.
2865 */
2866 static int
Bram Moolenaar49771f42010-07-20 17:32:38 +02002867crypt_method_from_magic(ptr, len)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002868 char *ptr;
2869 int len;
2870{
2871 int i;
2872
2873 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2874 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002875 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002876 continue;
2877 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2878 return i;
2879 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002880
Bram Moolenaar442b4222010-05-24 21:34:22 +02002881 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002882 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2883 EMSG(_("E821: File is encrypted with unknown method"));
2884
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002885 return -1;
2886}
2887
2888/*
2889 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002890 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2891 * *filesizep are updated.
2892 * Return the (new) encryption key, NULL for no encryption.
2893 */
2894 static char_u *
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002895check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002896 char_u *cryptkey; /* previous encryption key or NULL */
2897 char_u *ptr; /* pointer to read bytes */
2898 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002899 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002900 int newfile; /* editing a new buffer */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002901 char_u *fname; /* file name to display */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002902 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002903{
Bram Moolenaar49771f42010-07-20 17:32:38 +02002904 int method = crypt_method_from_magic((char *)ptr, *sizep);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002905
2906 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002907 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02002908 set_crypt_method(curbuf, method);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002909 if (method > 0)
2910 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002911 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002912 {
2913 if (*curbuf->b_p_key)
2914 cryptkey = curbuf->b_p_key;
2915 else
2916 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002917 /* When newfile is TRUE, store the typed key in the 'key'
2918 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002919 * Don't ask for the key again when first time Enter was hit.
2920 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002921 smsg((char_u *)_(need_key_msg), fname);
2922 msg_scroll = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002923 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002924 *did_ask = TRUE;
2925
Bram Moolenaar071d4272004-06-13 20:20:40 +00002926 /* check if empty key entered */
2927 if (cryptkey != NULL && *cryptkey == NUL)
2928 {
2929 if (cryptkey != curbuf->b_p_key)
2930 vim_free(cryptkey);
2931 cryptkey = NULL;
2932 }
2933 }
2934 }
2935
2936 if (cryptkey != NULL)
2937 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002938 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002939 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002940
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002941 crypt_push_state();
2942 use_crypt_method = method;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002943 if (method == 0)
2944 crypt_init_keys(cryptkey);
2945 else
2946 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002947 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2948 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002949 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950
2951 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002952 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2953 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002954 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len,
2955 (size_t)*sizep);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002956 }
2957 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002958 /* When starting to edit a new file which does not have encryption, clear
2959 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002960 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2962
2963 return cryptkey;
2964}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002965
2966/*
2967 * Check for magic number used for encryption. Applies to the current buffer.
2968 * If found and decryption is possible returns OK;
2969 */
2970 int
2971prepare_crypt_read(fp)
2972 FILE *fp;
2973{
2974 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002975 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2976 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002977
2978 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
2979 return FAIL;
Bram Moolenaar49771f42010-07-20 17:32:38 +02002980 method = crypt_method_from_magic((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02002981 CRYPT_MAGIC_LEN +
Bram Moolenaarcc448b32010-07-14 16:52:17 +02002982 CRYPT_SEED_LEN_MAX +
2983 CRYPT_SALT_LEN_MAX);
Bram Moolenaar49771f42010-07-20 17:32:38 +02002984 if (method < 0 || method != get_crypt_method(curbuf))
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002985 return FAIL;
2986
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002987 crypt_push_state();
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002988 if (method == 0)
2989 crypt_init_keys(curbuf->b_p_key);
2990 else
2991 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002992 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002993 int seed_len = crypt_seed_len[method];
2994
Bram Moolenaar80794b12010-06-13 05:20:42 +02002995 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002996 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002997 bf_key_init(curbuf->b_p_key, buffer, salt_len);
2998 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002999 }
3000 return OK;
3001}
3002
3003/*
3004 * Prepare for writing encrypted bytes for buffer "buf".
3005 * Returns a pointer to an allocated header of length "*lenp".
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003006 * When out of memory returns NULL.
3007 * Otherwise calls crypt_push_state(), call crypt_pop_state() later.
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003008 */
3009 char_u *
3010prepare_crypt_write(buf, lenp)
3011 buf_T *buf;
3012 int *lenp;
3013{
3014 char_u *header;
Bram Moolenaar49771f42010-07-20 17:32:38 +02003015 int seed_len = crypt_seed_len[get_crypt_method(buf)];
3016 int salt_len = crypt_salt_len[get_crypt_method(buf)];
Bram Moolenaar80794b12010-06-13 05:20:42 +02003017 char_u *salt;
3018 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003019
Bram Moolenaar80794b12010-06-13 05:20:42 +02003020 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
3021 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003022 if (header != NULL)
3023 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003024 crypt_push_state();
Bram Moolenaar49771f42010-07-20 17:32:38 +02003025 use_crypt_method = get_crypt_method(buf); /* select zip or blowfish */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003026 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
3027 CRYPT_MAGIC_LEN);
Bram Moolenaar49771f42010-07-20 17:32:38 +02003028 if (use_crypt_method == 0)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003029 crypt_init_keys(buf->b_p_key);
3030 else
3031 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003032 /* Using blowfish, add salt and seed. */
3033 salt = header + CRYPT_MAGIC_LEN;
3034 seed = salt + salt_len;
3035 sha2_seed(salt, salt_len, seed, seed_len);
3036 bf_key_init(buf->b_p_key, salt, salt_len);
3037 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003038 }
3039 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003040 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003041 return header;
3042}
3043
Bram Moolenaar80794b12010-06-13 05:20:42 +02003044#endif /* FEAT_CRYPT */
3045
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046#ifdef UNIX
3047 static void
3048set_file_time(fname, atime, mtime)
3049 char_u *fname;
3050 time_t atime; /* access time */
3051 time_t mtime; /* modification time */
3052{
3053# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3054 struct utimbuf buf;
3055
3056 buf.actime = atime;
3057 buf.modtime = mtime;
3058 (void)utime((char *)fname, &buf);
3059# else
3060# if defined(HAVE_UTIMES)
3061 struct timeval tvp[2];
3062
3063 tvp[0].tv_sec = atime;
3064 tvp[0].tv_usec = 0;
3065 tvp[1].tv_sec = mtime;
3066 tvp[1].tv_usec = 0;
3067# ifdef NeXT
3068 (void)utimes((char *)fname, tvp);
3069# else
3070 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3071# endif
3072# endif
3073# endif
3074}
3075#endif /* UNIX */
3076
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003077#if defined(VMS) && !defined(MIN)
3078/* Older DECC compiler for VAX doesn't define MIN() */
3079# define MIN(a, b) ((a) < (b) ? (a) : (b))
3080#endif
3081
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003083 * Return TRUE if a file appears to be read-only from the file permissions.
3084 */
3085 int
3086check_file_readonly(fname, perm)
3087 char_u *fname; /* full path to file */
3088 int perm; /* known permissions on file */
3089{
3090#ifndef USE_MCH_ACCESS
3091 int fd = 0;
3092#endif
3093
3094 return (
3095#ifdef USE_MCH_ACCESS
3096# ifdef UNIX
3097 (perm & 0222) == 0 ||
3098# endif
3099 mch_access((char *)fname, W_OK)
3100#else
3101 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3102 ? TRUE : (close(fd), FALSE)
3103#endif
3104 );
3105}
3106
3107
3108/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003109 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110 *
3111 * We do our own buffering here because fwrite() is so slow.
3112 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003113 * If "forceit" is true, we don't care for errors when attempting backups.
3114 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003115 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003116 *
3117 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3118 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003119 *
3120 * This function must NOT use NameBuff (because it's called by autowrite()).
3121 *
3122 * return FAIL for failure, OK otherwise
3123 */
3124 int
3125buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3126 reset_changed, filtering)
3127 buf_T *buf;
3128 char_u *fname;
3129 char_u *sfname;
3130 linenr_T start, end;
3131 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3132 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003133 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003134 int forceit;
3135 int reset_changed;
3136 int filtering;
3137{
3138 int fd;
3139 char_u *backup = NULL;
3140 int backup_copy = FALSE; /* copy the original file? */
3141 int dobackup;
3142 char_u *ffname;
3143 char_u *wfname = NULL; /* name of file to write to */
3144 char_u *s;
3145 char_u *ptr;
3146 char_u c;
3147 int len;
3148 linenr_T lnum;
3149 long nchars;
3150 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003151 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003152 char_u *errnum = NULL;
3153 char_u *buffer;
3154 char_u smallbuf[SMBUFSIZE];
3155 char_u *backup_ext;
3156 int bufsize;
3157 long perm; /* file permissions */
3158 int retval = OK;
3159 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3160 int msg_save = msg_scroll;
3161 int overwriting; /* TRUE if writing over original */
3162 int no_eol = FALSE; /* no end-of-line written */
3163 int device = FALSE; /* writing to a device */
3164 struct stat st_old;
3165 int prev_got_int = got_int;
3166 int file_readonly = FALSE; /* overwritten file is read-only */
3167 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3168#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3169 int made_writable = FALSE; /* 'w' bit has been set */
3170#endif
3171 /* writing everything */
3172 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3173#ifdef FEAT_AUTOCMD
3174 linenr_T old_line_count = buf->b_ml.ml_line_count;
3175#endif
3176 int attr;
3177 int fileformat;
3178 int write_bin;
3179 struct bw_info write_info; /* info for buf_write_bytes() */
3180#ifdef FEAT_MBYTE
3181 int converted = FALSE;
3182 int notconverted = FALSE;
3183 char_u *fenc; /* effective 'fileencoding' */
3184 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3185#endif
3186#ifdef HAS_BW_FLAGS
3187 int wb_flags = 0;
3188#endif
3189#ifdef HAVE_ACL
3190 vim_acl_T acl = NULL; /* ACL copied from original file to
3191 backup or new file */
3192#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003193#ifdef FEAT_PERSISTENT_UNDO
3194 int write_undo_file = FALSE;
3195 context_sha256_T sha_ctx;
3196#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197
3198 if (fname == NULL || *fname == NUL) /* safety check */
3199 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003200 if (buf->b_ml.ml_mfp == NULL)
3201 {
3202 /* This can happen during startup when there is a stray "w" in the
3203 * vimrc file. */
3204 EMSG(_(e_emptybuf));
3205 return FAIL;
3206 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003207
3208 /*
3209 * Disallow writing from .exrc and .vimrc in current directory for
3210 * security reasons.
3211 */
3212 if (check_secure())
3213 return FAIL;
3214
3215 /* Avoid a crash for a long name. */
3216 if (STRLEN(fname) >= MAXPATHL)
3217 {
3218 EMSG(_(e_longname));
3219 return FAIL;
3220 }
3221
3222#ifdef FEAT_MBYTE
3223 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3224 write_info.bw_conv_buf = NULL;
3225 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003226 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003227 write_info.bw_restlen = 0;
3228# ifdef USE_ICONV
3229 write_info.bw_iconv_fd = (iconv_t)-1;
3230# endif
3231#endif
3232
Bram Moolenaardf177f62005-02-22 08:39:57 +00003233 /* After writing a file changedtick changes but we don't want to display
3234 * the line. */
3235 ex_no_reprint = TRUE;
3236
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237 /*
3238 * If there is no file name yet, use the one for the written file.
3239 * BF_NOTEDITED is set to reflect this (in case the write fails).
3240 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003241 * Don't do this when appending.
3242 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003243 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003244 if (buf->b_ffname == NULL
3245 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003246 && whole
3247 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003248#ifdef FEAT_QUICKFIX
3249 && !bt_nofile(buf)
3250#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003252 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003253 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3254 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003255 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003256 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003257 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003258 }
3259
3260 if (sfname == NULL)
3261 sfname = fname;
3262 /*
3263 * For Unix: Use the short file name whenever possible.
3264 * Avoids problems with networks and when directory names are changed.
3265 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3266 * another directory, which we don't detect
3267 */
3268 ffname = fname; /* remember full fname */
3269#ifdef UNIX
3270 fname = sfname;
3271#endif
3272
3273 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3274 overwriting = TRUE;
3275 else
3276 overwriting = FALSE;
3277
3278 if (exiting)
3279 settmode(TMODE_COOK); /* when exiting allow typahead now */
3280
3281 ++no_wait_return; /* don't wait for return yet */
3282
3283 /*
3284 * Set '[ and '] marks to the lines to be written.
3285 */
3286 buf->b_op_start.lnum = start;
3287 buf->b_op_start.col = 0;
3288 buf->b_op_end.lnum = end;
3289 buf->b_op_end.col = 0;
3290
3291#ifdef FEAT_AUTOCMD
3292 {
3293 aco_save_T aco;
3294 int buf_ffname = FALSE;
3295 int buf_sfname = FALSE;
3296 int buf_fname_f = FALSE;
3297 int buf_fname_s = FALSE;
3298 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003299 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003300 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003301
3302 /*
3303 * Apply PRE aucocommands.
3304 * Set curbuf to the buffer to be written.
3305 * Careful: The autocommands may call buf_write() recursively!
3306 */
3307 if (ffname == buf->b_ffname)
3308 buf_ffname = TRUE;
3309 if (sfname == buf->b_sfname)
3310 buf_sfname = TRUE;
3311 if (fname == buf->b_ffname)
3312 buf_fname_f = TRUE;
3313 if (fname == buf->b_sfname)
3314 buf_fname_s = TRUE;
3315
3316 /* set curwin/curbuf to buf and save a few things */
3317 aucmd_prepbuf(&aco, buf);
3318
3319 if (append)
3320 {
3321 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3322 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003323 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003324#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003325 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003326 nofile_err = TRUE;
3327 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003328#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003329 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003330 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003331 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003332 }
3333 else if (filtering)
3334 {
3335 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3336 NULL, sfname, FALSE, curbuf, eap);
3337 }
3338 else if (reset_changed && whole)
3339 {
3340 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3341 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003342 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003343#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003344 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003345 nofile_err = TRUE;
3346 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003347#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003348 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003349 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003350 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003351 }
3352 else
3353 {
3354 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3355 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003356 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003357#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003358 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003359 nofile_err = TRUE;
3360 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003361#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003362 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003363 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 }
3366
3367 /* restore curwin/curbuf and a few other things */
3368 aucmd_restbuf(&aco);
3369
3370 /*
3371 * In three situations we return here and don't write the file:
3372 * 1. the autocommands deleted or unloaded the buffer.
3373 * 2. The autocommands abort script processing.
3374 * 3. If one of the "Cmd" autocommands was executed.
3375 */
3376 if (!buf_valid(buf))
3377 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003378 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003379 || did_cmd || nofile_err
3380#ifdef FEAT_EVAL
3381 || aborting()
3382#endif
3383 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003384 {
3385 --no_wait_return;
3386 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003387 if (nofile_err)
3388 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3389
Bram Moolenaar1e015462005-09-25 22:16:38 +00003390 if (nofile_err
3391#ifdef FEAT_EVAL
3392 || aborting()
3393#endif
3394 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003395 /* An aborting error, interrupt or exception in the
3396 * autocommands. */
3397 return FAIL;
3398 if (did_cmd)
3399 {
3400 if (buf == NULL)
3401 /* The buffer was deleted. We assume it was written
3402 * (can't retry anyway). */
3403 return OK;
3404 if (overwriting)
3405 {
3406 /* Assume the buffer was written, update the timestamp. */
3407 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003408 if (append)
3409 buf->b_flags &= ~BF_NEW;
3410 else
3411 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003412 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003413 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003414 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 /* Buffer still changed, the autocommands didn't work
3416 * properly. */
3417 return FAIL;
3418 return OK;
3419 }
3420#ifdef FEAT_EVAL
3421 if (!aborting())
3422#endif
3423 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3424 return FAIL;
3425 }
3426
3427 /*
3428 * The autocommands may have changed the number of lines in the file.
3429 * When writing the whole file, adjust the end.
3430 * When writing part of the file, assume that the autocommands only
3431 * changed the number of lines that are to be written (tricky!).
3432 */
3433 if (buf->b_ml.ml_line_count != old_line_count)
3434 {
3435 if (whole) /* write all */
3436 end = buf->b_ml.ml_line_count;
3437 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3438 end += buf->b_ml.ml_line_count - old_line_count;
3439 else /* less lines */
3440 {
3441 end -= old_line_count - buf->b_ml.ml_line_count;
3442 if (end < start)
3443 {
3444 --no_wait_return;
3445 msg_scroll = msg_save;
3446 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3447 return FAIL;
3448 }
3449 }
3450 }
3451
3452 /*
3453 * The autocommands may have changed the name of the buffer, which may
3454 * be kept in fname, ffname and sfname.
3455 */
3456 if (buf_ffname)
3457 ffname = buf->b_ffname;
3458 if (buf_sfname)
3459 sfname = buf->b_sfname;
3460 if (buf_fname_f)
3461 fname = buf->b_ffname;
3462 if (buf_fname_s)
3463 fname = buf->b_sfname;
3464 }
3465#endif
3466
3467#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003468 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003469 {
3470 if (whole)
3471 {
3472 /*
3473 * b_changed can be 0 after an undo, but we still need to write
3474 * the buffer to NetBeans.
3475 */
3476 if (buf->b_changed || isNetbeansModified(buf))
3477 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003478 --no_wait_return; /* may wait for return now */
3479 msg_scroll = msg_save;
3480 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481 return retval;
3482 }
3483 else
3484 {
3485 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003486 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003487 buffer = NULL;
3488 goto fail;
3489 }
3490 }
3491 else
3492 {
3493 errnum = (char_u *)"E657: ";
3494 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3495 buffer = NULL;
3496 goto fail;
3497 }
3498 }
3499#endif
3500
3501 if (shortmess(SHM_OVER) && !exiting)
3502 msg_scroll = FALSE; /* overwrite previous file message */
3503 else
3504 msg_scroll = TRUE; /* don't overwrite previous file message */
3505 if (!filtering)
3506 filemess(buf,
3507#ifndef UNIX
3508 sfname,
3509#else
3510 fname,
3511#endif
3512 (char_u *)"", 0); /* show that we are busy */
3513 msg_scroll = FALSE; /* always overwrite the file message now */
3514
3515 buffer = alloc(BUFSIZE);
3516 if (buffer == NULL) /* can't allocate big buffer, use small
3517 * one (to be able to write when out of
3518 * memory) */
3519 {
3520 buffer = smallbuf;
3521 bufsize = SMBUFSIZE;
3522 }
3523 else
3524 bufsize = BUFSIZE;
3525
3526 /*
3527 * Get information about original file (if there is one).
3528 */
3529#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003530 st_old.st_dev = 0;
3531 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 perm = -1;
3533 if (mch_stat((char *)fname, &st_old) < 0)
3534 newfile = TRUE;
3535 else
3536 {
3537 perm = st_old.st_mode;
3538 if (!S_ISREG(st_old.st_mode)) /* not a file */
3539 {
3540 if (S_ISDIR(st_old.st_mode))
3541 {
3542 errnum = (char_u *)"E502: ";
3543 errmsg = (char_u *)_("is a directory");
3544 goto fail;
3545 }
3546 if (mch_nodetype(fname) != NODE_WRITABLE)
3547 {
3548 errnum = (char_u *)"E503: ";
3549 errmsg = (char_u *)_("is not a file or writable device");
3550 goto fail;
3551 }
3552 /* It's a device of some kind (or a fifo) which we can write to
3553 * but for which we can't make a backup. */
3554 device = TRUE;
3555 newfile = TRUE;
3556 perm = -1;
3557 }
3558 }
3559#else /* !UNIX */
3560 /*
3561 * Check for a writable device name.
3562 */
3563 c = mch_nodetype(fname);
3564 if (c == NODE_OTHER)
3565 {
3566 errnum = (char_u *)"E503: ";
3567 errmsg = (char_u *)_("is not a file or writable device");
3568 goto fail;
3569 }
3570 if (c == NODE_WRITABLE)
3571 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003572# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3573 /* MS-Windows allows opening a device, but we will probably get stuck
3574 * trying to write to it. */
3575 if (!p_odev)
3576 {
3577 errnum = (char_u *)"E796: ";
3578 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3579 goto fail;
3580 }
3581# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003582 device = TRUE;
3583 newfile = TRUE;
3584 perm = -1;
3585 }
3586 else
3587 {
3588 perm = mch_getperm(fname);
3589 if (perm < 0)
3590 newfile = TRUE;
3591 else if (mch_isdir(fname))
3592 {
3593 errnum = (char_u *)"E502: ";
3594 errmsg = (char_u *)_("is a directory");
3595 goto fail;
3596 }
3597 if (overwriting)
3598 (void)mch_stat((char *)fname, &st_old);
3599 }
3600#endif /* !UNIX */
3601
3602 if (!device && !newfile)
3603 {
3604 /*
3605 * Check if the file is really writable (when renaming the file to
3606 * make a backup we won't discover it later).
3607 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003608 file_readonly = check_file_readonly(fname, (int)perm);
3609
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610 if (!forceit && file_readonly)
3611 {
3612 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3613 {
3614 errnum = (char_u *)"E504: ";
3615 errmsg = (char_u *)_(err_readonly);
3616 }
3617 else
3618 {
3619 errnum = (char_u *)"E505: ";
3620 errmsg = (char_u *)_("is read-only (add ! to override)");
3621 }
3622 goto fail;
3623 }
3624
3625 /*
3626 * Check if the timestamp hasn't changed since reading the file.
3627 */
3628 if (overwriting)
3629 {
3630 retval = check_mtime(buf, &st_old);
3631 if (retval == FAIL)
3632 goto fail;
3633 }
3634 }
3635
3636#ifdef HAVE_ACL
3637 /*
3638 * For systems that support ACL: get the ACL from the original file.
3639 */
3640 if (!newfile)
3641 acl = mch_get_acl(fname);
3642#endif
3643
3644 /*
3645 * If 'backupskip' is not empty, don't make a backup for some files.
3646 */
3647 dobackup = (p_wb || p_bk || *p_pm != NUL);
3648#ifdef FEAT_WILDIGN
3649 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3650 dobackup = FALSE;
3651#endif
3652
3653 /*
3654 * Save the value of got_int and reset it. We don't want a previous
3655 * interruption cancel writing, only hitting CTRL-C while writing should
3656 * abort it.
3657 */
3658 prev_got_int = got_int;
3659 got_int = FALSE;
3660
3661 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3662 buf->b_saving = TRUE;
3663
3664 /*
3665 * If we are not appending or filtering, the file exists, and the
3666 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3667 * When 'patchmode' is set also make a backup when appending.
3668 *
3669 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3670 * off. This helps when editing large files on almost-full disks.
3671 */
3672 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3673 {
3674#if defined(UNIX) || defined(WIN32)
3675 struct stat st;
3676#endif
3677
3678 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3679 backup_copy = TRUE;
3680#if defined(UNIX) || defined(WIN32)
3681 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3682 {
3683 int i;
3684
3685# ifdef UNIX
3686 /*
3687 * Don't rename the file when:
3688 * - it's a hard link
3689 * - it's a symbolic link
3690 * - we don't have write permission in the directory
3691 * - we can't set the owner/group of the new file
3692 */
3693 if (st_old.st_nlink > 1
3694 || mch_lstat((char *)fname, &st) < 0
3695 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003696 || st.st_ino != st_old.st_ino
3697# ifndef HAVE_FCHOWN
3698 || st.st_uid != st_old.st_uid
3699 || st.st_gid != st_old.st_gid
3700# endif
3701 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003702 backup_copy = TRUE;
3703 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003704# else
3705# ifdef WIN32
3706 /* On NTFS file systems hard links are possible. */
3707 if (mch_is_linked(fname))
3708 backup_copy = TRUE;
3709 else
3710# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003711# endif
3712 {
3713 /*
3714 * Check if we can create a file and set the owner/group to
3715 * the ones from the original file.
3716 * First find a file name that doesn't exist yet (use some
3717 * arbitrary numbers).
3718 */
3719 STRCPY(IObuff, fname);
3720 for (i = 4913; ; i += 123)
3721 {
3722 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003723 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003724 break;
3725 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003726 fd = mch_open((char *)IObuff,
3727 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728 if (fd < 0) /* can't write in directory */
3729 backup_copy = TRUE;
3730 else
3731 {
3732# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003733# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003734 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003735# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 if (mch_stat((char *)IObuff, &st) < 0
3737 || st.st_uid != st_old.st_uid
3738 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003739 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003740 backup_copy = TRUE;
3741# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003742 /* Close the file before removing it, on MS-Windows we
3743 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003744 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003745 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003746# ifdef MSWIN
3747 /* MS-Windows may trigger a virus scanner to open the
3748 * file, we can't delete it then. Keep trying for half a
3749 * second. */
3750 {
3751 int try;
3752
3753 for (try = 0; try < 10; ++try)
3754 {
3755 if (mch_lstat((char *)IObuff, &st) < 0)
3756 break;
3757 ui_delay(50L, TRUE); /* wait 50 msec */
3758 mch_remove(IObuff);
3759 }
3760 }
3761# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003762 }
3763 }
3764 }
3765
3766# ifdef UNIX
3767 /*
3768 * Break symlinks and/or hardlinks if we've been asked to.
3769 */
3770 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3771 {
3772 int lstat_res;
3773
3774 lstat_res = mch_lstat((char *)fname, &st);
3775
3776 /* Symlinks. */
3777 if ((bkc_flags & BKC_BREAKSYMLINK)
3778 && lstat_res == 0
3779 && st.st_ino != st_old.st_ino)
3780 backup_copy = FALSE;
3781
3782 /* Hardlinks. */
3783 if ((bkc_flags & BKC_BREAKHARDLINK)
3784 && st_old.st_nlink > 1
3785 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3786 backup_copy = FALSE;
3787 }
3788#endif
3789
3790#endif
3791
3792 /* make sure we have a valid backup extension to use */
3793 if (*p_bex == NUL)
3794 {
3795#ifdef RISCOS
3796 backup_ext = (char_u *)"/bak";
3797#else
3798 backup_ext = (char_u *)".bak";
3799#endif
3800 }
3801 else
3802 backup_ext = p_bex;
3803
3804 if (backup_copy
3805 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3806 {
3807 int bfd;
3808 char_u *copybuf, *wp;
3809 int some_error = FALSE;
3810 struct stat st_new;
3811 char_u *dirp;
3812 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003813#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 int did_set_shortname;
3815#endif
3816
3817 copybuf = alloc(BUFSIZE + 1);
3818 if (copybuf == NULL)
3819 {
3820 some_error = TRUE; /* out of memory */
3821 goto nobackup;
3822 }
3823
3824 /*
3825 * Try to make the backup in each directory in the 'bdir' option.
3826 *
3827 * Unix semantics has it, that we may have a writable file,
3828 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3829 * - the directory is not writable,
3830 * - the file may be a symbolic link,
3831 * - the file may belong to another user/group, etc.
3832 *
3833 * For these reasons, the existing writable file must be truncated
3834 * and reused. Creation of a backup COPY will be attempted.
3835 */
3836 dirp = p_bdir;
3837 while (*dirp)
3838 {
3839#ifdef UNIX
3840 st_new.st_ino = 0;
3841 st_new.st_dev = 0;
3842 st_new.st_gid = 0;
3843#endif
3844
3845 /*
3846 * Isolate one directory name, using an entry in 'bdir'.
3847 */
3848 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3849 rootname = get_file_in_dir(fname, copybuf);
3850 if (rootname == NULL)
3851 {
3852 some_error = TRUE; /* out of memory */
3853 goto nobackup;
3854 }
3855
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003856#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003857 did_set_shortname = FALSE;
3858#endif
3859
3860 /*
3861 * May try twice if 'shortname' not set.
3862 */
3863 for (;;)
3864 {
3865 /*
3866 * Make backup file name.
3867 */
3868 backup = buf_modname(
3869#ifdef SHORT_FNAME
3870 TRUE,
3871#else
3872 (buf->b_p_sn || buf->b_shortname),
3873#endif
3874 rootname, backup_ext, FALSE);
3875 if (backup == NULL)
3876 {
3877 vim_free(rootname);
3878 some_error = TRUE; /* out of memory */
3879 goto nobackup;
3880 }
3881
3882 /*
3883 * Check if backup file already exists.
3884 */
3885 if (mch_stat((char *)backup, &st_new) >= 0)
3886 {
3887#ifdef UNIX
3888 /*
3889 * Check if backup file is same as original file.
3890 * May happen when modname() gave the same file back.
3891 * E.g. silly link, or file name-length reached.
3892 * If we don't check here, we either ruin the file
3893 * when copying or erase it after writing. jw.
3894 */
3895 if (st_new.st_dev == st_old.st_dev
3896 && st_new.st_ino == st_old.st_ino)
3897 {
3898 vim_free(backup);
3899 backup = NULL; /* no backup file to delete */
3900# ifndef SHORT_FNAME
3901 /*
3902 * may try again with 'shortname' set
3903 */
3904 if (!(buf->b_shortname || buf->b_p_sn))
3905 {
3906 buf->b_shortname = TRUE;
3907 did_set_shortname = TRUE;
3908 continue;
3909 }
3910 /* setting shortname didn't help */
3911 if (did_set_shortname)
3912 buf->b_shortname = FALSE;
3913# endif
3914 break;
3915 }
3916#endif
3917
3918 /*
3919 * If we are not going to keep the backup file, don't
3920 * delete an existing one, try to use another name.
3921 * Change one character, just before the extension.
3922 */
3923 if (!p_bk)
3924 {
3925 wp = backup + STRLEN(backup) - 1
3926 - STRLEN(backup_ext);
3927 if (wp < backup) /* empty file name ??? */
3928 wp = backup;
3929 *wp = 'z';
3930 while (*wp > 'a'
3931 && mch_stat((char *)backup, &st_new) >= 0)
3932 --*wp;
3933 /* They all exist??? Must be something wrong. */
3934 if (*wp == 'a')
3935 {
3936 vim_free(backup);
3937 backup = NULL;
3938 }
3939 }
3940 }
3941 break;
3942 }
3943 vim_free(rootname);
3944
3945 /*
3946 * Try to create the backup file
3947 */
3948 if (backup != NULL)
3949 {
3950 /* remove old backup, if present */
3951 mch_remove(backup);
3952 /* Open with O_EXCL to avoid the file being created while
3953 * we were sleeping (symlink hacker attack?) */
3954 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003955 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3956 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003957 if (bfd < 0)
3958 {
3959 vim_free(backup);
3960 backup = NULL;
3961 }
3962 else
3963 {
3964 /* set file protection same as original file, but
3965 * strip s-bit */
3966 (void)mch_setperm(backup, perm & 0777);
3967
3968#ifdef UNIX
3969 /*
3970 * Try to set the group of the backup same as the
3971 * original file. If this fails, set the protection
3972 * bits for the group same as the protection bits for
3973 * others.
3974 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003975 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003976# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003977 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978# endif
3979 )
3980 mch_setperm(backup,
3981 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003982# ifdef HAVE_SELINUX
3983 mch_copy_sec(fname, backup);
3984# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003985#endif
3986
3987 /*
3988 * copy the file.
3989 */
3990 write_info.bw_fd = bfd;
3991 write_info.bw_buf = copybuf;
3992#ifdef HAS_BW_FLAGS
3993 write_info.bw_flags = FIO_NOCONVERT;
3994#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003995 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996 BUFSIZE)) > 0)
3997 {
3998 if (buf_write_bytes(&write_info) == FAIL)
3999 {
4000 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4001 break;
4002 }
4003 ui_breakcheck();
4004 if (got_int)
4005 {
4006 errmsg = (char_u *)_(e_interr);
4007 break;
4008 }
4009 }
4010
4011 if (close(bfd) < 0 && errmsg == NULL)
4012 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4013 if (write_info.bw_len < 0)
4014 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4015#ifdef UNIX
4016 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4017#endif
4018#ifdef HAVE_ACL
4019 mch_set_acl(backup, acl);
4020#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004021#ifdef HAVE_SELINUX
4022 mch_copy_sec(fname, backup);
4023#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004024 break;
4025 }
4026 }
4027 }
4028 nobackup:
4029 close(fd); /* ignore errors for closing read file */
4030 vim_free(copybuf);
4031
4032 if (backup == NULL && errmsg == NULL)
4033 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4034 /* ignore errors when forceit is TRUE */
4035 if ((some_error || errmsg != NULL) && !forceit)
4036 {
4037 retval = FAIL;
4038 goto fail;
4039 }
4040 errmsg = NULL;
4041 }
4042 else
4043 {
4044 char_u *dirp;
4045 char_u *p;
4046 char_u *rootname;
4047
4048 /*
4049 * Make a backup by renaming the original file.
4050 */
4051 /*
4052 * If 'cpoptions' includes the "W" flag, we don't want to
4053 * overwrite a read-only file. But rename may be possible
4054 * anyway, thus we need an extra check here.
4055 */
4056 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4057 {
4058 errnum = (char_u *)"E504: ";
4059 errmsg = (char_u *)_(err_readonly);
4060 goto fail;
4061 }
4062
4063 /*
4064 *
4065 * Form the backup file name - change path/fo.o.h to
4066 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4067 * that works is used.
4068 */
4069 dirp = p_bdir;
4070 while (*dirp)
4071 {
4072 /*
4073 * Isolate one directory name and make the backup file name.
4074 */
4075 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4076 rootname = get_file_in_dir(fname, IObuff);
4077 if (rootname == NULL)
4078 backup = NULL;
4079 else
4080 {
4081 backup = buf_modname(
4082#ifdef SHORT_FNAME
4083 TRUE,
4084#else
4085 (buf->b_p_sn || buf->b_shortname),
4086#endif
4087 rootname, backup_ext, FALSE);
4088 vim_free(rootname);
4089 }
4090
4091 if (backup != NULL)
4092 {
4093 /*
4094 * If we are not going to keep the backup file, don't
4095 * delete an existing one, try to use another name.
4096 * Change one character, just before the extension.
4097 */
4098 if (!p_bk && mch_getperm(backup) >= 0)
4099 {
4100 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4101 if (p < backup) /* empty file name ??? */
4102 p = backup;
4103 *p = 'z';
4104 while (*p > 'a' && mch_getperm(backup) >= 0)
4105 --*p;
4106 /* They all exist??? Must be something wrong! */
4107 if (*p == 'a')
4108 {
4109 vim_free(backup);
4110 backup = NULL;
4111 }
4112 }
4113 }
4114 if (backup != NULL)
4115 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004116 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004117 * Delete any existing backup and move the current version
4118 * to the backup. For safety, we don't remove the backup
4119 * until the write has finished successfully. And if the
4120 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004121 */
4122 /*
4123 * If the renaming of the original file to the backup file
4124 * works, quit here.
4125 */
4126 if (vim_rename(fname, backup) == 0)
4127 break;
4128
4129 vim_free(backup); /* don't do the rename below */
4130 backup = NULL;
4131 }
4132 }
4133 if (backup == NULL && !forceit)
4134 {
4135 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4136 goto fail;
4137 }
4138 }
4139 }
4140
4141#if defined(UNIX) && !defined(ARCHIE)
4142 /* When using ":w!" and the file was read-only: make it writable */
4143 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4144 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4145 {
4146 perm |= 0200;
4147 (void)mch_setperm(fname, perm);
4148 made_writable = TRUE;
4149 }
4150#endif
4151
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004152 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004153 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4154 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 {
4156 buf->b_p_ro = FALSE;
4157#ifdef FEAT_TITLE
4158 need_maketitle = TRUE; /* set window title later */
4159#endif
4160#ifdef FEAT_WINDOWS
4161 status_redraw_all(); /* redraw status lines later */
4162#endif
4163 }
4164
4165 if (end > buf->b_ml.ml_line_count)
4166 end = buf->b_ml.ml_line_count;
4167 if (buf->b_ml.ml_flags & ML_EMPTY)
4168 start = end + 1;
4169
4170 /*
4171 * If the original file is being overwritten, there is a small chance that
4172 * we crash in the middle of writing. Therefore the file is preserved now.
4173 * This makes all block numbers positive so that recovery does not need
4174 * the original file.
4175 * Don't do this if there is a backup file and we are exiting.
4176 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004177 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178 && !(exiting && backup != NULL))
4179 {
4180 ml_preserve(buf, FALSE);
4181 if (got_int)
4182 {
4183 errmsg = (char_u *)_(e_interr);
4184 goto restore_backup;
4185 }
4186 }
4187
4188#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4189 /*
4190 * Before risking to lose the original file verify if there's
4191 * a resource fork to preserve, and if cannot be done warn
4192 * the users. This happens when overwriting without backups.
4193 */
4194 if (backup == NULL && overwriting && !append)
4195 if (mch_has_resource_fork(fname))
4196 {
4197 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4198 goto restore_backup;
4199 }
4200#endif
4201
4202#ifdef VMS
4203 vms_remove_version(fname); /* remove version */
4204#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004205 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004206 * multi-byte conversion. */
4207 wfname = fname;
4208
4209#ifdef FEAT_MBYTE
4210 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4211 if (eap != NULL && eap->force_enc != 0)
4212 {
4213 fenc = eap->cmd + eap->force_enc;
4214 fenc = enc_canonize(fenc);
4215 fenc_tofree = fenc;
4216 }
4217 else
4218 fenc = buf->b_p_fenc;
4219
4220 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004221 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004222 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004223 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224
4225 /*
4226 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4227 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4228 * Prepare the flags for it and allocate bw_conv_buf when needed.
4229 */
4230 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4231 {
4232 wb_flags = get_fio_flags(fenc);
4233 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4234 {
4235 /* Need to allocate a buffer to translate into. */
4236 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4237 write_info.bw_conv_buflen = bufsize * 2;
4238 else /* FIO_UCS4 */
4239 write_info.bw_conv_buflen = bufsize * 4;
4240 write_info.bw_conv_buf
4241 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4242 if (write_info.bw_conv_buf == NULL)
4243 end = 0;
4244 }
4245 }
4246
4247# ifdef WIN3264
4248 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4249 {
4250 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4251 write_info.bw_conv_buflen = bufsize * 4;
4252 write_info.bw_conv_buf
4253 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4254 if (write_info.bw_conv_buf == NULL)
4255 end = 0;
4256 }
4257# endif
4258
4259# ifdef MACOS_X
4260 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4261 {
4262 write_info.bw_conv_buflen = bufsize * 3;
4263 write_info.bw_conv_buf
4264 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4265 if (write_info.bw_conv_buf == NULL)
4266 end = 0;
4267 }
4268# endif
4269
4270# if defined(FEAT_EVAL) || defined(USE_ICONV)
4271 if (converted && wb_flags == 0)
4272 {
4273# ifdef USE_ICONV
4274 /*
4275 * Use iconv() conversion when conversion is needed and it's not done
4276 * internally.
4277 */
4278 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4279 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4280 if (write_info.bw_iconv_fd != (iconv_t)-1)
4281 {
4282 /* We're going to use iconv(), allocate a buffer to convert in. */
4283 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4284 write_info.bw_conv_buf
4285 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4286 if (write_info.bw_conv_buf == NULL)
4287 end = 0;
4288 write_info.bw_first = TRUE;
4289 }
4290# ifdef FEAT_EVAL
4291 else
4292# endif
4293# endif
4294
4295# ifdef FEAT_EVAL
4296 /*
4297 * When the file needs to be converted with 'charconvert' after
4298 * writing, write to a temp file instead and let the conversion
4299 * overwrite the original file.
4300 */
4301 if (*p_ccv != NUL)
4302 {
4303 wfname = vim_tempname('w');
4304 if (wfname == NULL) /* Can't write without a tempfile! */
4305 {
4306 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4307 goto restore_backup;
4308 }
4309 }
4310# endif
4311 }
4312# endif
4313 if (converted && wb_flags == 0
4314# ifdef USE_ICONV
4315 && write_info.bw_iconv_fd == (iconv_t)-1
4316# endif
4317# ifdef FEAT_EVAL
4318 && wfname == fname
4319# endif
4320 )
4321 {
4322 if (!forceit)
4323 {
4324 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4325 goto restore_backup;
4326 }
4327 notconverted = TRUE;
4328 }
4329#endif
4330
4331 /*
4332 * Open the file "wfname" for writing.
4333 * We may try to open the file twice: If we can't write to the
4334 * file and forceit is TRUE we delete the existing file and try to create
4335 * a new one. If this still fails we may have lost the original file!
4336 * (this may happen when the user reached his quotum for number of files).
4337 * Appending will fail if the file does not exist and forceit is FALSE.
4338 */
4339 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4340 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4341 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004342 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343 {
4344 /*
4345 * A forced write will try to create a new file if the old one is
4346 * still readonly. This may also happen when the directory is
4347 * read-only. In that case the mch_remove() will fail.
4348 */
4349 if (errmsg == NULL)
4350 {
4351#ifdef UNIX
4352 struct stat st;
4353
4354 /* Don't delete the file when it's a hard or symbolic link. */
4355 if ((!newfile && st_old.st_nlink > 1)
4356 || (mch_lstat((char *)fname, &st) == 0
4357 && (st.st_dev != st_old.st_dev
4358 || st.st_ino != st_old.st_ino)))
4359 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4360 else
4361#endif
4362 {
4363 errmsg = (char_u *)_("E212: Can't open file for writing");
4364 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4365 && perm >= 0)
4366 {
4367#ifdef UNIX
4368 /* we write to the file, thus it should be marked
4369 writable after all */
4370 if (!(perm & 0200))
4371 made_writable = TRUE;
4372 perm |= 0200;
4373 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4374 perm &= 0777;
4375#endif
4376 if (!append) /* don't remove when appending */
4377 mch_remove(wfname);
4378 continue;
4379 }
4380 }
4381 }
4382
4383restore_backup:
4384 {
4385 struct stat st;
4386
4387 /*
4388 * If we failed to open the file, we don't need a backup. Throw it
4389 * away. If we moved or removed the original file try to put the
4390 * backup in its place.
4391 */
4392 if (backup != NULL && wfname == fname)
4393 {
4394 if (backup_copy)
4395 {
4396 /*
4397 * There is a small chance that we removed the original,
4398 * try to move the copy in its place.
4399 * This may not work if the vim_rename() fails.
4400 * In that case we leave the copy around.
4401 */
4402 /* If file does not exist, put the copy in its place */
4403 if (mch_stat((char *)fname, &st) < 0)
4404 vim_rename(backup, fname);
4405 /* if original file does exist throw away the copy */
4406 if (mch_stat((char *)fname, &st) >= 0)
4407 mch_remove(backup);
4408 }
4409 else
4410 {
4411 /* try to put the original file back */
4412 vim_rename(backup, fname);
4413 }
4414 }
4415
4416 /* if original file no longer exists give an extra warning */
4417 if (!newfile && mch_stat((char *)fname, &st) < 0)
4418 end = 0;
4419 }
4420
4421#ifdef FEAT_MBYTE
4422 if (wfname != fname)
4423 vim_free(wfname);
4424#endif
4425 goto fail;
4426 }
4427 errmsg = NULL;
4428
4429#if defined(MACOS_CLASSIC) || defined(WIN3264)
4430 /* TODO: Is it need for MACOS_X? (Dany) */
4431 /*
4432 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004433 * This is done in order to preserve the resource fork and the
4434 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004435 */
4436 if (backup != NULL && overwriting && !append)
4437 {
4438 if (backup_copy)
4439 (void)mch_copy_file_attribute(wfname, backup);
4440 else
4441 (void)mch_copy_file_attribute(backup, wfname);
4442 }
4443
4444 if (!overwriting && !append)
4445 {
4446 if (buf->b_ffname != NULL)
4447 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004448 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004449 }
4450#endif
4451
4452 write_info.bw_fd = fd;
4453
4454#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004455 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004456 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004457 char_u *header;
4458 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004459
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004460 header = prepare_crypt_write(buf, &header_len);
4461 if (header == NULL)
4462 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004463 else
4464 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004465 /* Write magic number, so that Vim knows that this file is
4466 * encrypted when reading it again. This also undergoes utf-8 to
4467 * ucs-2/4 conversion when needed. */
4468 write_info.bw_buf = header;
4469 write_info.bw_len = header_len;
4470 write_info.bw_flags = FIO_NOCONVERT;
4471 if (buf_write_bytes(&write_info) == FAIL)
4472 end = 0;
4473 wb_flags |= FIO_ENCRYPTED;
4474 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004475 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 }
4477#endif
4478
4479 write_info.bw_buf = buffer;
4480 nchars = 0;
4481
4482 /* use "++bin", "++nobin" or 'binary' */
4483 if (eap != NULL && eap->force_bin != 0)
4484 write_bin = (eap->force_bin == FORCE_BIN);
4485 else
4486 write_bin = buf->b_p_bin;
4487
4488#ifdef FEAT_MBYTE
4489 /*
4490 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004491 * Skip it when appending and the file already existed, the BOM only makes
4492 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004493 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004494 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495 {
4496 write_info.bw_len = make_bom(buffer, fenc);
4497 if (write_info.bw_len > 0)
4498 {
4499 /* don't convert, do encryption */
4500 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4501 if (buf_write_bytes(&write_info) == FAIL)
4502 end = 0;
4503 else
4504 nchars += write_info.bw_len;
4505 }
4506 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004507 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004508#endif
4509
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004510#ifdef FEAT_PERSISTENT_UNDO
4511 write_undo_file = (buf->b_p_udf && overwriting && !append
4512 && !filtering && reset_changed);
4513 if (write_undo_file)
4514 /* Prepare for computing the hash value of the text. */
4515 sha256_start(&sha_ctx);
4516#endif
4517
Bram Moolenaar071d4272004-06-13 20:20:40 +00004518 write_info.bw_len = bufsize;
4519#ifdef HAS_BW_FLAGS
4520 write_info.bw_flags = wb_flags;
4521#endif
4522 fileformat = get_fileformat_force(buf, eap);
4523 s = buffer;
4524 len = 0;
4525 for (lnum = start; lnum <= end; ++lnum)
4526 {
4527 /*
4528 * The next while loop is done once for each character written.
4529 * Keep it fast!
4530 */
4531 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004532#ifdef FEAT_PERSISTENT_UNDO
4533 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004534 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004535#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004536 while ((c = *++ptr) != NUL)
4537 {
4538 if (c == NL)
4539 *s = NUL; /* replace newlines with NULs */
4540 else if (c == CAR && fileformat == EOL_MAC)
4541 *s = NL; /* Mac: replace CRs with NLs */
4542 else
4543 *s = c;
4544 ++s;
4545 if (++len != bufsize)
4546 continue;
4547 if (buf_write_bytes(&write_info) == FAIL)
4548 {
4549 end = 0; /* write error: break loop */
4550 break;
4551 }
4552 nchars += bufsize;
4553 s = buffer;
4554 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004555#ifdef FEAT_MBYTE
4556 write_info.bw_start_lnum = lnum;
4557#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004558 }
4559 /* write failed or last line has no EOL: stop here */
4560 if (end == 0
4561 || (lnum == end
4562 && write_bin
4563 && (lnum == write_no_eol_lnum
4564 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4565 {
4566 ++lnum; /* written the line, count it */
4567 no_eol = TRUE;
4568 break;
4569 }
4570 if (fileformat == EOL_UNIX)
4571 *s++ = NL;
4572 else
4573 {
4574 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4575 if (fileformat == EOL_DOS) /* write CR-NL */
4576 {
4577 if (++len == bufsize)
4578 {
4579 if (buf_write_bytes(&write_info) == FAIL)
4580 {
4581 end = 0; /* write error: break loop */
4582 break;
4583 }
4584 nchars += bufsize;
4585 s = buffer;
4586 len = 0;
4587 }
4588 *s++ = NL;
4589 }
4590 }
4591 if (++len == bufsize && end)
4592 {
4593 if (buf_write_bytes(&write_info) == FAIL)
4594 {
4595 end = 0; /* write error: break loop */
4596 break;
4597 }
4598 nchars += bufsize;
4599 s = buffer;
4600 len = 0;
4601
4602 ui_breakcheck();
4603 if (got_int)
4604 {
4605 end = 0; /* Interrupted, break loop */
4606 break;
4607 }
4608 }
4609#ifdef VMS
4610 /*
4611 * On VMS there is a problem: newlines get added when writing blocks
4612 * at a time. Fix it by writing a line at a time.
4613 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004614 * Explanation: VAX/DECC RTL insists that records in some RMS
4615 * structures end with a newline (carriage return) character, and if
4616 * they don't it adds one.
4617 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004618 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004619 if (buf->b_fab_rfm == FAB$C_VFC
4620 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004621 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004622 int b2write;
4623
4624 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4625 ? MIN(4096, bufsize)
4626 : MIN(buf->b_fab_mrs, bufsize));
4627
4628 b2write = len;
4629 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004630 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004631 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4632 if (buf_write_bytes(&write_info) == FAIL)
4633 {
4634 end = 0;
4635 break;
4636 }
4637 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638 }
4639 write_info.bw_len = bufsize;
4640 nchars += len;
4641 s = buffer;
4642 len = 0;
4643 }
4644#endif
4645 }
4646 if (len > 0 && end > 0)
4647 {
4648 write_info.bw_len = len;
4649 if (buf_write_bytes(&write_info) == FAIL)
4650 end = 0; /* write error */
4651 nchars += len;
4652 }
4653
4654#if defined(UNIX) && defined(HAVE_FSYNC)
4655 /* On many journalling file systems there is a bug that causes both the
4656 * original and the backup file to be lost when halting the system right
4657 * after writing the file. That's because only the meta-data is
4658 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004659 * been written to disk and we don't lose it.
4660 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004661 * (could be a pipe).
4662 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4663 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664 {
4665 errmsg = (char_u *)_("E667: Fsync failed");
4666 end = 0;
4667 }
4668#endif
4669
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004670#ifdef HAVE_SELINUX
4671 /* Probably need to set the security context. */
4672 if (!backup_copy)
4673 mch_copy_sec(backup, wfname);
4674#endif
4675
Bram Moolenaara5792f52005-11-23 21:25:05 +00004676#ifdef UNIX
4677 /* When creating a new file, set its owner/group to that of the original
4678 * file. Get the new device and inode number. */
4679 if (backup != NULL && !backup_copy)
4680 {
4681# ifdef HAVE_FCHOWN
4682 struct stat st;
4683
4684 /* don't change the owner when it's already OK, some systems remove
4685 * permission or ACL stuff */
4686 if (mch_stat((char *)wfname, &st) < 0
4687 || st.st_uid != st_old.st_uid
4688 || st.st_gid != st_old.st_gid)
4689 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004690 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004691 if (perm >= 0) /* set permission again, may have changed */
4692 (void)mch_setperm(wfname, perm);
4693 }
4694# endif
4695 buf_setino(buf);
4696 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004697 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004698 /* Set the inode when creating a new file. */
4699 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004700#endif
4701
Bram Moolenaar071d4272004-06-13 20:20:40 +00004702 if (close(fd) != 0)
4703 {
4704 errmsg = (char_u *)_("E512: Close failed");
4705 end = 0;
4706 }
4707
4708#ifdef UNIX
4709 if (made_writable)
4710 perm &= ~0200; /* reset 'w' bit for security reasons */
4711#endif
4712 if (perm >= 0) /* set perm. of new file same as old file */
4713 (void)mch_setperm(wfname, perm);
4714#ifdef RISCOS
4715 if (!append && !filtering)
4716 /* Set the filetype after writing the file. */
4717 mch_set_filetype(wfname, buf->b_p_oft);
4718#endif
4719#ifdef HAVE_ACL
4720 /* Probably need to set the ACL before changing the user (can't set the
4721 * ACL on a file the user doesn't own). */
4722 if (!backup_copy)
4723 mch_set_acl(wfname, acl);
4724#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004725#ifdef FEAT_CRYPT
4726 if (wb_flags & FIO_ENCRYPTED)
4727 crypt_pop_state();
4728#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004729
Bram Moolenaar071d4272004-06-13 20:20:40 +00004730
4731#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4732 if (wfname != fname)
4733 {
4734 /*
4735 * The file was written to a temp file, now it needs to be converted
4736 * with 'charconvert' to (overwrite) the output file.
4737 */
4738 if (end != 0)
4739 {
4740 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4741 wfname, fname) == FAIL)
4742 {
4743 write_info.bw_conv_error = TRUE;
4744 end = 0;
4745 }
4746 }
4747 mch_remove(wfname);
4748 vim_free(wfname);
4749 }
4750#endif
4751
4752 if (end == 0)
4753 {
4754 if (errmsg == NULL)
4755 {
4756#ifdef FEAT_MBYTE
4757 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004758 {
4759 if (write_info.bw_conv_error_lnum == 0)
4760 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4761 else
4762 {
4763 errmsg_allocated = TRUE;
4764 errmsg = alloc(300);
4765 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4766 (long)write_info.bw_conv_error_lnum);
4767 }
4768 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004769 else
4770#endif
4771 if (got_int)
4772 errmsg = (char_u *)_(e_interr);
4773 else
4774 errmsg = (char_u *)_("E514: write error (file system full?)");
4775 }
4776
4777 /*
4778 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004779 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004780 * original file when trying to make a backup when writing the file a
4781 * second time.
4782 * When "backup_copy" is set we need to copy the backup over the new
4783 * file. Otherwise rename the backup file.
4784 * If this is OK, don't give the extra warning message.
4785 */
4786 if (backup != NULL)
4787 {
4788 if (backup_copy)
4789 {
4790 /* This may take a while, if we were interrupted let the user
4791 * know we got the message. */
4792 if (got_int)
4793 {
4794 MSG(_(e_interr));
4795 out_flush();
4796 }
4797 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4798 {
4799 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004800 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4801 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 {
4803 /* copy the file. */
4804 write_info.bw_buf = smallbuf;
4805#ifdef HAS_BW_FLAGS
4806 write_info.bw_flags = FIO_NOCONVERT;
4807#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004808 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004809 SMBUFSIZE)) > 0)
4810 if (buf_write_bytes(&write_info) == FAIL)
4811 break;
4812
4813 if (close(write_info.bw_fd) >= 0
4814 && write_info.bw_len == 0)
4815 end = 1; /* success */
4816 }
4817 close(fd); /* ignore errors for closing read file */
4818 }
4819 }
4820 else
4821 {
4822 if (vim_rename(backup, fname) == 0)
4823 end = 1;
4824 }
4825 }
4826 goto fail;
4827 }
4828
4829 lnum -= start; /* compute number of written lines */
4830 --no_wait_return; /* may wait for return now */
4831
4832#if !(defined(UNIX) || defined(VMS))
4833 fname = sfname; /* use shortname now, for the messages */
4834#endif
4835 if (!filtering)
4836 {
4837 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4838 c = FALSE;
4839#ifdef FEAT_MBYTE
4840 if (write_info.bw_conv_error)
4841 {
4842 STRCAT(IObuff, _(" CONVERSION ERROR"));
4843 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004844 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004845 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004846 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004847 }
4848 else if (notconverted)
4849 {
4850 STRCAT(IObuff, _("[NOT converted]"));
4851 c = TRUE;
4852 }
4853 else if (converted)
4854 {
4855 STRCAT(IObuff, _("[converted]"));
4856 c = TRUE;
4857 }
4858#endif
4859 if (device)
4860 {
4861 STRCAT(IObuff, _("[Device]"));
4862 c = TRUE;
4863 }
4864 else if (newfile)
4865 {
4866 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4867 c = TRUE;
4868 }
4869 if (no_eol)
4870 {
4871 msg_add_eol();
4872 c = TRUE;
4873 }
4874 /* may add [unix/dos/mac] */
4875 if (msg_add_fileformat(fileformat))
4876 c = TRUE;
4877#ifdef FEAT_CRYPT
4878 if (wb_flags & FIO_ENCRYPTED)
4879 {
4880 STRCAT(IObuff, _("[crypted]"));
4881 c = TRUE;
4882 }
4883#endif
4884 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4885 if (!shortmess(SHM_WRITE))
4886 {
4887 if (append)
4888 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4889 else
4890 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4891 }
4892
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004893 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004894 }
4895
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004896 /* When written everything correctly: reset 'modified'. Unless not
4897 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004898 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004899#ifdef FEAT_MBYTE
4900 && !write_info.bw_conv_error
4901#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004902 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4903 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904 {
4905 unchanged(buf, TRUE);
4906 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004907 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004908 }
4909
4910 /*
4911 * If written to the current file, update the timestamp of the swap file
4912 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4913 */
4914 if (overwriting)
4915 {
4916 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004917 if (append)
4918 buf->b_flags &= ~BF_NEW;
4919 else
4920 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004921 }
4922
4923 /*
4924 * If we kept a backup until now, and we are in patch mode, then we make
4925 * the backup file our 'original' file.
4926 */
4927 if (*p_pm && dobackup)
4928 {
4929 char *org = (char *)buf_modname(
4930#ifdef SHORT_FNAME
4931 TRUE,
4932#else
4933 (buf->b_p_sn || buf->b_shortname),
4934#endif
4935 fname, p_pm, FALSE);
4936
4937 if (backup != NULL)
4938 {
4939 struct stat st;
4940
4941 /*
4942 * If the original file does not exist yet
4943 * the current backup file becomes the original file
4944 */
4945 if (org == NULL)
4946 EMSG(_("E205: Patchmode: can't save original file"));
4947 else if (mch_stat(org, &st) < 0)
4948 {
4949 vim_rename(backup, (char_u *)org);
4950 vim_free(backup); /* don't delete the file */
4951 backup = NULL;
4952#ifdef UNIX
4953 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4954#endif
4955 }
4956 }
4957 /*
4958 * If there is no backup file, remember that a (new) file was
4959 * created.
4960 */
4961 else
4962 {
4963 int empty_fd;
4964
4965 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004966 || (empty_fd = mch_open(org,
4967 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004968 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004969 EMSG(_("E206: patchmode: can't touch empty original file"));
4970 else
4971 close(empty_fd);
4972 }
4973 if (org != NULL)
4974 {
4975 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4976 vim_free(org);
4977 }
4978 }
4979
4980 /*
4981 * Remove the backup unless 'backup' option is set
4982 */
4983 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4984 EMSG(_("E207: Can't delete backup file"));
4985
4986#ifdef FEAT_SUN_WORKSHOP
4987 if (usingSunWorkShop)
4988 workshop_file_saved((char *) ffname);
4989#endif
4990
4991 goto nofail;
4992
4993 /*
4994 * Finish up. We get here either after failure or success.
4995 */
4996fail:
4997 --no_wait_return; /* may wait for return now */
4998nofail:
4999
5000 /* Done saving, we accept changed buffer warnings again */
5001 buf->b_saving = FALSE;
5002
5003 vim_free(backup);
5004 if (buffer != smallbuf)
5005 vim_free(buffer);
5006#ifdef FEAT_MBYTE
5007 vim_free(fenc_tofree);
5008 vim_free(write_info.bw_conv_buf);
5009# ifdef USE_ICONV
5010 if (write_info.bw_iconv_fd != (iconv_t)-1)
5011 {
5012 iconv_close(write_info.bw_iconv_fd);
5013 write_info.bw_iconv_fd = (iconv_t)-1;
5014 }
5015# endif
5016#endif
5017#ifdef HAVE_ACL
5018 mch_free_acl(acl);
5019#endif
5020
5021 if (errmsg != NULL)
5022 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005023 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005024
5025 attr = hl_attr(HLF_E); /* set highlight for error messages */
5026 msg_add_fname(buf,
5027#ifndef UNIX
5028 sfname
5029#else
5030 fname
5031#endif
5032 ); /* put file name in IObuff with quotes */
5033 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5034 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5035 /* If the error message has the form "is ...", put the error number in
5036 * front of the file name. */
5037 if (errnum != NULL)
5038 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005039 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005040 mch_memmove(IObuff, errnum, (size_t)numlen);
5041 }
5042 STRCAT(IObuff, errmsg);
5043 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005044 if (errmsg_allocated)
5045 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005046
5047 retval = FAIL;
5048 if (end == 0)
5049 {
5050 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5051 attr | MSG_HIST);
5052 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5053 attr | MSG_HIST);
5054
5055 /* Update the timestamp to avoid an "overwrite changed file"
5056 * prompt when writing again. */
5057 if (mch_stat((char *)fname, &st_old) >= 0)
5058 {
5059 buf_store_time(buf, &st_old, fname);
5060 buf->b_mtime_read = buf->b_mtime;
5061 }
5062 }
5063 }
5064 msg_scroll = msg_save;
5065
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005066#ifdef FEAT_PERSISTENT_UNDO
5067 /*
5068 * When writing the whole file and 'undofile' is set, also write the undo
5069 * file.
5070 */
5071 if (retval == OK && write_undo_file)
5072 {
5073 char_u hash[UNDO_HASH_SIZE];
5074
5075 sha256_finish(&sha_ctx, hash);
5076 u_write_undo(NULL, FALSE, buf, hash);
5077 }
5078#endif
5079
Bram Moolenaar071d4272004-06-13 20:20:40 +00005080#ifdef FEAT_AUTOCMD
5081#ifdef FEAT_EVAL
5082 if (!should_abort(retval))
5083#else
5084 if (!got_int)
5085#endif
5086 {
5087 aco_save_T aco;
5088
5089 write_no_eol_lnum = 0; /* in case it was set by the previous read */
5090
5091 /*
5092 * Apply POST autocommands.
5093 * Careful: The autocommands may call buf_write() recursively!
5094 */
5095 aucmd_prepbuf(&aco, buf);
5096
5097 if (append)
5098 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5099 FALSE, curbuf, eap);
5100 else if (filtering)
5101 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5102 FALSE, curbuf, eap);
5103 else if (reset_changed && whole)
5104 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5105 FALSE, curbuf, eap);
5106 else
5107 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5108 FALSE, curbuf, eap);
5109
5110 /* restore curwin/curbuf and a few other things */
5111 aucmd_restbuf(&aco);
5112
5113#ifdef FEAT_EVAL
5114 if (aborting()) /* autocmds may abort script processing */
5115 retval = FALSE;
5116#endif
5117 }
5118#endif
5119
5120 got_int |= prev_got_int;
5121
5122#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5123 /* Update machine specific information. */
5124 mch_post_buffer_write(buf);
5125#endif
5126 return retval;
5127}
5128
5129/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005130 * Set the name of the current buffer. Use when the buffer doesn't have a
5131 * name and a ":r" or ":w" command with a file name is used.
5132 */
5133 static int
5134set_rw_fname(fname, sfname)
5135 char_u *fname;
5136 char_u *sfname;
5137{
5138#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005139 buf_T *buf = curbuf;
5140
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005141 /* It's like the unnamed buffer is deleted.... */
5142 if (curbuf->b_p_bl)
5143 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5144 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5145# ifdef FEAT_EVAL
5146 if (aborting()) /* autocmds may abort script processing */
5147 return FAIL;
5148# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005149 if (curbuf != buf)
5150 {
5151 /* We are in another buffer now, don't do the renaming. */
5152 EMSG(_(e_auchangedbuf));
5153 return FAIL;
5154 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005155#endif
5156
5157 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5158 curbuf->b_flags |= BF_NOTEDITED;
5159
5160#ifdef FEAT_AUTOCMD
5161 /* ....and a new named one is created */
5162 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5163 if (curbuf->b_p_bl)
5164 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5165# ifdef FEAT_EVAL
5166 if (aborting()) /* autocmds may abort script processing */
5167 return FAIL;
5168# endif
5169
5170 /* Do filetype detection now if 'filetype' is empty. */
5171 if (*curbuf->b_p_ft == NUL)
5172 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005173 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005174 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005175 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005176 }
5177#endif
5178
5179 return OK;
5180}
5181
5182/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005183 * Put file name into IObuff with quotes.
5184 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005185 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186msg_add_fname(buf, fname)
5187 buf_T *buf;
5188 char_u *fname;
5189{
5190 if (fname == NULL)
5191 fname = (char_u *)"-stdin-";
5192 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5193 IObuff[0] = '"';
5194 STRCAT(IObuff, "\" ");
5195}
5196
5197/*
5198 * Append message for text mode to IObuff.
5199 * Return TRUE if something appended.
5200 */
5201 static int
5202msg_add_fileformat(eol_type)
5203 int eol_type;
5204{
5205#ifndef USE_CRNL
5206 if (eol_type == EOL_DOS)
5207 {
5208 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5209 return TRUE;
5210 }
5211#endif
5212#ifndef USE_CR
5213 if (eol_type == EOL_MAC)
5214 {
5215 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5216 return TRUE;
5217 }
5218#endif
5219#if defined(USE_CRNL) || defined(USE_CR)
5220 if (eol_type == EOL_UNIX)
5221 {
5222 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5223 return TRUE;
5224 }
5225#endif
5226 return FALSE;
5227}
5228
5229/*
5230 * Append line and character count to IObuff.
5231 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005232 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005233msg_add_lines(insert_space, lnum, nchars)
5234 int insert_space;
5235 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005236 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005237{
5238 char_u *p;
5239
5240 p = IObuff + STRLEN(IObuff);
5241
5242 if (insert_space)
5243 *p++ = ' ';
5244 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005245 sprintf((char *)p,
5246#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005247 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005248#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005249 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5250 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005251#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005252 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005253 else
5254 {
5255 if (lnum == 1)
5256 STRCPY(p, _("1 line, "));
5257 else
5258 sprintf((char *)p, _("%ld lines, "), lnum);
5259 p += STRLEN(p);
5260 if (nchars == 1)
5261 STRCPY(p, _("1 character"));
5262 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005263 sprintf((char *)p,
5264#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005265 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005266#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005267 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5268 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005269#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005270 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005271 }
5272}
5273
5274/*
5275 * Append message for missing line separator to IObuff.
5276 */
5277 static void
5278msg_add_eol()
5279{
5280 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5281}
5282
5283/*
5284 * Check modification time of file, before writing to it.
5285 * The size isn't checked, because using a tool like "gzip" takes care of
5286 * using the same timestamp but can't set the size.
5287 */
5288 static int
5289check_mtime(buf, st)
5290 buf_T *buf;
5291 struct stat *st;
5292{
5293 if (buf->b_mtime_read != 0
5294 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5295 {
5296 msg_scroll = TRUE; /* don't overwrite messages here */
5297 msg_silent = 0; /* must give this prompt */
5298 /* don't use emsg() here, don't want to flush the buffers */
5299 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5300 hl_attr(HLF_E));
5301 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5302 TRUE) == 'n')
5303 return FAIL;
5304 msg_scroll = FALSE; /* always overwrite the file message now */
5305 }
5306 return OK;
5307}
5308
5309 static int
5310time_differs(t1, t2)
5311 long t1, t2;
5312{
5313#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5314 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5315 * the seconds. Since the roundoff is done when flushing the inode, the
5316 * time may change unexpectedly by one second!!! */
5317 return (t1 - t2 > 1 || t2 - t1 > 1);
5318#else
5319 return (t1 != t2);
5320#endif
5321}
5322
5323/*
5324 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005325 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005326 *
5327 * Return FAIL for failure, OK otherwise.
5328 */
5329 static int
5330buf_write_bytes(ip)
5331 struct bw_info *ip;
5332{
5333 int wlen;
5334 char_u *buf = ip->bw_buf; /* data to write */
5335 int len = ip->bw_len; /* length of data */
5336#ifdef HAS_BW_FLAGS
5337 int flags = ip->bw_flags; /* extra flags */
5338#endif
5339
5340#ifdef FEAT_MBYTE
5341 /*
5342 * Skip conversion when writing the crypt magic number or the BOM.
5343 */
5344 if (!(flags & FIO_NOCONVERT))
5345 {
5346 char_u *p;
5347 unsigned c;
5348 int n;
5349
5350 if (flags & FIO_UTF8)
5351 {
5352 /*
5353 * Convert latin1 in the buffer to UTF-8 in the file.
5354 */
5355 p = ip->bw_conv_buf; /* translate to buffer */
5356 for (wlen = 0; wlen < len; ++wlen)
5357 p += utf_char2bytes(buf[wlen], p);
5358 buf = ip->bw_conv_buf;
5359 len = (int)(p - ip->bw_conv_buf);
5360 }
5361 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5362 {
5363 /*
5364 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5365 * Latin1 chars in the file.
5366 */
5367 if (flags & FIO_LATIN1)
5368 p = buf; /* translate in-place (can only get shorter) */
5369 else
5370 p = ip->bw_conv_buf; /* translate to buffer */
5371 for (wlen = 0; wlen < len; wlen += n)
5372 {
5373 if (wlen == 0 && ip->bw_restlen != 0)
5374 {
5375 int l;
5376
5377 /* Use remainder of previous call. Append the start of
5378 * buf[] to get a full sequence. Might still be too
5379 * short! */
5380 l = CONV_RESTLEN - ip->bw_restlen;
5381 if (l > len)
5382 l = len;
5383 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005384 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005385 if (n > ip->bw_restlen + len)
5386 {
5387 /* We have an incomplete byte sequence at the end to
5388 * be written. We can't convert it without the
5389 * remaining bytes. Keep them for the next call. */
5390 if (ip->bw_restlen + len > CONV_RESTLEN)
5391 return FAIL;
5392 ip->bw_restlen += len;
5393 break;
5394 }
5395 if (n > 1)
5396 c = utf_ptr2char(ip->bw_rest);
5397 else
5398 c = ip->bw_rest[0];
5399 if (n >= ip->bw_restlen)
5400 {
5401 n -= ip->bw_restlen;
5402 ip->bw_restlen = 0;
5403 }
5404 else
5405 {
5406 ip->bw_restlen -= n;
5407 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5408 (size_t)ip->bw_restlen);
5409 n = 0;
5410 }
5411 }
5412 else
5413 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005414 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005415 if (n > len - wlen)
5416 {
5417 /* We have an incomplete byte sequence at the end to
5418 * be written. We can't convert it without the
5419 * remaining bytes. Keep them for the next call. */
5420 if (len - wlen > CONV_RESTLEN)
5421 return FAIL;
5422 ip->bw_restlen = len - wlen;
5423 mch_memmove(ip->bw_rest, buf + wlen,
5424 (size_t)ip->bw_restlen);
5425 break;
5426 }
5427 if (n > 1)
5428 c = utf_ptr2char(buf + wlen);
5429 else
5430 c = buf[wlen];
5431 }
5432
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005433 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5434 {
5435 ip->bw_conv_error = TRUE;
5436 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5437 }
5438 if (c == NL)
5439 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440 }
5441 if (flags & FIO_LATIN1)
5442 len = (int)(p - buf);
5443 else
5444 {
5445 buf = ip->bw_conv_buf;
5446 len = (int)(p - ip->bw_conv_buf);
5447 }
5448 }
5449
5450# ifdef WIN3264
5451 else if (flags & FIO_CODEPAGE)
5452 {
5453 /*
5454 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5455 * codepage.
5456 */
5457 char_u *from;
5458 size_t fromlen;
5459 char_u *to;
5460 int u8c;
5461 BOOL bad = FALSE;
5462 int needed;
5463
5464 if (ip->bw_restlen > 0)
5465 {
5466 /* Need to concatenate the remainder of the previous call and
5467 * the bytes of the current call. Use the end of the
5468 * conversion buffer for this. */
5469 fromlen = len + ip->bw_restlen;
5470 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5471 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5472 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5473 }
5474 else
5475 {
5476 from = buf;
5477 fromlen = len;
5478 }
5479
5480 to = ip->bw_conv_buf;
5481 if (enc_utf8)
5482 {
5483 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5484 * The buffer has been allocated to be big enough. */
5485 while (fromlen > 0)
5486 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005487 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488 if (n > (int)fromlen) /* incomplete byte sequence */
5489 break;
5490 u8c = utf_ptr2char(from);
5491 *to++ = (u8c & 0xff);
5492 *to++ = (u8c >> 8);
5493 fromlen -= n;
5494 from += n;
5495 }
5496
5497 /* Copy remainder to ip->bw_rest[] to be used for the next
5498 * call. */
5499 if (fromlen > CONV_RESTLEN)
5500 {
5501 /* weird overlong sequence */
5502 ip->bw_conv_error = TRUE;
5503 return FAIL;
5504 }
5505 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005506 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005507 }
5508 else
5509 {
5510 /* Convert from enc_codepage to UCS-2, to the start of the
5511 * buffer. The buffer has been allocated to be big enough. */
5512 ip->bw_restlen = 0;
5513 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005514 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 NULL, 0);
5516 if (needed == 0)
5517 {
5518 /* When conversion fails there may be a trailing byte. */
5519 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005520 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005521 NULL, 0);
5522 if (needed == 0)
5523 {
5524 /* Conversion doesn't work. */
5525 ip->bw_conv_error = TRUE;
5526 return FAIL;
5527 }
5528 /* Save the trailing byte for the next call. */
5529 ip->bw_rest[0] = from[fromlen - 1];
5530 ip->bw_restlen = 1;
5531 }
5532 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005533 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005534 (LPWSTR)to, needed);
5535 if (needed == 0)
5536 {
5537 /* Safety check: Conversion doesn't work. */
5538 ip->bw_conv_error = TRUE;
5539 return FAIL;
5540 }
5541 to += needed * 2;
5542 }
5543
5544 fromlen = to - ip->bw_conv_buf;
5545 buf = to;
5546# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5547 if (FIO_GET_CP(flags) == CP_UTF8)
5548 {
5549 /* Convert from UCS-2 to UTF-8, using the remainder of the
5550 * conversion buffer. Fails when out of space. */
5551 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5552 {
5553 u8c = *from++;
5554 u8c += (*from++ << 8);
5555 to += utf_char2bytes(u8c, to);
5556 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5557 {
5558 ip->bw_conv_error = TRUE;
5559 return FAIL;
5560 }
5561 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005562 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005563 }
5564 else
5565#endif
5566 {
5567 /* Convert from UCS-2 to the codepage, using the remainder of
5568 * the conversion buffer. If the conversion uses the default
5569 * character "0", the data doesn't fit in this encoding, so
5570 * fail. */
5571 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5572 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005573 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5574 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575 if (bad)
5576 {
5577 ip->bw_conv_error = TRUE;
5578 return FAIL;
5579 }
5580 }
5581 }
5582# endif
5583
Bram Moolenaar56718732006-03-15 22:53:57 +00005584# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005585 else if (flags & FIO_MACROMAN)
5586 {
5587 /*
5588 * Convert UTF-8 or latin1 to Apple MacRoman.
5589 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005590 char_u *from;
5591 size_t fromlen;
5592
5593 if (ip->bw_restlen > 0)
5594 {
5595 /* Need to concatenate the remainder of the previous call and
5596 * the bytes of the current call. Use the end of the
5597 * conversion buffer for this. */
5598 fromlen = len + ip->bw_restlen;
5599 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5600 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5601 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5602 }
5603 else
5604 {
5605 from = buf;
5606 fromlen = len;
5607 }
5608
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005609 if (enc2macroman(from, fromlen,
5610 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5611 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005612 {
5613 ip->bw_conv_error = TRUE;
5614 return FAIL;
5615 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005616 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005617 }
5618# endif
5619
5620# ifdef USE_ICONV
5621 if (ip->bw_iconv_fd != (iconv_t)-1)
5622 {
5623 const char *from;
5624 size_t fromlen;
5625 char *to;
5626 size_t tolen;
5627
5628 /* Convert with iconv(). */
5629 if (ip->bw_restlen > 0)
5630 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005631 char *fp;
5632
Bram Moolenaar071d4272004-06-13 20:20:40 +00005633 /* Need to concatenate the remainder of the previous call and
5634 * the bytes of the current call. Use the end of the
5635 * conversion buffer for this. */
5636 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005637 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5638 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5639 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5640 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 tolen = ip->bw_conv_buflen - fromlen;
5642 }
5643 else
5644 {
5645 from = (const char *)buf;
5646 fromlen = len;
5647 tolen = ip->bw_conv_buflen;
5648 }
5649 to = (char *)ip->bw_conv_buf;
5650
5651 if (ip->bw_first)
5652 {
5653 size_t save_len = tolen;
5654
5655 /* output the initial shift state sequence */
5656 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5657
5658 /* There is a bug in iconv() on Linux (which appears to be
5659 * wide-spread) which sets "to" to NULL and messes up "tolen".
5660 */
5661 if (to == NULL)
5662 {
5663 to = (char *)ip->bw_conv_buf;
5664 tolen = save_len;
5665 }
5666 ip->bw_first = FALSE;
5667 }
5668
5669 /*
5670 * If iconv() has an error or there is not enough room, fail.
5671 */
5672 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5673 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5674 || fromlen > CONV_RESTLEN)
5675 {
5676 ip->bw_conv_error = TRUE;
5677 return FAIL;
5678 }
5679
5680 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5681 if (fromlen > 0)
5682 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5683 ip->bw_restlen = (int)fromlen;
5684
5685 buf = ip->bw_conv_buf;
5686 len = (int)((char_u *)to - ip->bw_conv_buf);
5687 }
5688# endif
5689 }
5690#endif /* FEAT_MBYTE */
5691
5692#ifdef FEAT_CRYPT
5693 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005694 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005695#endif
5696
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005697 wlen = write_eintr(ip->bw_fd, buf, len);
5698 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005699}
5700
5701#ifdef FEAT_MBYTE
5702/*
5703 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005704 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005705 */
5706 static int
5707ucs2bytes(c, pp, flags)
5708 unsigned c; /* in: character */
5709 char_u **pp; /* in/out: pointer to result */
5710 int flags; /* FIO_ flags */
5711{
5712 char_u *p = *pp;
5713 int error = FALSE;
5714 int cc;
5715
5716
5717 if (flags & FIO_UCS4)
5718 {
5719 if (flags & FIO_ENDIAN_L)
5720 {
5721 *p++ = c;
5722 *p++ = (c >> 8);
5723 *p++ = (c >> 16);
5724 *p++ = (c >> 24);
5725 }
5726 else
5727 {
5728 *p++ = (c >> 24);
5729 *p++ = (c >> 16);
5730 *p++ = (c >> 8);
5731 *p++ = c;
5732 }
5733 }
5734 else if (flags & (FIO_UCS2 | FIO_UTF16))
5735 {
5736 if (c >= 0x10000)
5737 {
5738 if (flags & FIO_UTF16)
5739 {
5740 /* Make two words, ten bits of the character in each. First
5741 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5742 c -= 0x10000;
5743 if (c >= 0x100000)
5744 error = TRUE;
5745 cc = ((c >> 10) & 0x3ff) + 0xd800;
5746 if (flags & FIO_ENDIAN_L)
5747 {
5748 *p++ = cc;
5749 *p++ = ((unsigned)cc >> 8);
5750 }
5751 else
5752 {
5753 *p++ = ((unsigned)cc >> 8);
5754 *p++ = cc;
5755 }
5756 c = (c & 0x3ff) + 0xdc00;
5757 }
5758 else
5759 error = TRUE;
5760 }
5761 if (flags & FIO_ENDIAN_L)
5762 {
5763 *p++ = c;
5764 *p++ = (c >> 8);
5765 }
5766 else
5767 {
5768 *p++ = (c >> 8);
5769 *p++ = c;
5770 }
5771 }
5772 else /* Latin1 */
5773 {
5774 if (c >= 0x100)
5775 {
5776 error = TRUE;
5777 *p++ = 0xBF;
5778 }
5779 else
5780 *p++ = c;
5781 }
5782
5783 *pp = p;
5784 return error;
5785}
5786
5787/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005788 * Return TRUE if file encoding "fenc" requires conversion from or to
5789 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005790 */
5791 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005792need_conversion(fenc)
5793 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005795 int same_encoding;
5796 int enc_flags;
5797 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005799 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005800 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005801 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005802 fenc_flags = 0;
5803 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005804 else
5805 {
5806 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5807 * "ucs-4be", etc. */
5808 enc_flags = get_fio_flags(p_enc);
5809 fenc_flags = get_fio_flags(fenc);
5810 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5811 }
5812 if (same_encoding)
5813 {
5814 /* Specified encoding matches with 'encoding'. This requires
5815 * conversion when 'encoding' is Unicode but not UTF-8. */
5816 return enc_unicode != 0;
5817 }
5818
5819 /* Encodings differ. However, conversion is not needed when 'enc' is any
5820 * Unicode encoding and the file is UTF-8. */
5821 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005822}
5823
5824/*
5825 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5826 * internal conversion.
5827 * if "ptr" is an empty string, use 'encoding'.
5828 */
5829 static int
5830get_fio_flags(ptr)
5831 char_u *ptr;
5832{
5833 int prop;
5834
5835 if (*ptr == NUL)
5836 ptr = p_enc;
5837
5838 prop = enc_canon_props(ptr);
5839 if (prop & ENC_UNICODE)
5840 {
5841 if (prop & ENC_2BYTE)
5842 {
5843 if (prop & ENC_ENDIAN_L)
5844 return FIO_UCS2 | FIO_ENDIAN_L;
5845 return FIO_UCS2;
5846 }
5847 if (prop & ENC_4BYTE)
5848 {
5849 if (prop & ENC_ENDIAN_L)
5850 return FIO_UCS4 | FIO_ENDIAN_L;
5851 return FIO_UCS4;
5852 }
5853 if (prop & ENC_2WORD)
5854 {
5855 if (prop & ENC_ENDIAN_L)
5856 return FIO_UTF16 | FIO_ENDIAN_L;
5857 return FIO_UTF16;
5858 }
5859 return FIO_UTF8;
5860 }
5861 if (prop & ENC_LATIN1)
5862 return FIO_LATIN1;
5863 /* must be ENC_DBCS, requires iconv() */
5864 return 0;
5865}
5866
5867#ifdef WIN3264
5868/*
5869 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5870 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5871 * Used for conversion between 'encoding' and 'fileencoding'.
5872 */
5873 static int
5874get_win_fio_flags(ptr)
5875 char_u *ptr;
5876{
5877 int cp;
5878
5879 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5880 if (!enc_utf8 && enc_codepage <= 0)
5881 return 0;
5882
5883 cp = encname2codepage(ptr);
5884 if (cp == 0)
5885 {
5886# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5887 if (STRCMP(ptr, "utf-8") == 0)
5888 cp = CP_UTF8;
5889 else
5890# endif
5891 return 0;
5892 }
5893 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5894}
5895#endif
5896
5897#ifdef MACOS_X
5898/*
5899 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5900 * needed for the internal conversion to/from utf-8 or latin1.
5901 */
5902 static int
5903get_mac_fio_flags(ptr)
5904 char_u *ptr;
5905{
5906 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5907 && (enc_canon_props(ptr) & ENC_MACROMAN))
5908 return FIO_MACROMAN;
5909 return 0;
5910}
5911#endif
5912
5913/*
5914 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5915 * "size" must be at least 2.
5916 * Return the name of the encoding and set "*lenp" to the length.
5917 * Returns NULL when no BOM found.
5918 */
5919 static char_u *
5920check_for_bom(p, size, lenp, flags)
5921 char_u *p;
5922 long size;
5923 int *lenp;
5924 int flags;
5925{
5926 char *name = NULL;
5927 int len = 2;
5928
5929 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005930 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005931 {
5932 name = "utf-8"; /* EF BB BF */
5933 len = 3;
5934 }
5935 else if (p[0] == 0xff && p[1] == 0xfe)
5936 {
5937 if (size >= 4 && p[2] == 0 && p[3] == 0
5938 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5939 {
5940 name = "ucs-4le"; /* FF FE 00 00 */
5941 len = 4;
5942 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005943 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005945 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5946 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005947 name = "utf-16le"; /* FF FE */
5948 }
5949 else if (p[0] == 0xfe && p[1] == 0xff
5950 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5951 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005952 /* Default to utf-16, it works also for ucs-2 text. */
5953 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005955 else
5956 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005957 }
5958 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5959 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5960 {
5961 name = "ucs-4"; /* 00 00 FE FF */
5962 len = 4;
5963 }
5964
5965 *lenp = len;
5966 return (char_u *)name;
5967}
5968
5969/*
5970 * Generate a BOM in "buf[4]" for encoding "name".
5971 * Return the length of the BOM (zero when no BOM).
5972 */
5973 static int
5974make_bom(buf, name)
5975 char_u *buf;
5976 char_u *name;
5977{
5978 int flags;
5979 char_u *p;
5980
5981 flags = get_fio_flags(name);
5982
5983 /* Can't put a BOM in a non-Unicode file. */
5984 if (flags == FIO_LATIN1 || flags == 0)
5985 return 0;
5986
5987 if (flags == FIO_UTF8) /* UTF-8 */
5988 {
5989 buf[0] = 0xef;
5990 buf[1] = 0xbb;
5991 buf[2] = 0xbf;
5992 return 3;
5993 }
5994 p = buf;
5995 (void)ucs2bytes(0xfeff, &p, flags);
5996 return (int)(p - buf);
5997}
5998#endif
5999
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006000#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006001 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006002/*
6003 * Try to find a shortname by comparing the fullname with the current
6004 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006005 * Returns "full_path" or pointer into "full_path" if shortened.
6006 */
6007 char_u *
6008shorten_fname1(full_path)
6009 char_u *full_path;
6010{
6011 char_u dirname[MAXPATHL];
6012 char_u *p = full_path;
6013
6014 if (mch_dirname(dirname, MAXPATHL) == OK)
6015 {
6016 p = shorten_fname(full_path, dirname);
6017 if (p == NULL || *p == NUL)
6018 p = full_path;
6019 }
6020 return p;
6021}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006022#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006023
6024/*
6025 * Try to find a shortname by comparing the fullname with the current
6026 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006027 * Returns NULL if not shorter name possible, pointer into "full_path"
6028 * otherwise.
6029 */
6030 char_u *
6031shorten_fname(full_path, dir_name)
6032 char_u *full_path;
6033 char_u *dir_name;
6034{
6035 int len;
6036 char_u *p;
6037
6038 if (full_path == NULL)
6039 return NULL;
6040 len = (int)STRLEN(dir_name);
6041 if (fnamencmp(dir_name, full_path, len) == 0)
6042 {
6043 p = full_path + len;
6044#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6045 /*
6046 * MSDOS: when a file is in the root directory, dir_name will end in a
6047 * slash, since C: by itself does not define a specific dir. In this
6048 * case p may already be correct. <negri>
6049 */
6050 if (!((len > 2) && (*(p - 2) == ':')))
6051#endif
6052 {
6053 if (vim_ispathsep(*p))
6054 ++p;
6055#ifndef VMS /* the path separator is always part of the path */
6056 else
6057 p = NULL;
6058#endif
6059 }
6060 }
6061#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6062 /*
6063 * When using a file in the current drive, remove the drive name:
6064 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6065 * a floppy from "A:\dir" to "B:\dir".
6066 */
6067 else if (len > 3
6068 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6069 && full_path[1] == ':'
6070 && vim_ispathsep(full_path[2]))
6071 p = full_path + 2;
6072#endif
6073 else
6074 p = NULL;
6075 return p;
6076}
6077
6078/*
6079 * Shorten filenames for all buffers.
6080 * When "force" is TRUE: Use full path from now on for files currently being
6081 * edited, both for file name and swap file name. Try to shorten the file
6082 * names a bit, if safe to do so.
6083 * When "force" is FALSE: Only try to shorten absolute file names.
6084 * For buffers that have buftype "nofile" or "scratch": never change the file
6085 * name.
6086 */
6087 void
6088shorten_fnames(force)
6089 int force;
6090{
6091 char_u dirname[MAXPATHL];
6092 buf_T *buf;
6093 char_u *p;
6094
6095 mch_dirname(dirname, MAXPATHL);
6096 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6097 {
6098 if (buf->b_fname != NULL
6099#ifdef FEAT_QUICKFIX
6100 && !bt_nofile(buf)
6101#endif
6102 && !path_with_url(buf->b_fname)
6103 && (force
6104 || buf->b_sfname == NULL
6105 || mch_isFullName(buf->b_sfname)))
6106 {
6107 vim_free(buf->b_sfname);
6108 buf->b_sfname = NULL;
6109 p = shorten_fname(buf->b_ffname, dirname);
6110 if (p != NULL)
6111 {
6112 buf->b_sfname = vim_strsave(p);
6113 buf->b_fname = buf->b_sfname;
6114 }
6115 if (p == NULL || buf->b_fname == NULL)
6116 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006118
6119 /* Always make the swap file name a full path, a "nofile" buffer may
6120 * also have a swap file. */
6121 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006122 }
6123#ifdef FEAT_WINDOWS
6124 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006125 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126#endif
6127}
6128
6129#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6130 || defined(FEAT_GUI_MSWIN) \
6131 || defined(FEAT_GUI_MAC) \
6132 || defined(PROTO)
6133/*
6134 * Shorten all filenames in "fnames[count]" by current directory.
6135 */
6136 void
6137shorten_filenames(fnames, count)
6138 char_u **fnames;
6139 int count;
6140{
6141 int i;
6142 char_u dirname[MAXPATHL];
6143 char_u *p;
6144
6145 if (fnames == NULL || count < 1)
6146 return;
6147 mch_dirname(dirname, sizeof(dirname));
6148 for (i = 0; i < count; ++i)
6149 {
6150 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6151 {
6152 /* shorten_fname() returns pointer in given "fnames[i]". If free
6153 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6154 * "p" first then free fnames[i]. */
6155 p = vim_strsave(p);
6156 vim_free(fnames[i]);
6157 fnames[i] = p;
6158 }
6159 }
6160}
6161#endif
6162
6163/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006164 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006165 * fo_o_h.ext for MSDOS or when shortname option set.
6166 *
6167 * Assumed that fname is a valid name found in the filesystem we assure that
6168 * the return value is a different name and ends in 'ext'.
6169 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6170 * characters otherwise.
6171 * Space for the returned name is allocated, must be freed later.
6172 * Returns NULL when out of memory.
6173 */
6174 char_u *
6175modname(fname, ext, prepend_dot)
6176 char_u *fname, *ext;
6177 int prepend_dot; /* may prepend a '.' to file name */
6178{
6179 return buf_modname(
6180#ifdef SHORT_FNAME
6181 TRUE,
6182#else
6183 (curbuf->b_p_sn || curbuf->b_shortname),
6184#endif
6185 fname, ext, prepend_dot);
6186}
6187
6188 char_u *
6189buf_modname(shortname, fname, ext, prepend_dot)
6190 int shortname; /* use 8.3 file name */
6191 char_u *fname, *ext;
6192 int prepend_dot; /* may prepend a '.' to file name */
6193{
6194 char_u *retval;
6195 char_u *s;
6196 char_u *e;
6197 char_u *ptr;
6198 int fnamelen, extlen;
6199
6200 extlen = (int)STRLEN(ext);
6201
6202 /*
6203 * If there is no file name we must get the name of the current directory
6204 * (we need the full path in case :cd is used).
6205 */
6206 if (fname == NULL || *fname == NUL)
6207 {
6208 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6209 if (retval == NULL)
6210 return NULL;
6211 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6212 (fnamelen = (int)STRLEN(retval)) == 0)
6213 {
6214 vim_free(retval);
6215 return NULL;
6216 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006217 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006218 {
6219 retval[fnamelen++] = PATHSEP;
6220 retval[fnamelen] = NUL;
6221 }
6222#ifndef SHORT_FNAME
6223 prepend_dot = FALSE; /* nothing to prepend a dot to */
6224#endif
6225 }
6226 else
6227 {
6228 fnamelen = (int)STRLEN(fname);
6229 retval = alloc((unsigned)(fnamelen + extlen + 3));
6230 if (retval == NULL)
6231 return NULL;
6232 STRCPY(retval, fname);
6233#ifdef VMS
6234 vms_remove_version(retval); /* we do not need versions here */
6235#endif
6236 }
6237
6238 /*
6239 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6240 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6241 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6242 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6243 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006244 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006245 {
6246#ifndef RISCOS
6247 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006248# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006250# else
6251# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006252 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006253# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006255 )
6256 if (*ptr == '.') /* replace '.' by '_' */
6257 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006258#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006259 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006260 {
6261 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006263 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006264 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265
6266 /* the file name has at most BASENAMELEN characters. */
6267#ifndef SHORT_FNAME
6268 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6269 ptr[BASENAMELEN] = '\0';
6270#endif
6271
6272 s = ptr + STRLEN(ptr);
6273
6274 /*
6275 * For 8.3 file names we may have to reduce the length.
6276 */
6277#ifdef USE_LONG_FNAME
6278 if (!USE_LONG_FNAME || shortname)
6279#else
6280# ifndef SHORT_FNAME
6281 if (shortname)
6282# endif
6283#endif
6284 {
6285 /*
6286 * If there is no file name, or the file name ends in '/', and the
6287 * extension starts with '.', put a '_' before the dot, because just
6288 * ".ext" is invalid.
6289 */
6290 if (fname == NULL || *fname == NUL
6291 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6292 {
6293#ifdef RISCOS
6294 if (*ext == '/')
6295#else
6296 if (*ext == '.')
6297#endif
6298 *s++ = '_';
6299 }
6300 /*
6301 * If the extension starts with '.', truncate the base name at 8
6302 * characters
6303 */
6304#ifdef RISCOS
6305 /* We normally use '/', but swap files are '_' */
6306 else if (*ext == '/' || *ext == '_')
6307#else
6308 else if (*ext == '.')
6309#endif
6310 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006311 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006312 {
6313 s = ptr + 8;
6314 *s = '\0';
6315 }
6316 }
6317 /*
6318 * If the extension doesn't start with '.', and the file name
6319 * doesn't have an extension yet, append a '.'
6320 */
6321#ifdef RISCOS
6322 else if ((e = vim_strchr(ptr, '/')) == NULL)
6323 *s++ = '/';
6324#else
6325 else if ((e = vim_strchr(ptr, '.')) == NULL)
6326 *s++ = '.';
6327#endif
6328 /*
6329 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006330 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006331 */
6332 else if ((int)STRLEN(e) + extlen > 4)
6333 s = e + 4 - extlen;
6334 }
6335#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6336 /*
6337 * If there is no file name, and the extension starts with '.', put a
6338 * '_' before the dot, because just ".ext" may be invalid if it's on a
6339 * FAT partition, and on HPFS it doesn't matter.
6340 */
6341 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6342 *s++ = '_';
6343#endif
6344
6345 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006346 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006347 * ext can start with '.' and cannot exceed 3 more characters.
6348 */
6349 STRCPY(s, ext);
6350
6351#ifndef SHORT_FNAME
6352 /*
6353 * Prepend the dot.
6354 */
6355 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6356#ifdef RISCOS
6357 '/'
6358#else
6359 '.'
6360#endif
6361#ifdef USE_LONG_FNAME
6362 && USE_LONG_FNAME
6363#endif
6364 )
6365 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006366 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006367#ifdef RISCOS
6368 *e = '/';
6369#else
6370 *e = '.';
6371#endif
6372 }
6373#endif
6374
6375 /*
6376 * Check that, after appending the extension, the file name is really
6377 * different.
6378 */
6379 if (fname != NULL && STRCMP(fname, retval) == 0)
6380 {
6381 /* we search for a character that can be replaced by '_' */
6382 while (--s >= ptr)
6383 {
6384 if (*s != '_')
6385 {
6386 *s = '_';
6387 break;
6388 }
6389 }
6390 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6391 *ptr = 'v';
6392 }
6393 return retval;
6394}
6395
6396/*
6397 * Like fgets(), but if the file line is too long, it is truncated and the
6398 * rest of the line is thrown away. Returns TRUE for end-of-file.
6399 */
6400 int
6401vim_fgets(buf, size, fp)
6402 char_u *buf;
6403 int size;
6404 FILE *fp;
6405{
6406 char *eof;
6407#define FGETS_SIZE 200
6408 char tbuf[FGETS_SIZE];
6409
6410 buf[size - 2] = NUL;
6411#ifdef USE_CR
6412 eof = fgets_cr((char *)buf, size, fp);
6413#else
6414 eof = fgets((char *)buf, size, fp);
6415#endif
6416 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6417 {
6418 buf[size - 1] = NUL; /* Truncate the line */
6419
6420 /* Now throw away the rest of the line: */
6421 do
6422 {
6423 tbuf[FGETS_SIZE - 2] = NUL;
6424#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006425 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006426#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006427 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006428#endif
6429 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6430 }
6431 return (eof == NULL);
6432}
6433
6434#if defined(USE_CR) || defined(PROTO)
6435/*
6436 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6437 * Returns TRUE for end-of-file.
6438 * Only used for the Mac, because it's much slower than vim_fgets().
6439 */
6440 int
6441tag_fgets(buf, size, fp)
6442 char_u *buf;
6443 int size;
6444 FILE *fp;
6445{
6446 int i = 0;
6447 int c;
6448 int eof = FALSE;
6449
6450 for (;;)
6451 {
6452 c = fgetc(fp);
6453 if (c == EOF)
6454 {
6455 eof = TRUE;
6456 break;
6457 }
6458 if (c == '\r')
6459 {
6460 /* Always store a NL for end-of-line. */
6461 if (i < size - 1)
6462 buf[i++] = '\n';
6463 c = fgetc(fp);
6464 if (c != '\n') /* Macintosh format: single CR. */
6465 ungetc(c, fp);
6466 break;
6467 }
6468 if (i < size - 1)
6469 buf[i++] = c;
6470 if (c == '\n')
6471 break;
6472 }
6473 buf[i] = NUL;
6474 return eof;
6475}
6476#endif
6477
6478/*
6479 * rename() only works if both files are on the same file system, this
6480 * function will (attempts to?) copy the file across if rename fails -- webb
6481 * Return -1 for failure, 0 for success.
6482 */
6483 int
6484vim_rename(from, to)
6485 char_u *from;
6486 char_u *to;
6487{
6488 int fd_in;
6489 int fd_out;
6490 int n;
6491 char *errmsg = NULL;
6492 char *buffer;
6493#ifdef AMIGA
6494 BPTR flock;
6495#endif
6496 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006497 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006498#ifdef HAVE_ACL
6499 vim_acl_T acl; /* ACL from original file */
6500#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006501#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6502 int use_tmp_file = FALSE;
6503#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006504
6505 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006506 * When the names are identical, there is nothing to do. When they refer
6507 * to the same file (ignoring case and slash/backslash differences) but
6508 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006509 */
6510 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006511 {
6512#ifdef CASE_INSENSITIVE_FILENAME
6513 if (STRCMP(gettail(from), gettail(to)) != 0)
6514 use_tmp_file = TRUE;
6515 else
6516#endif
6517 return 0;
6518 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006519
6520 /*
6521 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6522 */
6523 if (mch_stat((char *)from, &st) < 0)
6524 return -1;
6525
Bram Moolenaar3576da72008-12-30 15:15:57 +00006526#ifdef UNIX
6527 {
6528 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006529
6530 /* It's possible for the source and destination to be the same file.
6531 * This happens when "from" and "to" differ in case and are on a FAT32
6532 * filesystem. In that case go through a temp file name. */
6533 if (mch_stat((char *)to, &st_to) >= 0
6534 && st.st_dev == st_to.st_dev
6535 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006536 use_tmp_file = TRUE;
6537 }
6538#endif
6539
6540#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6541 if (use_tmp_file)
6542 {
6543 char tempname[MAXPATHL + 1];
6544
6545 /*
6546 * Find a name that doesn't exist and is in the same directory.
6547 * Rename "from" to "tempname" and then rename "tempname" to "to".
6548 */
6549 if (STRLEN(from) >= MAXPATHL - 5)
6550 return -1;
6551 STRCPY(tempname, from);
6552 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006553 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006554 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6555 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006556 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006557 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006558 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006559 if (mch_rename(tempname, (char *)to) == 0)
6560 return 0;
6561 /* Strange, the second step failed. Try moving the
6562 * file back and return failure. */
6563 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006564 return -1;
6565 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006566 /* If it fails for one temp name it will most likely fail
6567 * for any temp name, give up. */
6568 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006569 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006570 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006571 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006572 }
6573#endif
6574
Bram Moolenaar071d4272004-06-13 20:20:40 +00006575 /*
6576 * Delete the "to" file, this is required on some systems to make the
6577 * mch_rename() work, on other systems it makes sure that we don't have
6578 * two files when the mch_rename() fails.
6579 */
6580
6581#ifdef AMIGA
6582 /*
6583 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6584 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006585 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006586 * deleting the "from" file (horror!) we lock it during the remove.
6587 *
6588 * When used for making a backup before writing the file: This should not
6589 * happen with ":w", because startscript() should detect this problem and
6590 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6591 * name. This problem does exist with ":w filename", but then the
6592 * original file will be somewhere else so the backup isn't really
6593 * important. If autoscripting is off the rename may fail.
6594 */
6595 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6596#endif
6597 mch_remove(to);
6598#ifdef AMIGA
6599 if (flock)
6600 UnLock(flock);
6601#endif
6602
6603 /*
6604 * First try a normal rename, return if it works.
6605 */
6606 if (mch_rename((char *)from, (char *)to) == 0)
6607 return 0;
6608
6609 /*
6610 * Rename() failed, try copying the file.
6611 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006612 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006613#ifdef HAVE_ACL
6614 /* For systems that support ACL: get the ACL from the original file. */
6615 acl = mch_get_acl(from);
6616#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006617 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6618 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006619 {
6620#ifdef HAVE_ACL
6621 mch_free_acl(acl);
6622#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006624 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006625
6626 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006627 fd_out = mch_open((char *)to,
6628 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006629 if (fd_out == -1)
6630 {
6631 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006632#ifdef HAVE_ACL
6633 mch_free_acl(acl);
6634#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006635 return -1;
6636 }
6637
6638 buffer = (char *)alloc(BUFSIZE);
6639 if (buffer == NULL)
6640 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006642 close(fd_in);
6643#ifdef HAVE_ACL
6644 mch_free_acl(acl);
6645#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006646 return -1;
6647 }
6648
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006649 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6650 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006651 {
6652 errmsg = _("E208: Error writing to \"%s\"");
6653 break;
6654 }
6655
6656 vim_free(buffer);
6657 close(fd_in);
6658 if (close(fd_out) < 0)
6659 errmsg = _("E209: Error closing \"%s\"");
6660 if (n < 0)
6661 {
6662 errmsg = _("E210: Error reading \"%s\"");
6663 to = from;
6664 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006665#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006666 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006667#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006668#ifdef HAVE_ACL
6669 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006670 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006671#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006672 if (errmsg != NULL)
6673 {
6674 EMSG2(errmsg, to);
6675 return -1;
6676 }
6677 mch_remove(from);
6678 return 0;
6679}
6680
6681static int already_warned = FALSE;
6682
6683/*
6684 * Check if any not hidden buffer has been changed.
6685 * Postpone the check if there are characters in the stuff buffer, a global
6686 * command is being executed, a mapping is being executed or an autocommand is
6687 * busy.
6688 * Returns TRUE if some message was written (screen should be redrawn and
6689 * cursor positioned).
6690 */
6691 int
6692check_timestamps(focus)
6693 int focus; /* called for GUI focus event */
6694{
6695 buf_T *buf;
6696 int didit = 0;
6697 int n;
6698
6699 /* Don't check timestamps while system() or another low-level function may
6700 * cause us to lose and gain focus. */
6701 if (no_check_timestamps > 0)
6702 return FALSE;
6703
6704 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6705 * event and we would keep on checking if the file is steadily growing.
6706 * Do check again after typing something. */
6707 if (focus && did_check_timestamps)
6708 {
6709 need_check_timestamps = TRUE;
6710 return FALSE;
6711 }
6712
6713 if (!stuff_empty() || global_busy || !typebuf_typed()
6714#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006715 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716#endif
6717 )
6718 need_check_timestamps = TRUE; /* check later */
6719 else
6720 {
6721 ++no_wait_return;
6722 did_check_timestamps = TRUE;
6723 already_warned = FALSE;
6724 for (buf = firstbuf; buf != NULL; )
6725 {
6726 /* Only check buffers in a window. */
6727 if (buf->b_nwindows > 0)
6728 {
6729 n = buf_check_timestamp(buf, focus);
6730 if (didit < n)
6731 didit = n;
6732 if (n > 0 && !buf_valid(buf))
6733 {
6734 /* Autocommands have removed the buffer, start at the
6735 * first one again. */
6736 buf = firstbuf;
6737 continue;
6738 }
6739 }
6740 buf = buf->b_next;
6741 }
6742 --no_wait_return;
6743 need_check_timestamps = FALSE;
6744 if (need_wait_return && didit == 2)
6745 {
6746 /* make sure msg isn't overwritten */
6747 msg_puts((char_u *)"\n");
6748 out_flush();
6749 }
6750 }
6751 return didit;
6752}
6753
6754/*
6755 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6756 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6757 * empty.
6758 */
6759 static int
6760move_lines(frombuf, tobuf)
6761 buf_T *frombuf;
6762 buf_T *tobuf;
6763{
6764 buf_T *tbuf = curbuf;
6765 int retval = OK;
6766 linenr_T lnum;
6767 char_u *p;
6768
6769 /* Copy the lines in "frombuf" to "tobuf". */
6770 curbuf = tobuf;
6771 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6772 {
6773 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6774 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6775 {
6776 vim_free(p);
6777 retval = FAIL;
6778 break;
6779 }
6780 vim_free(p);
6781 }
6782
6783 /* Delete all the lines in "frombuf". */
6784 if (retval != FAIL)
6785 {
6786 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006787 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6788 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006789 {
6790 /* Oops! We could try putting back the saved lines, but that
6791 * might fail again... */
6792 retval = FAIL;
6793 break;
6794 }
6795 }
6796
6797 curbuf = tbuf;
6798 return retval;
6799}
6800
6801/*
6802 * Check if buffer "buf" has been changed.
6803 * Also check if the file for a new buffer unexpectedly appeared.
6804 * return 1 if a changed buffer was found.
6805 * return 2 if a message has been displayed.
6806 * return 0 otherwise.
6807 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006808 int
6809buf_check_timestamp(buf, focus)
6810 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006811 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006812{
6813 struct stat st;
6814 int stat_res;
6815 int retval = 0;
6816 char_u *path;
6817 char_u *tbuf;
6818 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006819 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820 int helpmesg = FALSE;
6821 int reload = FALSE;
6822#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6823 int can_reload = FALSE;
6824#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006825 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 int orig_mode = buf->b_orig_mode;
6827#ifdef FEAT_GUI
6828 int save_mouse_correct = need_mouse_correct;
6829#endif
6830#ifdef FEAT_AUTOCMD
6831 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006832 int n;
6833 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006835 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006836
6837 /* If there is no file name, the buffer is not loaded, 'buftype' is
6838 * set, we are in the middle of a save or being called recursively: ignore
6839 * this buffer. */
6840 if (buf->b_ffname == NULL
6841 || buf->b_ml.ml_mfp == NULL
6842#if defined(FEAT_QUICKFIX)
6843 || *buf->b_p_bt != NUL
6844#endif
6845 || buf->b_saving
6846#ifdef FEAT_AUTOCMD
6847 || busy
6848#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006849#ifdef FEAT_NETBEANS_INTG
6850 || isNetbeansBuffer(buf)
6851#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006852 )
6853 return 0;
6854
6855 if ( !(buf->b_flags & BF_NOTEDITED)
6856 && buf->b_mtime != 0
6857 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6858 || time_differs((long)st.st_mtime, buf->b_mtime)
6859#ifdef HAVE_ST_MODE
6860 || (int)st.st_mode != buf->b_orig_mode
6861#else
6862 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6863#endif
6864 ))
6865 {
6866 retval = 1;
6867
Bram Moolenaar316059c2006-01-14 21:18:42 +00006868 /* set b_mtime to stop further warnings (e.g., when executing
6869 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870 if (stat_res < 0)
6871 {
6872 buf->b_mtime = 0;
6873 buf->b_orig_size = 0;
6874 buf->b_orig_mode = 0;
6875 }
6876 else
6877 buf_store_time(buf, &st, buf->b_ffname);
6878
6879 /* Don't do anything for a directory. Might contain the file
6880 * explorer. */
6881 if (mch_isdir(buf->b_fname))
6882 ;
6883
6884 /*
6885 * If 'autoread' is set, the buffer has no changes and the file still
6886 * exists, reload the buffer. Use the buffer-local option value if it
6887 * was set, the global option value otherwise.
6888 */
6889 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6890 && !bufIsChanged(buf) && stat_res >= 0)
6891 reload = TRUE;
6892 else
6893 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006894 if (stat_res < 0)
6895 reason = "deleted";
6896 else if (bufIsChanged(buf))
6897 reason = "conflict";
6898 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6899 reason = "changed";
6900 else if (orig_mode != buf->b_orig_mode)
6901 reason = "mode";
6902 else
6903 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006904
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006905#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006906 /*
6907 * Only give the warning if there are no FileChangedShell
6908 * autocommands.
6909 * Avoid being called recursively by setting "busy".
6910 */
6911 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006912# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006913 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6914 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006915# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006916 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006917 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6918 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006919 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006920 busy = FALSE;
6921 if (n)
6922 {
6923 if (!buf_valid(buf))
6924 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006925# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006926 s = get_vim_var_str(VV_FCS_CHOICE);
6927 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6928 reload = TRUE;
6929 else if (STRCMP(s, "ask") == 0)
6930 n = FALSE;
6931 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006932# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006933 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006935 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006936#endif
6937 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006938 if (*reason == 'd')
6939 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 else
6941 {
6942 helpmesg = TRUE;
6943#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6944 can_reload = TRUE;
6945#endif
6946 /*
6947 * Check if the file contents really changed to avoid
6948 * giving a warning when only the timestamp was set (e.g.,
6949 * checked out of CVS). Always warn when the buffer was
6950 * changed.
6951 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006952 if (reason[2] == 'n')
6953 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006954 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006955 mesg2 = _("See \":help W12\" for more info.");
6956 }
6957 else if (reason[1] == 'h')
6958 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006959 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006960 mesg2 = _("See \":help W11\" for more info.");
6961 }
6962 else if (*reason == 'm')
6963 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006964 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006965 mesg2 = _("See \":help W16\" for more info.");
6966 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006967 else
6968 /* Only timestamp changed, store it to avoid a warning
6969 * in check_mtime() later. */
6970 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006971 }
6972 }
6973 }
6974
6975 }
6976 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6977 && vim_fexists(buf->b_ffname))
6978 {
6979 retval = 1;
6980 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6981 buf->b_flags |= BF_NEW_W;
6982#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6983 can_reload = TRUE;
6984#endif
6985 }
6986
6987 if (mesg != NULL)
6988 {
6989 path = home_replace_save(buf, buf->b_fname);
6990 if (path != NULL)
6991 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006992 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993 mesg2 = "";
6994 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6995 + STRLEN(mesg2) + 2));
6996 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006997#ifdef FEAT_EVAL
6998 /* Set warningmsg here, before the unimportant and output-specific
6999 * mesg2 has been appended. */
7000 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7001#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007002#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7003 if (can_reload)
7004 {
7005 if (*mesg2 != NUL)
7006 {
7007 STRCAT(tbuf, "\n");
7008 STRCAT(tbuf, mesg2);
7009 }
7010 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007011 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007012 reload = TRUE;
7013 }
7014 else
7015#endif
7016 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7017 {
7018 if (*mesg2 != NUL)
7019 {
7020 STRCAT(tbuf, "; ");
7021 STRCAT(tbuf, mesg2);
7022 }
7023 EMSG(tbuf);
7024 retval = 2;
7025 }
7026 else
7027 {
Bram Moolenaared203462004-06-16 11:19:22 +00007028# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007029 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007030# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007031 {
7032 msg_start();
7033 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7034 if (*mesg2 != NUL)
7035 msg_puts_attr((char_u *)mesg2,
7036 hl_attr(HLF_W) + MSG_HIST);
7037 msg_clr_eos();
7038 (void)msg_end();
7039 if (emsg_silent == 0)
7040 {
7041 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007042# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007043 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007044# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007045 /* give the user some time to think about it */
7046 ui_delay(1000L, TRUE);
7047
7048 /* don't redraw and erase the message */
7049 redraw_cmdline = FALSE;
7050 }
7051 }
7052 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053 }
7054
7055 vim_free(path);
7056 vim_free(tbuf);
7057 }
7058 }
7059
7060 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007061 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007062 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007063
Bram Moolenaar56718732006-03-15 22:53:57 +00007064#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007065 /* Trigger FileChangedShell when the file was changed in any way. */
7066 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007067 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7068 buf->b_fname, buf->b_fname, FALSE, buf);
7069#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007070#ifdef FEAT_GUI
7071 /* restore this in case an autocommand has set it; it would break
7072 * 'mousefocus' */
7073 need_mouse_correct = save_mouse_correct;
7074#endif
7075
7076 return retval;
7077}
7078
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007079/*
7080 * Reload a buffer that is already loaded.
7081 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007082 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7083 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007084 */
7085 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007086buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007087 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007088 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007089{
7090 exarg_T ea;
7091 pos_T old_cursor;
7092 linenr_T old_topline;
7093 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007094 buf_T *savebuf;
7095 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007096 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007097 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007098
7099 /* set curwin/curbuf for "buf" and save some things */
7100 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007101
7102 /* We only want to read the text from the file, not reset the syntax
7103 * highlighting, clear marks, diff status, etc. Force the fileformat
7104 * and encoding to be the same. */
7105 if (prep_exarg(&ea, buf) == OK)
7106 {
7107 old_cursor = curwin->w_cursor;
7108 old_topline = curwin->w_topline;
7109
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007110 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007111 {
7112 /* Save all the text, so that the reload can be undone.
7113 * Sync first so that this is a separate undo-able action. */
7114 u_sync(FALSE);
7115 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7116 flags |= READ_KEEP_UNDO;
7117 }
7118
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007119 /*
7120 * To behave like when a new file is edited (matters for
7121 * BufReadPost autocommands) we first need to delete the current
7122 * buffer contents. But if reading the file fails we should keep
7123 * the old contents. Can't use memory only, the file might be
7124 * too big. Use a hidden buffer to move the buffer contents to.
7125 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007126 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007127 savebuf = NULL;
7128 else
7129 {
7130 /* Allocate a buffer without putting it in the buffer list. */
7131 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007132 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007133 {
7134 /* Open the memline. */
7135 curbuf = savebuf;
7136 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007137 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007138 curbuf = buf;
7139 curwin->w_buffer = buf;
7140 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007141 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007142 || move_lines(buf, savebuf) == FAIL)
7143 {
7144 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7145 buf->b_fname);
7146 saved = FAIL;
7147 }
7148 }
7149
7150 if (saved == OK)
7151 {
7152 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7153#ifdef FEAT_AUTOCMD
7154 keep_filetype = TRUE; /* don't detect 'filetype' */
7155#endif
7156 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7157 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007158 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007159 {
7160#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7161 if (!aborting())
7162#endif
7163 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007164 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007165 {
7166 /* Put the text back from the save buffer. First
7167 * delete any lines that readfile() added. */
7168 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007169 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007170 break;
7171 (void)move_lines(savebuf, buf);
7172 }
7173 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007174 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007175 {
7176 /* Mark the buffer as unmodified and free undo info. */
7177 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007178 if ((flags & READ_KEEP_UNDO) == 0)
7179 {
7180 u_blockfree(buf);
7181 u_clearall(buf);
7182 }
7183 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007184 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007185 /* Mark all undo states as changed. */
7186 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007187 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007188 }
7189 }
7190 vim_free(ea.cmd);
7191
Bram Moolenaar8424a622006-04-19 21:23:36 +00007192 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007193 wipe_buffer(savebuf, FALSE);
7194
7195#ifdef FEAT_DIFF
7196 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007197 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007198#endif
7199
7200 /* Restore the topline and cursor position and check it (lines may
7201 * have been removed). */
7202 if (old_topline > curbuf->b_ml.ml_line_count)
7203 curwin->w_topline = curbuf->b_ml.ml_line_count;
7204 else
7205 curwin->w_topline = old_topline;
7206 curwin->w_cursor = old_cursor;
7207 check_cursor();
7208 update_topline();
7209#ifdef FEAT_AUTOCMD
7210 keep_filetype = FALSE;
7211#endif
7212#ifdef FEAT_FOLDING
7213 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007214 win_T *wp;
7215 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007216
7217 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007218 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007219 if (wp->w_buffer == curwin->w_buffer
7220 && !foldmethodIsManual(wp))
7221 foldUpdateAll(wp);
7222 }
7223#endif
7224 /* If the mode didn't change and 'readonly' was set, keep the old
7225 * value; the user probably used the ":view" command. But don't
7226 * reset it, might have had a read error. */
7227 if (orig_mode == curbuf->b_orig_mode)
7228 curbuf->b_p_ro |= old_ro;
7229 }
7230
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007231 /* restore curwin/curbuf and a few other things */
7232 aucmd_restbuf(&aco);
7233 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007234}
7235
Bram Moolenaar071d4272004-06-13 20:20:40 +00007236 void
7237buf_store_time(buf, st, fname)
7238 buf_T *buf;
7239 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007240 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007241{
7242 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007243 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244#ifdef HAVE_ST_MODE
7245 buf->b_orig_mode = (int)st->st_mode;
7246#else
7247 buf->b_orig_mode = mch_getperm(fname);
7248#endif
7249}
7250
7251/*
7252 * Adjust the line with missing eol, used for the next write.
7253 * Used for do_filter(), when the input lines for the filter are deleted.
7254 */
7255 void
7256write_lnum_adjust(offset)
7257 linenr_T offset;
7258{
Bram Moolenaardf177f62005-02-22 08:39:57 +00007259 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007260 write_no_eol_lnum += offset;
7261}
7262
7263#if defined(TEMPDIRNAMES) || defined(PROTO)
7264static long temp_count = 0; /* Temp filename counter. */
7265
7266/*
7267 * Delete the temp directory and all files it contains.
7268 */
7269 void
7270vim_deltempdir()
7271{
7272 char_u **files;
7273 int file_count;
7274 int i;
7275
7276 if (vim_tempdir != NULL)
7277 {
7278 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7279 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7280 EW_DIR|EW_FILE|EW_SILENT) == OK)
7281 {
7282 for (i = 0; i < file_count; ++i)
7283 mch_remove(files[i]);
7284 FreeWild(file_count, files);
7285 }
7286 gettail(NameBuff)[-1] = NUL;
7287 (void)mch_rmdir(NameBuff);
7288
7289 vim_free(vim_tempdir);
7290 vim_tempdir = NULL;
7291 }
7292}
7293#endif
7294
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007295#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007296/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007297 * Directory "tempdir" was created. Expand this name to a full path and put
7298 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7299 * "tempdir" must be no longer than MAXPATHL.
7300 */
7301 static void
7302vim_settempdir(tempdir)
7303 char_u *tempdir;
7304{
7305 char_u *buf;
7306
7307 buf = alloc((unsigned)MAXPATHL + 2);
7308 if (buf != NULL)
7309 {
7310 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7311 STRCPY(buf, tempdir);
7312# ifdef __EMX__
7313 if (vim_strchr(buf, '/') != NULL)
7314 STRCAT(buf, "/");
7315 else
7316# endif
7317 add_pathsep(buf);
7318 vim_tempdir = vim_strsave(buf);
7319 vim_free(buf);
7320 }
7321}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007322#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007323
7324/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007325 * vim_tempname(): Return a unique name that can be used for a temp file.
7326 *
7327 * The temp file is NOT created.
7328 *
7329 * The returned pointer is to allocated memory.
7330 * The returned pointer is NULL if no valid name was found.
7331 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007332 char_u *
7333vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007334 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007335{
7336#ifdef USE_TMPNAM
7337 char_u itmp[L_tmpnam]; /* use tmpnam() */
7338#else
7339 char_u itmp[TEMPNAMELEN];
7340#endif
7341
7342#ifdef TEMPDIRNAMES
7343 static char *(tempdirs[]) = {TEMPDIRNAMES};
7344 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007345# ifndef EEXIST
7346 struct stat st;
7347# endif
7348
7349 /*
7350 * This will create a directory for private use by this instance of Vim.
7351 * This is done once, and the same directory is used for all temp files.
7352 * This method avoids security problems because of symlink attacks et al.
7353 * It's also a bit faster, because we only need to check for an existing
7354 * file when creating the directory and not for each temp file.
7355 */
7356 if (vim_tempdir == NULL)
7357 {
7358 /*
7359 * Try the entries in TEMPDIRNAMES to create the temp directory.
7360 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007361 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007363# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007364 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007365 long nr;
7366 long off;
7367# endif
7368
Bram Moolenaar071d4272004-06-13 20:20:40 +00007369 /* expand $TMP, leave room for "/v1100000/999999999" */
7370 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7371 if (mch_isdir(itmp)) /* directory exists */
7372 {
7373# ifdef __EMX__
7374 /* If $TMP contains a forward slash (perhaps using bash or
7375 * tcsh), don't add a backslash, use a forward slash!
7376 * Adding 2 backslashes didn't work. */
7377 if (vim_strchr(itmp, '/') != NULL)
7378 STRCAT(itmp, "/");
7379 else
7380# endif
7381 add_pathsep(itmp);
7382
Bram Moolenaareaf03392009-11-17 11:08:52 +00007383# ifdef HAVE_MKDTEMP
7384 /* Leave room for filename */
7385 STRCAT(itmp, "vXXXXXX");
7386 if (mkdtemp((char *)itmp) != NULL)
7387 vim_settempdir(itmp);
7388# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007389 /* Get an arbitrary number of up to 6 digits. When it's
7390 * unlikely that it already exists it will be faster,
7391 * otherwise it doesn't matter. The use of mkdir() avoids any
7392 * security problems because of the predictable number. */
7393 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007394 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007395
7396 /* Try up to 10000 different values until we find a name that
7397 * doesn't exist. */
7398 for (off = 0; off < 10000L; ++off)
7399 {
7400 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007401# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007402 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007403# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404
Bram Moolenaareaf03392009-11-17 11:08:52 +00007405 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7406# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407 /* If mkdir() does not set errno to EEXIST, check for
7408 * existing file here. There is a race condition then,
7409 * although it's fail-safe. */
7410 if (mch_stat((char *)itmp, &st) >= 0)
7411 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007412# endif
7413# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007414 /* Make sure the umask doesn't remove the executable bit.
7415 * "repl" has been reported to use "177". */
7416 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007417# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007418 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007419# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007421# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 if (r == 0)
7423 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007424 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007425 break;
7426 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007427# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428 /* If the mkdir() didn't fail because the file/dir exists,
7429 * we probably can't create any dir here, try another
7430 * place. */
7431 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007432# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 break;
7434 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007435# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 if (vim_tempdir != NULL)
7437 break;
7438 }
7439 }
7440 }
7441
7442 if (vim_tempdir != NULL)
7443 {
7444 /* There is no need to check if the file exists, because we own the
7445 * directory and nobody else creates a file in it. */
7446 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7447 return vim_strsave(itmp);
7448 }
7449
7450 return NULL;
7451
7452#else /* TEMPDIRNAMES */
7453
7454# ifdef WIN3264
7455 char szTempFile[_MAX_PATH + 1];
7456 char buf4[4];
7457 char_u *retval;
7458 char_u *p;
7459
7460 STRCPY(itmp, "");
7461 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7462 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7463 strcpy(buf4, "VIM");
7464 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7465 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7466 return NULL;
7467 /* GetTempFileName() will create the file, we don't want that */
7468 (void)DeleteFile(itmp);
7469
7470 /* Backslashes in a temp file name cause problems when filtering with
7471 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7472 * didn't set 'shellslash'. */
7473 retval = vim_strsave(itmp);
7474 if (*p_shcf == '-' || p_ssl)
7475 for (p = retval; *p; ++p)
7476 if (*p == '\\')
7477 *p = '/';
7478 return retval;
7479
7480# else /* WIN3264 */
7481
7482# ifdef USE_TMPNAM
7483 /* tmpnam() will make its own name */
7484 if (*tmpnam((char *)itmp) == NUL)
7485 return NULL;
7486# else
7487 char_u *p;
7488
7489# ifdef VMS_TEMPNAM
7490 /* mktemp() is not working on VMS. It seems to be
7491 * a do-nothing function. Therefore we use tempnam().
7492 */
7493 sprintf((char *)itmp, "VIM%c", extra_char);
7494 p = (char_u *)tempnam("tmp:", (char *)itmp);
7495 if (p != NULL)
7496 {
7497 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7498 * and VIM will then be unable to find the file later */
7499 STRCPY(itmp, p);
7500 STRCAT(itmp, ".txt");
7501 free(p);
7502 }
7503 else
7504 return NULL;
7505# else
7506 STRCPY(itmp, TEMPNAME);
7507 if ((p = vim_strchr(itmp, '?')) != NULL)
7508 *p = extra_char;
7509 if (mktemp((char *)itmp) == NULL)
7510 return NULL;
7511# endif
7512# endif
7513
7514 return vim_strsave(itmp);
7515# endif /* WIN3264 */
7516#endif /* TEMPDIRNAMES */
7517}
7518
7519#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7520/*
7521 * Convert all backslashes in fname to forward slashes in-place.
7522 */
7523 void
7524forward_slash(fname)
7525 char_u *fname;
7526{
7527 char_u *p;
7528
7529 for (p = fname; *p != NUL; ++p)
7530# ifdef FEAT_MBYTE
7531 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007532 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007533 ++p;
7534 else
7535# endif
7536 if (*p == '\\')
7537 *p = '/';
7538}
7539#endif
7540
7541
7542/*
7543 * Code for automatic commands.
7544 *
7545 * Only included when "FEAT_AUTOCMD" has been defined.
7546 */
7547
7548#if defined(FEAT_AUTOCMD) || defined(PROTO)
7549
7550/*
7551 * The autocommands are stored in a list for each event.
7552 * Autocommands for the same pattern, that are consecutive, are joined
7553 * together, to avoid having to match the pattern too often.
7554 * The result is an array of Autopat lists, which point to AutoCmd lists:
7555 *
7556 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7557 * Autopat.cmds Autopat.cmds
7558 * | |
7559 * V V
7560 * AutoCmd.next AutoCmd.next
7561 * | |
7562 * V V
7563 * AutoCmd.next NULL
7564 * |
7565 * V
7566 * NULL
7567 *
7568 * first_autopat[1] --> Autopat.next --> NULL
7569 * Autopat.cmds
7570 * |
7571 * V
7572 * AutoCmd.next
7573 * |
7574 * V
7575 * NULL
7576 * etc.
7577 *
7578 * The order of AutoCmds is important, this is the order in which they were
7579 * defined and will have to be executed.
7580 */
7581typedef struct AutoCmd
7582{
7583 char_u *cmd; /* The command to be executed (NULL
7584 when command has been removed) */
7585 char nested; /* If autocommands nest here */
7586 char last; /* last command in list */
7587#ifdef FEAT_EVAL
7588 scid_T scriptID; /* script ID where defined */
7589#endif
7590 struct AutoCmd *next; /* Next AutoCmd in list */
7591} AutoCmd;
7592
7593typedef struct AutoPat
7594{
7595 int group; /* group ID */
7596 char_u *pat; /* pattern as typed (NULL when pattern
7597 has been removed) */
7598 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007599 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007600 char allow_dirs; /* Pattern may match whole path */
7601 char last; /* last pattern for apply_autocmds() */
7602 AutoCmd *cmds; /* list of commands to do */
7603 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007604 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007605} AutoPat;
7606
7607static struct event_name
7608{
7609 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007610 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007611} event_names[] =
7612{
7613 {"BufAdd", EVENT_BUFADD},
7614 {"BufCreate", EVENT_BUFADD},
7615 {"BufDelete", EVENT_BUFDELETE},
7616 {"BufEnter", EVENT_BUFENTER},
7617 {"BufFilePost", EVENT_BUFFILEPOST},
7618 {"BufFilePre", EVENT_BUFFILEPRE},
7619 {"BufHidden", EVENT_BUFHIDDEN},
7620 {"BufLeave", EVENT_BUFLEAVE},
7621 {"BufNew", EVENT_BUFNEW},
7622 {"BufNewFile", EVENT_BUFNEWFILE},
7623 {"BufRead", EVENT_BUFREADPOST},
7624 {"BufReadCmd", EVENT_BUFREADCMD},
7625 {"BufReadPost", EVENT_BUFREADPOST},
7626 {"BufReadPre", EVENT_BUFREADPRE},
7627 {"BufUnload", EVENT_BUFUNLOAD},
7628 {"BufWinEnter", EVENT_BUFWINENTER},
7629 {"BufWinLeave", EVENT_BUFWINLEAVE},
7630 {"BufWipeout", EVENT_BUFWIPEOUT},
7631 {"BufWrite", EVENT_BUFWRITEPRE},
7632 {"BufWritePost", EVENT_BUFWRITEPOST},
7633 {"BufWritePre", EVENT_BUFWRITEPRE},
7634 {"BufWriteCmd", EVENT_BUFWRITECMD},
7635 {"CmdwinEnter", EVENT_CMDWINENTER},
7636 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007637 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007638 {"CursorHold", EVENT_CURSORHOLD},
7639 {"CursorHoldI", EVENT_CURSORHOLDI},
7640 {"CursorMoved", EVENT_CURSORMOVED},
7641 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007642 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7643 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007644 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7645 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7646 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7647 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007648 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007649 {"FileChangedRO", EVENT_FILECHANGEDRO},
7650 {"FileReadPost", EVENT_FILEREADPOST},
7651 {"FileReadPre", EVENT_FILEREADPRE},
7652 {"FileReadCmd", EVENT_FILEREADCMD},
7653 {"FileType", EVENT_FILETYPE},
7654 {"FileWritePost", EVENT_FILEWRITEPOST},
7655 {"FileWritePre", EVENT_FILEWRITEPRE},
7656 {"FileWriteCmd", EVENT_FILEWRITECMD},
7657 {"FilterReadPost", EVENT_FILTERREADPOST},
7658 {"FilterReadPre", EVENT_FILTERREADPRE},
7659 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7660 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7661 {"FocusGained", EVENT_FOCUSGAINED},
7662 {"FocusLost", EVENT_FOCUSLOST},
7663 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7664 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007665 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007666 {"InsertChange", EVENT_INSERTCHANGE},
7667 {"InsertEnter", EVENT_INSERTENTER},
7668 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007669 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007670 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7671 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007672 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007673 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007674 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7675 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007676 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007677 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007678 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007679 {"StdinReadPost", EVENT_STDINREADPOST},
7680 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007681 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007682 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007683 {"TabEnter", EVENT_TABENTER},
7684 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007685 {"TermChanged", EVENT_TERMCHANGED},
7686 {"TermResponse", EVENT_TERMRESPONSE},
7687 {"User", EVENT_USER},
7688 {"VimEnter", EVENT_VIMENTER},
7689 {"VimLeave", EVENT_VIMLEAVE},
7690 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7691 {"WinEnter", EVENT_WINENTER},
7692 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007693 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007694 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007695};
7696
7697static AutoPat *first_autopat[NUM_EVENTS] =
7698{
7699 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7700 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7701 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7702 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007703 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7704 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007705};
7706
7707/*
7708 * struct used to keep status while executing autocommands for an event.
7709 */
7710typedef struct AutoPatCmd
7711{
7712 AutoPat *curpat; /* next AutoPat to examine */
7713 AutoCmd *nextcmd; /* next AutoCmd to execute */
7714 int group; /* group being used */
7715 char_u *fname; /* fname to match with */
7716 char_u *sfname; /* sfname to match with */
7717 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007718 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007719 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7720 buf is deleted */
7721 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007722} AutoPatCmd;
7723
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007724static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007725
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726/*
7727 * augroups stores a list of autocmd group names.
7728 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007729static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7731
7732/*
7733 * The ID of the current group. Group 0 is the default one.
7734 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007735static int current_augroup = AUGROUP_DEFAULT;
7736
7737static int au_need_clean = FALSE; /* need to delete marked patterns */
7738
Bram Moolenaar754b5602006-02-09 23:53:20 +00007739static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007740static void au_remove_pat __ARGS((AutoPat *ap));
7741static void au_remove_cmds __ARGS((AutoPat *ap));
7742static void au_cleanup __ARGS((void));
7743static int au_new_group __ARGS((char_u *name));
7744static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007745static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7746static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007747static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007748static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007749static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007750static int do_autocmd_event __ARGS((event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007752static int apply_autocmds_group __ARGS((event_T event, char_u *fname, char_u *fname_io, int force, int group, buf_T *buf, exarg_T *eap));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007753static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7754
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007755
Bram Moolenaar754b5602006-02-09 23:53:20 +00007756static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007758static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759
7760/*
7761 * Show the autocommands for one AutoPat.
7762 */
7763 static void
7764show_autocmd(ap, event)
7765 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007766 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007767{
7768 AutoCmd *ac;
7769
7770 /* Check for "got_int" (here and at various places below), which is set
7771 * when "q" has been hit for the "--more--" prompt */
7772 if (got_int)
7773 return;
7774 if (ap->pat == NULL) /* pattern has been removed */
7775 return;
7776
7777 msg_putchar('\n');
7778 if (got_int)
7779 return;
7780 if (event != last_event || ap->group != last_group)
7781 {
7782 if (ap->group != AUGROUP_DEFAULT)
7783 {
7784 if (AUGROUP_NAME(ap->group) == NULL)
7785 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7786 else
7787 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7788 msg_puts((char_u *)" ");
7789 }
7790 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7791 last_event = event;
7792 last_group = ap->group;
7793 msg_putchar('\n');
7794 if (got_int)
7795 return;
7796 }
7797 msg_col = 4;
7798 msg_outtrans(ap->pat);
7799
7800 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7801 {
7802 if (ac->cmd != NULL) /* skip removed commands */
7803 {
7804 if (msg_col >= 14)
7805 msg_putchar('\n');
7806 msg_col = 14;
7807 if (got_int)
7808 return;
7809 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007810#ifdef FEAT_EVAL
7811 if (p_verbose > 0)
7812 last_set_msg(ac->scriptID);
7813#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007814 if (got_int)
7815 return;
7816 if (ac->next != NULL)
7817 {
7818 msg_putchar('\n');
7819 if (got_int)
7820 return;
7821 }
7822 }
7823 }
7824}
7825
7826/*
7827 * Mark an autocommand pattern for deletion.
7828 */
7829 static void
7830au_remove_pat(ap)
7831 AutoPat *ap;
7832{
7833 vim_free(ap->pat);
7834 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007835 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007836 au_need_clean = TRUE;
7837}
7838
7839/*
7840 * Mark all commands for a pattern for deletion.
7841 */
7842 static void
7843au_remove_cmds(ap)
7844 AutoPat *ap;
7845{
7846 AutoCmd *ac;
7847
7848 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7849 {
7850 vim_free(ac->cmd);
7851 ac->cmd = NULL;
7852 }
7853 au_need_clean = TRUE;
7854}
7855
7856/*
7857 * Cleanup autocommands and patterns that have been deleted.
7858 * This is only done when not executing autocommands.
7859 */
7860 static void
7861au_cleanup()
7862{
7863 AutoPat *ap, **prev_ap;
7864 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007865 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007866
7867 if (autocmd_busy || !au_need_clean)
7868 return;
7869
7870 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007871 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7872 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007873 {
7874 /* loop over all autocommand patterns */
7875 prev_ap = &(first_autopat[(int)event]);
7876 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7877 {
7878 /* loop over all commands for this pattern */
7879 prev_ac = &(ap->cmds);
7880 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7881 {
7882 /* remove the command if the pattern is to be deleted or when
7883 * the command has been marked for deletion */
7884 if (ap->pat == NULL || ac->cmd == NULL)
7885 {
7886 *prev_ac = ac->next;
7887 vim_free(ac->cmd);
7888 vim_free(ac);
7889 }
7890 else
7891 prev_ac = &(ac->next);
7892 }
7893
7894 /* remove the pattern if it has been marked for deletion */
7895 if (ap->pat == NULL)
7896 {
7897 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007898 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007899 vim_free(ap);
7900 }
7901 else
7902 prev_ap = &(ap->next);
7903 }
7904 }
7905
7906 au_need_clean = FALSE;
7907}
7908
7909/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007910 * Called when buffer is freed, to remove/invalidate related buffer-local
7911 * autocmds.
7912 */
7913 void
7914aubuflocal_remove(buf)
7915 buf_T *buf;
7916{
7917 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007918 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007919 AutoPatCmd *apc;
7920
7921 /* invalidate currently executing autocommands */
7922 for (apc = active_apc_list; apc; apc = apc->next)
7923 if (buf->b_fnum == apc->arg_bufnr)
7924 apc->arg_bufnr = 0;
7925
7926 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007927 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7928 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007929 /* loop over all autocommand patterns */
7930 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7931 if (ap->buflocal_nr == buf->b_fnum)
7932 {
7933 au_remove_pat(ap);
7934 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007935 {
7936 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007937 smsg((char_u *)
7938 _("auto-removing autocommand: %s <buffer=%d>"),
7939 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007940 verbose_leave();
7941 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007942 }
7943 au_cleanup();
7944}
7945
7946/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007947 * Add an autocmd group name.
7948 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7949 */
7950 static int
7951au_new_group(name)
7952 char_u *name;
7953{
7954 int i;
7955
7956 i = au_find_group(name);
7957 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7958 {
7959 /* First try using a free entry. */
7960 for (i = 0; i < augroups.ga_len; ++i)
7961 if (AUGROUP_NAME(i) == NULL)
7962 break;
7963 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7964 return AUGROUP_ERROR;
7965
7966 AUGROUP_NAME(i) = vim_strsave(name);
7967 if (AUGROUP_NAME(i) == NULL)
7968 return AUGROUP_ERROR;
7969 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007970 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007971 }
7972
7973 return i;
7974}
7975
7976 static void
7977au_del_group(name)
7978 char_u *name;
7979{
7980 int i;
7981
7982 i = au_find_group(name);
7983 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7984 EMSG2(_("E367: No such group: \"%s\""), name);
7985 else
7986 {
7987 vim_free(AUGROUP_NAME(i));
7988 AUGROUP_NAME(i) = NULL;
7989 }
7990}
7991
7992/*
7993 * Find the ID of an autocmd group name.
7994 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7995 */
7996 static int
7997au_find_group(name)
7998 char_u *name;
7999{
8000 int i;
8001
8002 for (i = 0; i < augroups.ga_len; ++i)
8003 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8004 return i;
8005 return AUGROUP_ERROR;
8006}
8007
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008008/*
8009 * Return TRUE if augroup "name" exists.
8010 */
8011 int
8012au_has_group(name)
8013 char_u *name;
8014{
8015 return au_find_group(name) != AUGROUP_ERROR;
8016}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008017
Bram Moolenaar071d4272004-06-13 20:20:40 +00008018/*
8019 * ":augroup {name}".
8020 */
8021 void
8022do_augroup(arg, del_group)
8023 char_u *arg;
8024 int del_group;
8025{
8026 int i;
8027
8028 if (del_group)
8029 {
8030 if (*arg == NUL)
8031 EMSG(_(e_argreq));
8032 else
8033 au_del_group(arg);
8034 }
8035 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8036 current_augroup = AUGROUP_DEFAULT;
8037 else if (*arg) /* ":aug xxx": switch to group xxx */
8038 {
8039 i = au_new_group(arg);
8040 if (i != AUGROUP_ERROR)
8041 current_augroup = i;
8042 }
8043 else /* ":aug": list the group names */
8044 {
8045 msg_start();
8046 for (i = 0; i < augroups.ga_len; ++i)
8047 {
8048 if (AUGROUP_NAME(i) != NULL)
8049 {
8050 msg_puts(AUGROUP_NAME(i));
8051 msg_puts((char_u *)" ");
8052 }
8053 }
8054 msg_clr_eos();
8055 msg_end();
8056 }
8057}
8058
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008059#if defined(EXITFREE) || defined(PROTO)
8060 void
8061free_all_autocmds()
8062{
8063 for (current_augroup = -1; current_augroup < augroups.ga_len;
8064 ++current_augroup)
8065 do_autocmd((char_u *)"", TRUE);
8066 ga_clear_strings(&augroups);
8067}
8068#endif
8069
Bram Moolenaar071d4272004-06-13 20:20:40 +00008070/*
8071 * Return the event number for event name "start".
8072 * Return NUM_EVENTS if the event name was not found.
8073 * Return a pointer to the next event name in "end".
8074 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008075 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008076event_name2nr(start, end)
8077 char_u *start;
8078 char_u **end;
8079{
8080 char_u *p;
8081 int i;
8082 int len;
8083
8084 /* the event name ends with end of line, a blank or a comma */
8085 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8086 ;
8087 for (i = 0; event_names[i].name != NULL; ++i)
8088 {
8089 len = (int)STRLEN(event_names[i].name);
8090 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8091 break;
8092 }
8093 if (*p == ',')
8094 ++p;
8095 *end = p;
8096 if (event_names[i].name == NULL)
8097 return NUM_EVENTS;
8098 return event_names[i].event;
8099}
8100
8101/*
8102 * Return the name for event "event".
8103 */
8104 static char_u *
8105event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008106 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008107{
8108 int i;
8109
8110 for (i = 0; event_names[i].name != NULL; ++i)
8111 if (event_names[i].event == event)
8112 return (char_u *)event_names[i].name;
8113 return (char_u *)"Unknown";
8114}
8115
8116/*
8117 * Scan over the events. "*" stands for all events.
8118 */
8119 static char_u *
8120find_end_event(arg, have_group)
8121 char_u *arg;
8122 int have_group; /* TRUE when group name was found */
8123{
8124 char_u *pat;
8125 char_u *p;
8126
8127 if (*arg == '*')
8128 {
8129 if (arg[1] && !vim_iswhite(arg[1]))
8130 {
8131 EMSG2(_("E215: Illegal character after *: %s"), arg);
8132 return NULL;
8133 }
8134 pat = arg + 1;
8135 }
8136 else
8137 {
8138 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8139 {
8140 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8141 {
8142 if (have_group)
8143 EMSG2(_("E216: No such event: %s"), pat);
8144 else
8145 EMSG2(_("E216: No such group or event: %s"), pat);
8146 return NULL;
8147 }
8148 }
8149 }
8150 return pat;
8151}
8152
8153/*
8154 * Return TRUE if "event" is included in 'eventignore'.
8155 */
8156 static int
8157event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008158 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008159{
8160 char_u *p = p_ei;
8161
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008162 while (*p != NUL)
8163 {
8164 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8165 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008166 if (event_name2nr(p, &p) == event)
8167 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008168 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008169
8170 return FALSE;
8171}
8172
8173/*
8174 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8175 */
8176 int
8177check_ei()
8178{
8179 char_u *p = p_ei;
8180
Bram Moolenaar071d4272004-06-13 20:20:40 +00008181 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008182 {
8183 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8184 {
8185 p += 3;
8186 if (*p == ',')
8187 ++p;
8188 }
8189 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008190 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008191 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008192
8193 return OK;
8194}
8195
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008196# if defined(FEAT_SYN_HL) || defined(PROTO)
8197
8198/*
8199 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8200 * buffer loaded into the window. "what" must start with a comma.
8201 * Returns the old value of 'eventignore' in allocated memory.
8202 */
8203 char_u *
8204au_event_disable(what)
8205 char *what;
8206{
8207 char_u *new_ei;
8208 char_u *save_ei;
8209
8210 save_ei = vim_strsave(p_ei);
8211 if (save_ei != NULL)
8212 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008213 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008214 if (new_ei != NULL)
8215 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008216 if (*what == ',' && *p_ei == NUL)
8217 STRCPY(new_ei, what + 1);
8218 else
8219 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008220 set_string_option_direct((char_u *)"ei", -1, new_ei,
8221 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008222 vim_free(new_ei);
8223 }
8224 }
8225 return save_ei;
8226}
8227
8228 void
8229au_event_restore(old_ei)
8230 char_u *old_ei;
8231{
8232 if (old_ei != NULL)
8233 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008234 set_string_option_direct((char_u *)"ei", -1, old_ei,
8235 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008236 vim_free(old_ei);
8237 }
8238}
8239# endif /* FEAT_SYN_HL */
8240
Bram Moolenaar071d4272004-06-13 20:20:40 +00008241/*
8242 * do_autocmd() -- implements the :autocmd command. Can be used in the
8243 * following ways:
8244 *
8245 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8246 * will be automatically executed for <event>
8247 * when editing a file matching <pat>, in
8248 * the current group.
8249 * :autocmd <event> <pat> Show the auto-commands associated with
8250 * <event> and <pat>.
8251 * :autocmd <event> Show the auto-commands associated with
8252 * <event>.
8253 * :autocmd Show all auto-commands.
8254 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8255 * <event> and <pat>, and add the command
8256 * <cmd>, for the current group.
8257 * :autocmd! <event> <pat> Remove all auto-commands associated with
8258 * <event> and <pat> for the current group.
8259 * :autocmd! <event> Remove all auto-commands associated with
8260 * <event> for the current group.
8261 * :autocmd! Remove ALL auto-commands for the current
8262 * group.
8263 *
8264 * Multiple events and patterns may be given separated by commas. Here are
8265 * some examples:
8266 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8267 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8268 *
8269 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008270 *
8271 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008272 */
8273 void
8274do_autocmd(arg, forceit)
8275 char_u *arg;
8276 int forceit;
8277{
8278 char_u *pat;
8279 char_u *envpat = NULL;
8280 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008281 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008282 int need_free = FALSE;
8283 int nested = FALSE;
8284 int group;
8285
8286 /*
8287 * Check for a legal group name. If not, use AUGROUP_ALL.
8288 */
8289 group = au_get_grouparg(&arg);
8290 if (arg == NULL) /* out of memory */
8291 return;
8292
8293 /*
8294 * Scan over the events.
8295 * If we find an illegal name, return here, don't do anything.
8296 */
8297 pat = find_end_event(arg, group != AUGROUP_ALL);
8298 if (pat == NULL)
8299 return;
8300
8301 /*
8302 * Scan over the pattern. Put a NUL at the end.
8303 */
8304 pat = skipwhite(pat);
8305 cmd = pat;
8306 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8307 cmd++;
8308 if (*cmd)
8309 *cmd++ = NUL;
8310
8311 /* Expand environment variables in the pattern. Set 'shellslash', we want
8312 * forward slashes here. */
8313 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8314 {
8315#ifdef BACKSLASH_IN_FILENAME
8316 int p_ssl_save = p_ssl;
8317
8318 p_ssl = TRUE;
8319#endif
8320 envpat = expand_env_save(pat);
8321#ifdef BACKSLASH_IN_FILENAME
8322 p_ssl = p_ssl_save;
8323#endif
8324 if (envpat != NULL)
8325 pat = envpat;
8326 }
8327
8328 /*
8329 * Check for "nested" flag.
8330 */
8331 cmd = skipwhite(cmd);
8332 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8333 {
8334 nested = TRUE;
8335 cmd = skipwhite(cmd + 6);
8336 }
8337
8338 /*
8339 * Find the start of the commands.
8340 * Expand <sfile> in it.
8341 */
8342 if (*cmd != NUL)
8343 {
8344 cmd = expand_sfile(cmd);
8345 if (cmd == NULL) /* some error */
8346 return;
8347 need_free = TRUE;
8348 }
8349
8350 /*
8351 * Print header when showing autocommands.
8352 */
8353 if (!forceit && *cmd == NUL)
8354 {
8355 /* Highlight title */
8356 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8357 }
8358
8359 /*
8360 * Loop over the events.
8361 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008362 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008363 last_group = AUGROUP_ERROR; /* for listing the group name */
8364 if (*arg == '*' || *arg == NUL)
8365 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008366 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8367 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008368 if (do_autocmd_event(event, pat,
8369 nested, cmd, forceit, group) == FAIL)
8370 break;
8371 }
8372 else
8373 {
8374 while (*arg && !vim_iswhite(*arg))
8375 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8376 nested, cmd, forceit, group) == FAIL)
8377 break;
8378 }
8379
8380 if (need_free)
8381 vim_free(cmd);
8382 vim_free(envpat);
8383}
8384
8385/*
8386 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8387 * The "argp" argument is advanced to the following argument.
8388 *
8389 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8390 */
8391 static int
8392au_get_grouparg(argp)
8393 char_u **argp;
8394{
8395 char_u *group_name;
8396 char_u *p;
8397 char_u *arg = *argp;
8398 int group = AUGROUP_ALL;
8399
8400 p = skiptowhite(arg);
8401 if (p > arg)
8402 {
8403 group_name = vim_strnsave(arg, (int)(p - arg));
8404 if (group_name == NULL) /* out of memory */
8405 return AUGROUP_ERROR;
8406 group = au_find_group(group_name);
8407 if (group == AUGROUP_ERROR)
8408 group = AUGROUP_ALL; /* no match, use all groups */
8409 else
8410 *argp = skipwhite(p); /* match, skip over group name */
8411 vim_free(group_name);
8412 }
8413 return group;
8414}
8415
8416/*
8417 * do_autocmd() for one event.
8418 * If *pat == NUL do for all patterns.
8419 * If *cmd == NUL show entries.
8420 * If forceit == TRUE delete entries.
8421 * If group is not AUGROUP_ALL, only use this group.
8422 */
8423 static int
8424do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008425 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008426 char_u *pat;
8427 int nested;
8428 char_u *cmd;
8429 int forceit;
8430 int group;
8431{
8432 AutoPat *ap;
8433 AutoPat **prev_ap;
8434 AutoCmd *ac;
8435 AutoCmd **prev_ac;
8436 int brace_level;
8437 char_u *endpat;
8438 int findgroup;
8439 int allgroups;
8440 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008441 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008442 int buflocal_nr;
8443 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008444
8445 if (group == AUGROUP_ALL)
8446 findgroup = current_augroup;
8447 else
8448 findgroup = group;
8449 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8450
8451 /*
8452 * Show or delete all patterns for an event.
8453 */
8454 if (*pat == NUL)
8455 {
8456 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8457 {
8458 if (forceit) /* delete the AutoPat, if it's in the current group */
8459 {
8460 if (ap->group == findgroup)
8461 au_remove_pat(ap);
8462 }
8463 else if (group == AUGROUP_ALL || ap->group == group)
8464 show_autocmd(ap, event);
8465 }
8466 }
8467
8468 /*
8469 * Loop through all the specified patterns.
8470 */
8471 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8472 {
8473 /*
8474 * Find end of the pattern.
8475 * Watch out for a comma in braces, like "*.\{obj,o\}".
8476 */
8477 brace_level = 0;
8478 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8479 || endpat[-1] == '\\'); ++endpat)
8480 {
8481 if (*endpat == '{')
8482 brace_level++;
8483 else if (*endpat == '}')
8484 brace_level--;
8485 }
8486 if (pat == endpat) /* ignore single comma */
8487 continue;
8488 patlen = (int)(endpat - pat);
8489
8490 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008491 * detect special <buflocal[=X]> buffer-local patterns
8492 */
8493 is_buflocal = FALSE;
8494 buflocal_nr = 0;
8495
8496 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8497 && pat[patlen - 1] == '>')
8498 {
8499 /* Error will be printed only for addition. printing and removing
8500 * will proceed silently. */
8501 is_buflocal = TRUE;
8502 if (patlen == 8)
8503 buflocal_nr = curbuf->b_fnum;
8504 else if (patlen > 9 && pat[7] == '=')
8505 {
8506 /* <buffer=abuf> */
8507 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8508 buflocal_nr = autocmd_bufnr;
8509 /* <buffer=123> */
8510 else if (skipdigits(pat + 8) == pat + patlen - 1)
8511 buflocal_nr = atoi((char *)pat + 8);
8512 }
8513 }
8514
8515 if (is_buflocal)
8516 {
8517 /* normalize pat into standard "<buffer>#N" form */
8518 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8519 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008520 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008521 }
8522
8523 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008524 * Find AutoPat entries with this pattern.
8525 */
8526 prev_ap = &first_autopat[(int)event];
8527 while ((ap = *prev_ap) != NULL)
8528 {
8529 if (ap->pat != NULL)
8530 {
8531 /* Accept a pattern when:
8532 * - a group was specified and it's that group, or a group was
8533 * not specified and it's the current group, or a group was
8534 * not specified and we are listing
8535 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008536 * - the pattern matches.
8537 * For <buffer[=X]>, this condition works because we normalize
8538 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008539 */
8540 if ((allgroups || ap->group == findgroup)
8541 && ap->patlen == patlen
8542 && STRNCMP(pat, ap->pat, patlen) == 0)
8543 {
8544 /*
8545 * Remove existing autocommands.
8546 * If adding any new autocmd's for this AutoPat, don't
8547 * delete the pattern from the autopat list, append to
8548 * this list.
8549 */
8550 if (forceit)
8551 {
8552 if (*cmd != NUL && ap->next == NULL)
8553 {
8554 au_remove_cmds(ap);
8555 break;
8556 }
8557 au_remove_pat(ap);
8558 }
8559
8560 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008561 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008562 */
8563 else if (*cmd == NUL)
8564 show_autocmd(ap, event);
8565
8566 /*
8567 * Add autocmd to this autopat, if it's the last one.
8568 */
8569 else if (ap->next == NULL)
8570 break;
8571 }
8572 }
8573 prev_ap = &ap->next;
8574 }
8575
8576 /*
8577 * Add a new command.
8578 */
8579 if (*cmd != NUL)
8580 {
8581 /*
8582 * If the pattern we want to add a command to does appear at the
8583 * end of the list (or not is not in the list at all), add the
8584 * pattern at the end of the list.
8585 */
8586 if (ap == NULL)
8587 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008588 /* refuse to add buffer-local ap if buffer number is invalid */
8589 if (is_buflocal && (buflocal_nr == 0
8590 || buflist_findnr(buflocal_nr) == NULL))
8591 {
8592 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8593 buflocal_nr);
8594 return FAIL;
8595 }
8596
Bram Moolenaar071d4272004-06-13 20:20:40 +00008597 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8598 if (ap == NULL)
8599 return FAIL;
8600 ap->pat = vim_strnsave(pat, patlen);
8601 ap->patlen = patlen;
8602 if (ap->pat == NULL)
8603 {
8604 vim_free(ap);
8605 return FAIL;
8606 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008607
8608 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008609 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008610 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008611 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008612 }
8613 else
8614 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008615 char_u *reg_pat;
8616
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008617 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008618 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008619 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008620 if (reg_pat != NULL)
8621 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008622 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008623 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008624 {
8625 vim_free(ap->pat);
8626 vim_free(ap);
8627 return FAIL;
8628 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008629 }
8630 ap->cmds = NULL;
8631 *prev_ap = ap;
8632 ap->next = NULL;
8633 if (group == AUGROUP_ALL)
8634 ap->group = current_augroup;
8635 else
8636 ap->group = group;
8637 }
8638
8639 /*
8640 * Add the autocmd at the end of the AutoCmd list.
8641 */
8642 prev_ac = &(ap->cmds);
8643 while ((ac = *prev_ac) != NULL)
8644 prev_ac = &ac->next;
8645 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8646 if (ac == NULL)
8647 return FAIL;
8648 ac->cmd = vim_strsave(cmd);
8649#ifdef FEAT_EVAL
8650 ac->scriptID = current_SID;
8651#endif
8652 if (ac->cmd == NULL)
8653 {
8654 vim_free(ac);
8655 return FAIL;
8656 }
8657 ac->next = NULL;
8658 *prev_ac = ac;
8659 ac->nested = nested;
8660 }
8661 }
8662
8663 au_cleanup(); /* may really delete removed patterns/commands now */
8664 return OK;
8665}
8666
8667/*
8668 * Implementation of ":doautocmd [group] event [fname]".
8669 * Return OK for success, FAIL for failure;
8670 */
8671 int
8672do_doautocmd(arg, do_msg)
8673 char_u *arg;
8674 int do_msg; /* give message for no matching autocmds? */
8675{
8676 char_u *fname;
8677 int nothing_done = TRUE;
8678 int group;
8679
8680 /*
8681 * Check for a legal group name. If not, use AUGROUP_ALL.
8682 */
8683 group = au_get_grouparg(&arg);
8684 if (arg == NULL) /* out of memory */
8685 return FAIL;
8686
8687 if (*arg == '*')
8688 {
8689 EMSG(_("E217: Can't execute autocommands for ALL events"));
8690 return FAIL;
8691 }
8692
8693 /*
8694 * Scan over the events.
8695 * If we find an illegal name, return here, don't do anything.
8696 */
8697 fname = find_end_event(arg, group != AUGROUP_ALL);
8698 if (fname == NULL)
8699 return FAIL;
8700
8701 fname = skipwhite(fname);
8702
8703 /*
8704 * Loop over the events.
8705 */
8706 while (*arg && !vim_iswhite(*arg))
8707 if (apply_autocmds_group(event_name2nr(arg, &arg),
8708 fname, NULL, TRUE, group, curbuf, NULL))
8709 nothing_done = FALSE;
8710
8711 if (nothing_done && do_msg)
8712 MSG(_("No matching autocommands"));
8713
8714#ifdef FEAT_EVAL
8715 return aborting() ? FAIL : OK;
8716#else
8717 return OK;
8718#endif
8719}
8720
8721/*
8722 * ":doautoall": execute autocommands for each loaded buffer.
8723 */
8724 void
8725ex_doautoall(eap)
8726 exarg_T *eap;
8727{
8728 int retval;
8729 aco_save_T aco;
8730 buf_T *buf;
8731
8732 /*
8733 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8734 * equal to curbuf, but for some buffers there may not be a window.
8735 * So we change the buffer for the current window for a moment. This
8736 * gives problems when the autocommands make changes to the list of
8737 * buffers or windows...
8738 */
8739 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8740 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008741 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008742 {
8743 /* find a window for this buffer and save some values */
8744 aucmd_prepbuf(&aco, buf);
8745
8746 /* execute the autocommands for this buffer */
8747 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008748
8749 /* Execute the modeline settings, but don't set window-local
8750 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008751 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008752
8753 /* restore the current window */
8754 aucmd_restbuf(&aco);
8755
8756 /* stop if there is some error or buffer was deleted */
8757 if (retval == FAIL || !buf_valid(buf))
8758 break;
8759 }
8760 }
8761
8762 check_cursor(); /* just in case lines got deleted */
8763}
8764
8765/*
8766 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008767 * Search for a visible window containing the current buffer. If there isn't
8768 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008769 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008770 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008771 */
8772 void
8773aucmd_prepbuf(aco, buf)
8774 aco_save_T *aco; /* structure to save values in */
8775 buf_T *buf; /* new curbuf */
8776{
8777 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008778#ifdef FEAT_WINDOWS
8779 int save_ea;
8780#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008781
8782 /* Find a window that is for the new buffer */
8783 if (buf == curbuf) /* be quick when buf is curbuf */
8784 win = curwin;
8785 else
8786#ifdef FEAT_WINDOWS
8787 for (win = firstwin; win != NULL; win = win->w_next)
8788 if (win->w_buffer == buf)
8789 break;
8790#else
8791 win = NULL;
8792#endif
8793
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008794 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8795 * back to using the current window. */
8796 if (win == NULL && aucmd_win == NULL)
8797 {
8798 win_alloc_aucmd_win();
8799 if (aucmd_win == NULL)
8800 win = curwin;
8801 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008802 if (win == NULL && aucmd_win_used)
8803 /* Strange recursive autocommand, fall back to using the current
8804 * window. Expect a few side effects... */
8805 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008806
8807 aco->save_curwin = curwin;
8808 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008809 if (win != NULL)
8810 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008811 /* There is a window for "buf" in the current tab page, make it the
8812 * curwin. This is preferred, it has the least side effects (esp. if
8813 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008814 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008815 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008816 }
8817 else
8818 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008819 /* There is no window for "buf", use "aucmd_win". To minimize the side
8820 * effects, insert it in a the current tab page.
8821 * Anything related to a window (e.g., setting folds) may have
8822 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008823 aco->use_aucmd_win = TRUE;
8824 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008825 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008826 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008827 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008828 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008829 vim_free(aucmd_win->w_localdir);
8830 aucmd_win->w_localdir = NULL;
8831
8832 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8833 * win_enter_ext(). */
8834 aucmd_win->w_localdir = NULL;
8835 aco->globaldir = globaldir;
8836 globaldir = NULL;
8837
Bram Moolenaar071d4272004-06-13 20:20:40 +00008838
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008839#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008840 /* Split the current window, put the aucmd_win in the upper half.
8841 * We don't want the BufEnter or WinEnter autocommands. */
8842 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008843 make_snapshot(SNAP_AUCMD_IDX);
8844 save_ea = p_ea;
8845 p_ea = FALSE;
8846 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8847 (void)win_comp_pos(); /* recompute window positions */
8848 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008849 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008850#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008851 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008852 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008853 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008854 aco->new_curwin = curwin;
8855 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008856}
8857
8858/*
8859 * Cleanup after executing autocommands for a (hidden) buffer.
8860 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008861 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008862 */
8863 void
8864aucmd_restbuf(aco)
8865 aco_save_T *aco; /* structure holding saved values */
8866{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008867#ifdef FEAT_WINDOWS
8868 int dummy;
8869#endif
8870
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008871 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008872 {
8873 --curbuf->b_nwindows;
8874#ifdef FEAT_WINDOWS
8875 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008876 * page. Do not trigger autocommands here. */
8877 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008878 if (curwin != aucmd_win)
8879 {
8880 tabpage_T *tp;
8881 win_T *wp;
8882
8883 FOR_ALL_TAB_WINDOWS(tp, wp)
8884 {
8885 if (wp == aucmd_win)
8886 {
8887 if (tp != curtab)
8888 goto_tabpage_tp(tp);
8889 win_goto(aucmd_win);
8890 break;
8891 }
8892 }
8893 }
8894
8895 /* Remove the window and frame from the tree of frames. */
8896 (void)winframe_remove(curwin, &dummy, NULL);
8897 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008898 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008899 last_status(FALSE); /* may need to remove last status line */
8900 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8901 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008902 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008903
8904 if (win_valid(aco->save_curwin))
8905 curwin = aco->save_curwin;
8906 else
8907 /* Hmm, original window disappeared. Just use the first one. */
8908 curwin = firstwin;
8909# ifdef FEAT_EVAL
8910 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
Bram Moolenaar50daf402009-11-17 13:57:22 +00008911 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008912# endif
8913#else
8914 curwin = aco->save_curwin;
8915#endif
8916 curbuf = curwin->w_buffer;
8917
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008918 vim_free(globaldir);
8919 globaldir = aco->globaldir;
8920
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008921 /* the buffer contents may have changed */
8922 check_cursor();
8923 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8924 {
8925 curwin->w_topline = curbuf->b_ml.ml_line_count;
8926#ifdef FEAT_DIFF
8927 curwin->w_topfill = 0;
8928#endif
8929 }
8930#if defined(FEAT_GUI)
8931 /* Hide the scrollbars from the aucmd_win and update. */
8932 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8933 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8934 gui_may_update_scrollbars();
8935#endif
8936 }
8937 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008938 {
8939 /* restore curwin */
8940#ifdef FEAT_WINDOWS
8941 if (win_valid(aco->save_curwin))
8942#endif
8943 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008944 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008945 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008946 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008947 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008948 && curbuf != aco->new_curbuf
8949 && buf_valid(aco->new_curbuf)
8950 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008951 {
8952 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008953 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008954 curwin->w_buffer = curbuf;
8955 ++curbuf->b_nwindows;
8956 }
8957
8958 curwin = aco->save_curwin;
8959 curbuf = curwin->w_buffer;
8960 }
8961 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008962}
8963
8964static int autocmd_nested = FALSE;
8965
8966/*
8967 * Execute autocommands for "event" and file name "fname".
8968 * Return TRUE if some commands were executed.
8969 */
8970 int
8971apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008972 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008973 char_u *fname; /* NULL or empty means use actual file name */
8974 char_u *fname_io; /* fname to use for <afile> on cmdline */
8975 int force; /* when TRUE, ignore autocmd_busy */
8976 buf_T *buf; /* buffer for <abuf> */
8977{
8978 return apply_autocmds_group(event, fname, fname_io, force,
8979 AUGROUP_ALL, buf, NULL);
8980}
8981
8982/*
8983 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8984 * setting v:filearg.
8985 */
8986 static int
8987apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008988 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008989 char_u *fname;
8990 char_u *fname_io;
8991 int force;
8992 buf_T *buf;
8993 exarg_T *eap;
8994{
8995 return apply_autocmds_group(event, fname, fname_io, force,
8996 AUGROUP_ALL, buf, eap);
8997}
8998
8999/*
9000 * Like apply_autocmds(), but handles the caller's retval. If the script
9001 * processing is being aborted or if retval is FAIL when inside a try
9002 * conditional, no autocommands are executed. If otherwise the autocommands
9003 * cause the script to be aborted, retval is set to FAIL.
9004 */
9005 int
9006apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009007 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009008 char_u *fname; /* NULL or empty means use actual file name */
9009 char_u *fname_io; /* fname to use for <afile> on cmdline */
9010 int force; /* when TRUE, ignore autocmd_busy */
9011 buf_T *buf; /* buffer for <abuf> */
9012 int *retval; /* pointer to caller's retval */
9013{
9014 int did_cmd;
9015
Bram Moolenaar1e015462005-09-25 22:16:38 +00009016#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009017 if (should_abort(*retval))
9018 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009019#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009020
9021 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9022 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009023 if (did_cmd
9024#ifdef FEAT_EVAL
9025 && aborting()
9026#endif
9027 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009028 *retval = FAIL;
9029 return did_cmd;
9030}
9031
Bram Moolenaard35f9712005-12-18 22:02:33 +00009032/*
9033 * Return TRUE when there is a CursorHold autocommand defined.
9034 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009035 int
9036has_cursorhold()
9037{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009038 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9039 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009040}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009041
9042/*
9043 * Return TRUE if the CursorHold event can be triggered.
9044 */
9045 int
9046trigger_cursorhold()
9047{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009048 int state;
9049
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009050 if (!did_cursorhold && has_cursorhold() && !Recording
9051#ifdef FEAT_INS_EXPAND
9052 && !ins_compl_active()
9053#endif
9054 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009055 {
9056 state = get_real_state();
9057 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9058 return TRUE;
9059 }
9060 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009061}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009062
9063/*
9064 * Return TRUE when there is a CursorMoved autocommand defined.
9065 */
9066 int
9067has_cursormoved()
9068{
9069 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9070}
9071
9072/*
9073 * Return TRUE when there is a CursorMovedI autocommand defined.
9074 */
9075 int
9076has_cursormovedI()
9077{
9078 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9079}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009080
9081 static int
9082apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009083 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009084 char_u *fname; /* NULL or empty means use actual file name */
9085 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9086 use fname */
9087 int force; /* when TRUE, ignore autocmd_busy */
9088 int group; /* group ID, or AUGROUP_ALL */
9089 buf_T *buf; /* buffer for <abuf> */
9090 exarg_T *eap; /* command arguments */
9091{
9092 char_u *sfname = NULL; /* short file name */
9093 char_u *tail;
9094 int save_changed;
9095 buf_T *old_curbuf;
9096 int retval = FALSE;
9097 char_u *save_sourcing_name;
9098 linenr_T save_sourcing_lnum;
9099 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009100 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009101 int save_autocmd_bufnr;
9102 char_u *save_autocmd_match;
9103 int save_autocmd_busy;
9104 int save_autocmd_nested;
9105 static int nesting = 0;
9106 AutoPatCmd patcmd;
9107 AutoPat *ap;
9108#ifdef FEAT_EVAL
9109 scid_T save_current_SID;
9110 void *save_funccalp;
9111 char_u *save_cmdarg;
9112 long save_cmdbang;
9113#endif
9114 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009115#ifdef FEAT_PROFILE
9116 proftime_T wait_time;
9117#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009118
9119 /*
9120 * Quickly return if there are no autocommands for this event or
9121 * autocommands are blocked.
9122 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009123 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009124 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009125
9126 /*
9127 * When autocommands are busy, new autocommands are only executed when
9128 * explicitly enabled with the "nested" flag.
9129 */
9130 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009131 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009132
9133#ifdef FEAT_EVAL
9134 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009135 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009136 * occurred or an exception was thrown but not caught.
9137 */
9138 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009139 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009140#endif
9141
9142 /*
9143 * FileChangedShell never nests, because it can create an endless loop.
9144 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009145 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9146 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009147 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009148
9149 /*
9150 * Ignore events in 'eventignore'.
9151 */
9152 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009153 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009154
9155 /*
9156 * Allow nesting of autocommands, but restrict the depth, because it's
9157 * possible to create an endless loop.
9158 */
9159 if (nesting == 10)
9160 {
9161 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009162 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009163 }
9164
9165 /*
9166 * Check if these autocommands are disabled. Used when doing ":all" or
9167 * ":ball".
9168 */
9169 if ( (autocmd_no_enter
9170 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9171 || (autocmd_no_leave
9172 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009173 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009174
9175 /*
9176 * Save the autocmd_* variables and info about the current buffer.
9177 */
9178 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009179 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009180 save_autocmd_bufnr = autocmd_bufnr;
9181 save_autocmd_match = autocmd_match;
9182 save_autocmd_busy = autocmd_busy;
9183 save_autocmd_nested = autocmd_nested;
9184 save_changed = curbuf->b_changed;
9185 old_curbuf = curbuf;
9186
9187 /*
9188 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009189 * Make a copy to avoid that changing a buffer name or directory makes it
9190 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009191 */
9192 if (fname_io == NULL)
9193 {
9194 if (fname != NULL && *fname != NUL)
9195 autocmd_fname = fname;
9196 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009197 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009198 else
9199 autocmd_fname = NULL;
9200 }
9201 else
9202 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009203 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009204 autocmd_fname = vim_strsave(autocmd_fname);
9205 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009206
9207 /*
9208 * Set the buffer number to be used for <abuf>.
9209 */
9210 if (buf == NULL)
9211 autocmd_bufnr = 0;
9212 else
9213 autocmd_bufnr = buf->b_fnum;
9214
9215 /*
9216 * When the file name is NULL or empty, use the file name of buffer "buf".
9217 * Always use the full path of the file name to match with, in case
9218 * "allow_dirs" is set.
9219 */
9220 if (fname == NULL || *fname == NUL)
9221 {
9222 if (buf == NULL)
9223 fname = NULL;
9224 else
9225 {
9226#ifdef FEAT_SYN_HL
9227 if (event == EVENT_SYNTAX)
9228 fname = buf->b_p_syn;
9229 else
9230#endif
9231 if (event == EVENT_FILETYPE)
9232 fname = buf->b_p_ft;
9233 else
9234 {
9235 if (buf->b_sfname != NULL)
9236 sfname = vim_strsave(buf->b_sfname);
9237 fname = buf->b_ffname;
9238 }
9239 }
9240 if (fname == NULL)
9241 fname = (char_u *)"";
9242 fname = vim_strsave(fname); /* make a copy, so we can change it */
9243 }
9244 else
9245 {
9246 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009247 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9248 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009249 if (event == EVENT_FILETYPE
9250 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009251 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009252 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009253 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009254 || event == EVENT_QUICKFIXCMDPRE
9255 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009256 fname = vim_strsave(fname);
9257 else
9258 fname = FullName_save(fname, FALSE);
9259 }
9260 if (fname == NULL) /* out of memory */
9261 {
9262 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009263 retval = FALSE;
9264 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009265 }
9266
9267#ifdef BACKSLASH_IN_FILENAME
9268 /*
9269 * Replace all backslashes with forward slashes. This makes the
9270 * autocommand patterns portable between Unix and MS-DOS.
9271 */
9272 if (sfname != NULL)
9273 forward_slash(sfname);
9274 forward_slash(fname);
9275#endif
9276
9277#ifdef VMS
9278 /* remove version for correct match */
9279 if (sfname != NULL)
9280 vms_remove_version(sfname);
9281 vms_remove_version(fname);
9282#endif
9283
9284 /*
9285 * Set the name to be used for <amatch>.
9286 */
9287 autocmd_match = fname;
9288
9289
9290 /* Don't redraw while doing auto commands. */
9291 ++RedrawingDisabled;
9292 save_sourcing_name = sourcing_name;
9293 sourcing_name = NULL; /* don't free this one */
9294 save_sourcing_lnum = sourcing_lnum;
9295 sourcing_lnum = 0; /* no line number here */
9296
9297#ifdef FEAT_EVAL
9298 save_current_SID = current_SID;
9299
Bram Moolenaar05159a02005-02-26 23:04:13 +00009300# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009301 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009302 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9303# endif
9304
Bram Moolenaar071d4272004-06-13 20:20:40 +00009305 /* Don't use local function variables, if called from a function */
9306 save_funccalp = save_funccal();
9307#endif
9308
9309 /*
9310 * When starting to execute autocommands, save the search patterns.
9311 */
9312 if (!autocmd_busy)
9313 {
9314 save_search_patterns();
9315 saveRedobuff();
9316 did_filetype = keep_filetype;
9317 }
9318
9319 /*
9320 * Note that we are applying autocmds. Some commands need to know.
9321 */
9322 autocmd_busy = TRUE;
9323 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9324 ++nesting; /* see matching decrement below */
9325
9326 /* Remember that FileType was triggered. Used for did_filetype(). */
9327 if (event == EVENT_FILETYPE)
9328 did_filetype = TRUE;
9329
9330 tail = gettail(fname);
9331
9332 /* Find first autocommand that matches */
9333 patcmd.curpat = first_autopat[(int)event];
9334 patcmd.nextcmd = NULL;
9335 patcmd.group = group;
9336 patcmd.fname = fname;
9337 patcmd.sfname = sfname;
9338 patcmd.tail = tail;
9339 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009340 patcmd.arg_bufnr = autocmd_bufnr;
9341 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009342 auto_next_pat(&patcmd, FALSE);
9343
9344 /* found one, start executing the autocommands */
9345 if (patcmd.curpat != NULL)
9346 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009347 /* add to active_apc_list */
9348 patcmd.next = active_apc_list;
9349 active_apc_list = &patcmd;
9350
Bram Moolenaar071d4272004-06-13 20:20:40 +00009351#ifdef FEAT_EVAL
9352 /* set v:cmdarg (only when there is a matching pattern) */
9353 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9354 if (eap != NULL)
9355 {
9356 save_cmdarg = set_cmdarg(eap, NULL);
9357 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9358 }
9359 else
9360 save_cmdarg = NULL; /* avoid gcc warning */
9361#endif
9362 retval = TRUE;
9363 /* mark the last pattern, to avoid an endless loop when more patterns
9364 * are added when executing autocommands */
9365 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9366 ap->last = FALSE;
9367 ap->last = TRUE;
9368 check_lnums(TRUE); /* make sure cursor and topline are valid */
9369 do_cmdline(NULL, getnextac, (void *)&patcmd,
9370 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9371#ifdef FEAT_EVAL
9372 if (eap != NULL)
9373 {
9374 (void)set_cmdarg(NULL, save_cmdarg);
9375 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9376 }
9377#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009378 /* delete from active_apc_list */
9379 if (active_apc_list == &patcmd) /* just in case */
9380 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009381 }
9382
9383 --RedrawingDisabled;
9384 autocmd_busy = save_autocmd_busy;
9385 filechangeshell_busy = FALSE;
9386 autocmd_nested = save_autocmd_nested;
9387 vim_free(sourcing_name);
9388 sourcing_name = save_sourcing_name;
9389 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009390 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009391 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009392 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009393 autocmd_bufnr = save_autocmd_bufnr;
9394 autocmd_match = save_autocmd_match;
9395#ifdef FEAT_EVAL
9396 current_SID = save_current_SID;
9397 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009398# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009399 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009400 prof_child_exit(&wait_time);
9401# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009402#endif
9403 vim_free(fname);
9404 vim_free(sfname);
9405 --nesting; /* see matching increment above */
9406
9407 /*
9408 * When stopping to execute autocommands, restore the search patterns and
9409 * the redo buffer.
9410 */
9411 if (!autocmd_busy)
9412 {
9413 restore_search_patterns();
9414 restoreRedobuff();
9415 did_filetype = FALSE;
9416 }
9417
9418 /*
9419 * Some events don't set or reset the Changed flag.
9420 * Check if still in the same buffer!
9421 */
9422 if (curbuf == old_curbuf
9423 && (event == EVENT_BUFREADPOST
9424 || event == EVENT_BUFWRITEPOST
9425 || event == EVENT_FILEAPPENDPOST
9426 || event == EVENT_VIMLEAVE
9427 || event == EVENT_VIMLEAVEPRE))
9428 {
9429#ifdef FEAT_TITLE
9430 if (curbuf->b_changed != save_changed)
9431 need_maketitle = TRUE;
9432#endif
9433 curbuf->b_changed = save_changed;
9434 }
9435
9436 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009437
9438BYPASS_AU:
9439 /* When wiping out a buffer make sure all its buffer-local autocommands
9440 * are deleted. */
9441 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9442 aubuflocal_remove(buf);
9443
Bram Moolenaar071d4272004-06-13 20:20:40 +00009444 return retval;
9445}
9446
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009447# ifdef FEAT_EVAL
9448static char_u *old_termresponse = NULL;
9449# endif
9450
9451/*
9452 * Block triggering autocommands until unblock_autocmd() is called.
9453 * Can be used recursively, so long as it's symmetric.
9454 */
9455 void
9456block_autocmds()
9457{
9458# ifdef FEAT_EVAL
9459 /* Remember the value of v:termresponse. */
9460 if (autocmd_blocked == 0)
9461 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9462# endif
9463 ++autocmd_blocked;
9464}
9465
9466 void
9467unblock_autocmds()
9468{
9469 --autocmd_blocked;
9470
9471# ifdef FEAT_EVAL
9472 /* When v:termresponse was set while autocommands were blocked, trigger
9473 * the autocommands now. Esp. useful when executing a shell command
9474 * during startup (vimdiff). */
9475 if (autocmd_blocked == 0
9476 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9477 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9478# endif
9479}
9480
Bram Moolenaar071d4272004-06-13 20:20:40 +00009481/*
9482 * Find next autocommand pattern that matches.
9483 */
9484 static void
9485auto_next_pat(apc, stop_at_last)
9486 AutoPatCmd *apc;
9487 int stop_at_last; /* stop when 'last' flag is set */
9488{
9489 AutoPat *ap;
9490 AutoCmd *cp;
9491 char_u *name;
9492 char *s;
9493
9494 vim_free(sourcing_name);
9495 sourcing_name = NULL;
9496
9497 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9498 {
9499 apc->curpat = NULL;
9500
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009501 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009502 * the group matches. For buffer-local autocommands only check the
9503 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009504 if (ap->pat != NULL && ap->cmds != NULL
9505 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9506 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009507 /* execution-condition */
9508 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009509 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9510 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009511 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009512 {
9513 name = event_nr2name(apc->event);
9514 s = _("%s Auto commands for \"%s\"");
9515 sourcing_name = alloc((unsigned)(STRLEN(s)
9516 + STRLEN(name) + ap->patlen + 1));
9517 if (sourcing_name != NULL)
9518 {
9519 sprintf((char *)sourcing_name, s,
9520 (char *)name, (char *)ap->pat);
9521 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009522 {
9523 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009524 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009525 verbose_leave();
9526 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009527 }
9528
9529 apc->curpat = ap;
9530 apc->nextcmd = ap->cmds;
9531 /* mark last command */
9532 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9533 cp->last = FALSE;
9534 cp->last = TRUE;
9535 }
9536 line_breakcheck();
9537 if (apc->curpat != NULL) /* found a match */
9538 break;
9539 }
9540 if (stop_at_last && ap->last)
9541 break;
9542 }
9543}
9544
9545/*
9546 * Get next autocommand command.
9547 * Called by do_cmdline() to get the next line for ":if".
9548 * Returns allocated string, or NULL for end of autocommands.
9549 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009550 static char_u *
9551getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009552 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009553 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009554 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009555{
9556 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9557 char_u *retval;
9558 AutoCmd *ac;
9559
9560 /* Can be called again after returning the last line. */
9561 if (acp->curpat == NULL)
9562 return NULL;
9563
9564 /* repeat until we find an autocommand to execute */
9565 for (;;)
9566 {
9567 /* skip removed commands */
9568 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9569 if (acp->nextcmd->last)
9570 acp->nextcmd = NULL;
9571 else
9572 acp->nextcmd = acp->nextcmd->next;
9573
9574 if (acp->nextcmd != NULL)
9575 break;
9576
9577 /* at end of commands, find next pattern that matches */
9578 if (acp->curpat->last)
9579 acp->curpat = NULL;
9580 else
9581 acp->curpat = acp->curpat->next;
9582 if (acp->curpat != NULL)
9583 auto_next_pat(acp, TRUE);
9584 if (acp->curpat == NULL)
9585 return NULL;
9586 }
9587
9588 ac = acp->nextcmd;
9589
9590 if (p_verbose >= 9)
9591 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009592 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009593 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009594 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009595 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009596 }
9597 retval = vim_strsave(ac->cmd);
9598 autocmd_nested = ac->nested;
9599#ifdef FEAT_EVAL
9600 current_SID = ac->scriptID;
9601#endif
9602 if (ac->last)
9603 acp->nextcmd = NULL;
9604 else
9605 acp->nextcmd = ac->next;
9606 return retval;
9607}
9608
9609/*
9610 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009611 * To account for buffer-local autocommands, function needs to know
9612 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009613 */
9614 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009615has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009616 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009617 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009618 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009619{
9620 AutoPat *ap;
9621 char_u *fname;
9622 char_u *tail = gettail(sfname);
9623 int retval = FALSE;
9624
9625 fname = FullName_save(sfname, FALSE);
9626 if (fname == NULL)
9627 return FALSE;
9628
9629#ifdef BACKSLASH_IN_FILENAME
9630 /*
9631 * Replace all backslashes with forward slashes. This makes the
9632 * autocommand patterns portable between Unix and MS-DOS.
9633 */
9634 sfname = vim_strsave(sfname);
9635 if (sfname != NULL)
9636 forward_slash(sfname);
9637 forward_slash(fname);
9638#endif
9639
9640 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9641 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009642 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009643 ? match_file_pat(NULL, ap->reg_prog,
9644 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009645 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009646 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009647 {
9648 retval = TRUE;
9649 break;
9650 }
9651
9652 vim_free(fname);
9653#ifdef BACKSLASH_IN_FILENAME
9654 vim_free(sfname);
9655#endif
9656
9657 return retval;
9658}
9659
9660#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9661/*
9662 * Function given to ExpandGeneric() to obtain the list of autocommand group
9663 * names.
9664 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009665 char_u *
9666get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009667 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009668 int idx;
9669{
9670 if (idx == augroups.ga_len) /* add "END" add the end */
9671 return (char_u *)"END";
9672 if (idx >= augroups.ga_len) /* end of list */
9673 return NULL;
9674 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9675 return (char_u *)"";
9676 return AUGROUP_NAME(idx); /* return a name */
9677}
9678
9679static int include_groups = FALSE;
9680
9681 char_u *
9682set_context_in_autocmd(xp, arg, doautocmd)
9683 expand_T *xp;
9684 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009685 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009686{
9687 char_u *p;
9688 int group;
9689
9690 /* check for a group name, skip it if present */
9691 include_groups = FALSE;
9692 p = arg;
9693 group = au_get_grouparg(&arg);
9694 if (group == AUGROUP_ERROR)
9695 return NULL;
9696 /* If there only is a group name that's what we expand. */
9697 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9698 {
9699 arg = p;
9700 group = AUGROUP_ALL;
9701 }
9702
9703 /* skip over event name */
9704 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9705 if (*p == ',')
9706 arg = p + 1;
9707 if (*p == NUL)
9708 {
9709 if (group == AUGROUP_ALL)
9710 include_groups = TRUE;
9711 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9712 xp->xp_pattern = arg;
9713 return NULL;
9714 }
9715
9716 /* skip over pattern */
9717 arg = skipwhite(p);
9718 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9719 arg++;
9720 if (*arg)
9721 return arg; /* expand (next) command */
9722
9723 if (doautocmd)
9724 xp->xp_context = EXPAND_FILES; /* expand file names */
9725 else
9726 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9727 return NULL;
9728}
9729
9730/*
9731 * Function given to ExpandGeneric() to obtain the list of event names.
9732 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009733 char_u *
9734get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009735 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009736 int idx;
9737{
9738 if (idx < augroups.ga_len) /* First list group names, if wanted */
9739 {
9740 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9741 return (char_u *)""; /* skip deleted entries */
9742 return AUGROUP_NAME(idx); /* return a name */
9743 }
9744 return (char_u *)event_names[idx - augroups.ga_len].name;
9745}
9746
9747#endif /* FEAT_CMDL_COMPL */
9748
9749/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009750 * Return TRUE if autocmd is supported.
9751 */
9752 int
9753autocmd_supported(name)
9754 char_u *name;
9755{
9756 char_u *p;
9757
9758 return (event_name2nr(name, &p) != NUM_EVENTS);
9759}
9760
9761/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009762 * Return TRUE if an autocommand is defined for a group, event and
9763 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9764 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9765 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9766 * Used for:
9767 * exists("#Group") or
9768 * exists("#Group#Event") or
9769 * exists("#Group#Event#pat") or
9770 * exists("#Event") or
9771 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009772 */
9773 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009774au_exists(arg)
9775 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009776{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009777 char_u *arg_save;
9778 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009779 char_u *event_name;
9780 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009781 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009782 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009783 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009784 int group;
9785 int retval = FALSE;
9786
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009787 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009788 arg_save = vim_strsave(arg);
9789 if (arg_save == NULL)
9790 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009791 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009792 if (p != NULL)
9793 *p++ = NUL;
9794
9795 /* First, look for an autocmd group name */
9796 group = au_find_group(arg_save);
9797 if (group == AUGROUP_ERROR)
9798 {
9799 /* Didn't match a group name, assume the first argument is an event. */
9800 group = AUGROUP_ALL;
9801 event_name = arg_save;
9802 }
9803 else
9804 {
9805 if (p == NULL)
9806 {
9807 /* "Group": group name is present and it's recognized */
9808 retval = TRUE;
9809 goto theend;
9810 }
9811
9812 /* Must be "Group#Event" or "Group#Event#pat". */
9813 event_name = p;
9814 p = vim_strchr(event_name, '#');
9815 if (p != NULL)
9816 *p++ = NUL; /* "Group#Event#pat" */
9817 }
9818
9819 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009820
9821 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009822 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009823
9824 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009825 if (event == NUM_EVENTS)
9826 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009827
9828 /* Find the first autocommand for this event.
9829 * If there isn't any, return FALSE;
9830 * If there is one and no pattern given, return TRUE; */
9831 ap = first_autopat[(int)event];
9832 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009833 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009834
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009835 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9836 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009837 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009838 buflocal_buf = curbuf;
9839
Bram Moolenaar071d4272004-06-13 20:20:40 +00009840 /* Check if there is an autocommand with the given pattern. */
9841 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009842 /* only use a pattern when it has not been removed and has commands. */
9843 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009844 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009845 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009846 && (pattern == NULL
9847 || (buflocal_buf == NULL
9848 ? fnamecmp(ap->pat, pattern) == 0
9849 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009850 {
9851 retval = TRUE;
9852 break;
9853 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009854
Bram Moolenaar195d6352005-12-19 22:08:24 +00009855theend:
9856 vim_free(arg_save);
9857 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009858}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009859
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009860#else /* FEAT_AUTOCMD */
9861
9862/*
9863 * Prepare for executing commands for (hidden) buffer "buf".
9864 * This is the non-autocommand version, it simply saves "curbuf" and sets
9865 * "curbuf" and "curwin" to match "buf".
9866 */
9867 void
9868aucmd_prepbuf(aco, buf)
9869 aco_save_T *aco; /* structure to save values in */
9870 buf_T *buf; /* new curbuf */
9871{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009872 aco->save_curbuf = curbuf;
9873 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009874 curbuf = buf;
9875 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009876 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009877}
9878
9879/*
9880 * Restore after executing commands for a (hidden) buffer.
9881 * This is the non-autocommand version.
9882 */
9883 void
9884aucmd_restbuf(aco)
9885 aco_save_T *aco; /* structure holding saved values */
9886{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009887 --curbuf->b_nwindows;
9888 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009889 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009890 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009891}
9892
Bram Moolenaar071d4272004-06-13 20:20:40 +00009893#endif /* FEAT_AUTOCMD */
9894
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009895
Bram Moolenaar071d4272004-06-13 20:20:40 +00009896#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9897/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009898 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9899 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9900 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009901 * Used for autocommands and 'wildignore'.
9902 * Returns TRUE if there is a match, FALSE otherwise.
9903 */
9904 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009905match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009906 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009907 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009908 char_u *fname; /* full path of file name */
9909 char_u *sfname; /* short file name or NULL */
9910 char_u *tail; /* tail of path */
9911 int allow_dirs; /* allow matching with dir */
9912{
9913 regmatch_T regmatch;
9914 int result = FALSE;
9915#ifdef FEAT_OSFILETYPE
9916 int no_pattern = FALSE; /* TRUE if check is filetype only */
9917 char_u *type_start;
9918 char_u c;
9919 int match = FALSE;
9920#endif
9921
9922#ifdef CASE_INSENSITIVE_FILENAME
9923 regmatch.rm_ic = TRUE; /* Always ignore case */
9924#else
9925 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9926#endif
9927#ifdef FEAT_OSFILETYPE
9928 if (*pattern == '<')
9929 {
9930 /* There is a filetype condition specified with this pattern.
9931 * Check the filetype matches first. If not, don't bother with the
9932 * pattern (set regprog to NULL).
9933 * Always use magic for the regexp.
9934 */
9935
9936 for (type_start = pattern + 1; (c = *pattern); pattern++)
9937 {
9938 if ((c == ';' || c == '>') && match == FALSE)
9939 {
9940 *pattern = NUL; /* Terminate the string */
9941 match = mch_check_filetype(fname, type_start);
9942 *pattern = c; /* Restore the terminator */
9943 type_start = pattern + 1;
9944 }
9945 if (c == '>')
9946 break;
9947 }
9948
9949 /* (c should never be NUL, but check anyway) */
9950 if (match == FALSE || c == NUL)
9951 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9952 else if (*pattern == NUL)
9953 {
9954 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9955 no_pattern = TRUE; /* Always matches - don't check pat. */
9956 }
9957 else
9958 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9959 }
9960 else
9961#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009962 {
9963 if (prog != NULL)
9964 regmatch.regprog = prog;
9965 else
9966 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9967 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009968
9969 /*
9970 * Try for a match with the pattern with:
9971 * 1. the full file name, when the pattern has a '/'.
9972 * 2. the short file name, when the pattern has a '/'.
9973 * 3. the tail of the file name, when the pattern has no '/'.
9974 */
9975 if (
9976#ifdef FEAT_OSFILETYPE
9977 /* If the check is for a filetype only and we don't care
9978 * about the path then skip all the regexp stuff.
9979 */
9980 no_pattern ||
9981#endif
9982 (regmatch.regprog != NULL
9983 && ((allow_dirs
9984 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9985 || (sfname != NULL
9986 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9987 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9988 result = TRUE;
9989
Bram Moolenaar748bf032005-02-02 23:04:36 +00009990 if (prog == NULL)
9991 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009992 return result;
9993}
9994#endif
9995
9996#if defined(FEAT_WILDIGN) || defined(PROTO)
9997/*
9998 * Return TRUE if a file matches with a pattern in "list".
9999 * "list" is a comma-separated list of patterns, like 'wildignore'.
10000 * "sfname" is the short file name or NULL, "ffname" the long file name.
10001 */
10002 int
10003match_file_list(list, sfname, ffname)
10004 char_u *list;
10005 char_u *sfname;
10006 char_u *ffname;
10007{
10008 char_u buf[100];
10009 char_u *tail;
10010 char_u *regpat;
10011 char allow_dirs;
10012 int match;
10013 char_u *p;
10014
10015 tail = gettail(sfname);
10016
10017 /* try all patterns in 'wildignore' */
10018 p = list;
10019 while (*p)
10020 {
10021 copy_option_part(&p, buf, 100, ",");
10022 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10023 if (regpat == NULL)
10024 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010025 match = match_file_pat(regpat, NULL, ffname, sfname,
10026 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010027 vim_free(regpat);
10028 if (match)
10029 return TRUE;
10030 }
10031 return FALSE;
10032}
10033#endif
10034
10035/*
10036 * Convert the given pattern "pat" which has shell style wildcards in it, into
10037 * a regular expression, and return the result in allocated memory. If there
10038 * is a directory path separator to be matched, then TRUE is put in
10039 * allow_dirs, otherwise FALSE is put there -- webb.
10040 * Handle backslashes before special characters, like "\*" and "\ ".
10041 *
10042 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10043 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10044 *
10045 * Returns NULL when out of memory.
10046 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010047 char_u *
10048file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10049 char_u *pat;
10050 char_u *pat_end; /* first char after pattern or NULL */
10051 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010052 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010053{
10054 int size;
10055 char_u *endp;
10056 char_u *reg_pat;
10057 char_u *p;
10058 int i;
10059 int nested = 0;
10060 int add_dollar = TRUE;
10061#ifdef FEAT_OSFILETYPE
10062 int check_length = 0;
10063#endif
10064
10065 if (allow_dirs != NULL)
10066 *allow_dirs = FALSE;
10067 if (pat_end == NULL)
10068 pat_end = pat + STRLEN(pat);
10069
10070#ifdef FEAT_OSFILETYPE
10071 /* Find out how much of the string is the filetype check */
10072 if (*pat == '<')
10073 {
10074 /* Count chars until the next '>' */
10075 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10076 ;
10077 if (p < pat_end)
10078 {
10079 /* Pattern is of the form <.*>.* */
10080 check_length = p - pat + 1;
10081 if (p + 1 >= pat_end)
10082 {
10083 /* The 'pattern' is a filetype check ONLY */
10084 reg_pat = (char_u *)alloc(check_length + 1);
10085 if (reg_pat != NULL)
10086 {
10087 mch_memmove(reg_pat, pat, (size_t)check_length);
10088 reg_pat[check_length] = NUL;
10089 }
10090 return reg_pat;
10091 }
10092 }
10093 /* else: there was no closing '>' - assume it was a normal pattern */
10094
10095 }
10096 pat += check_length;
10097 size = 2 + check_length;
10098#else
10099 size = 2; /* '^' at start, '$' at end */
10100#endif
10101
10102 for (p = pat; p < pat_end; p++)
10103 {
10104 switch (*p)
10105 {
10106 case '*':
10107 case '.':
10108 case ',':
10109 case '{':
10110 case '}':
10111 case '~':
10112 size += 2; /* extra backslash */
10113 break;
10114#ifdef BACKSLASH_IN_FILENAME
10115 case '\\':
10116 case '/':
10117 size += 4; /* could become "[\/]" */
10118 break;
10119#endif
10120 default:
10121 size++;
10122# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010123 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010124 {
10125 ++p;
10126 ++size;
10127 }
10128# endif
10129 break;
10130 }
10131 }
10132 reg_pat = alloc(size + 1);
10133 if (reg_pat == NULL)
10134 return NULL;
10135
10136#ifdef FEAT_OSFILETYPE
10137 /* Copy the type check in to the start. */
10138 if (check_length)
10139 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10140 i = check_length;
10141#else
10142 i = 0;
10143#endif
10144
10145 if (pat[0] == '*')
10146 while (pat[0] == '*' && pat < pat_end - 1)
10147 pat++;
10148 else
10149 reg_pat[i++] = '^';
10150 endp = pat_end - 1;
10151 if (*endp == '*')
10152 {
10153 while (endp - pat > 0 && *endp == '*')
10154 endp--;
10155 add_dollar = FALSE;
10156 }
10157 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10158 {
10159 switch (*p)
10160 {
10161 case '*':
10162 reg_pat[i++] = '.';
10163 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010164 while (p[1] == '*') /* "**" matches like "*" */
10165 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010166 break;
10167 case '.':
10168#ifdef RISCOS
10169 if (allow_dirs != NULL)
10170 *allow_dirs = TRUE;
10171 /* FALLTHROUGH */
10172#endif
10173 case '~':
10174 reg_pat[i++] = '\\';
10175 reg_pat[i++] = *p;
10176 break;
10177 case '?':
10178#ifdef RISCOS
10179 case '#':
10180#endif
10181 reg_pat[i++] = '.';
10182 break;
10183 case '\\':
10184 if (p[1] == NUL)
10185 break;
10186#ifdef BACKSLASH_IN_FILENAME
10187 if (!no_bslash)
10188 {
10189 /* translate:
10190 * "\x" to "\\x" e.g., "dir\file"
10191 * "\*" to "\\.*" e.g., "dir\*.c"
10192 * "\?" to "\\." e.g., "dir\??.c"
10193 * "\+" to "\+" e.g., "fileX\+.c"
10194 */
10195 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10196 && p[1] != '+')
10197 {
10198 reg_pat[i++] = '[';
10199 reg_pat[i++] = '\\';
10200 reg_pat[i++] = '/';
10201 reg_pat[i++] = ']';
10202 if (allow_dirs != NULL)
10203 *allow_dirs = TRUE;
10204 break;
10205 }
10206 }
10207#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010208 /* Undo escaping from ExpandEscape():
10209 * foo\?bar -> foo?bar
10210 * foo\%bar -> foo%bar
10211 * foo\,bar -> foo,bar
10212 * foo\ bar -> foo bar
10213 * Don't unescape \, * and others that are also special in a
10214 * regexp. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010215 if (*++p == '?'
10216#ifdef BACKSLASH_IN_FILENAME
10217 && no_bslash
10218#endif
10219 )
10220 reg_pat[i++] = '?';
10221 else
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010222 if (*p == ',' || *p == '%' || *p == '#' || *p == ' ')
10223 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010224 else
10225 {
10226 if (allow_dirs != NULL && vim_ispathsep(*p)
10227#ifdef BACKSLASH_IN_FILENAME
10228 && (!no_bslash || *p != '\\')
10229#endif
10230 )
10231 *allow_dirs = TRUE;
10232 reg_pat[i++] = '\\';
10233 reg_pat[i++] = *p;
10234 }
10235 break;
10236#ifdef BACKSLASH_IN_FILENAME
10237 case '/':
10238 reg_pat[i++] = '[';
10239 reg_pat[i++] = '\\';
10240 reg_pat[i++] = '/';
10241 reg_pat[i++] = ']';
10242 if (allow_dirs != NULL)
10243 *allow_dirs = TRUE;
10244 break;
10245#endif
10246 case '{':
10247 reg_pat[i++] = '\\';
10248 reg_pat[i++] = '(';
10249 nested++;
10250 break;
10251 case '}':
10252 reg_pat[i++] = '\\';
10253 reg_pat[i++] = ')';
10254 --nested;
10255 break;
10256 case ',':
10257 if (nested)
10258 {
10259 reg_pat[i++] = '\\';
10260 reg_pat[i++] = '|';
10261 }
10262 else
10263 reg_pat[i++] = ',';
10264 break;
10265 default:
10266# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010267 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010268 reg_pat[i++] = *p++;
10269 else
10270# endif
10271 if (allow_dirs != NULL && vim_ispathsep(*p))
10272 *allow_dirs = TRUE;
10273 reg_pat[i++] = *p;
10274 break;
10275 }
10276 }
10277 if (add_dollar)
10278 reg_pat[i++] = '$';
10279 reg_pat[i] = NUL;
10280 if (nested != 0)
10281 {
10282 if (nested < 0)
10283 EMSG(_("E219: Missing {."));
10284 else
10285 EMSG(_("E220: Missing }."));
10286 vim_free(reg_pat);
10287 reg_pat = NULL;
10288 }
10289 return reg_pat;
10290}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010291
10292#if defined(EINTR) || defined(PROTO)
10293/*
10294 * Version of read() that retries when interrupted by EINTR (possibly
10295 * by a SIGWINCH).
10296 */
10297 long
10298read_eintr(fd, buf, bufsize)
10299 int fd;
10300 void *buf;
10301 size_t bufsize;
10302{
10303 long ret;
10304
10305 for (;;)
10306 {
10307 ret = vim_read(fd, buf, bufsize);
10308 if (ret >= 0 || errno != EINTR)
10309 break;
10310 }
10311 return ret;
10312}
10313
10314/*
10315 * Version of write() that retries when interrupted by EINTR (possibly
10316 * by a SIGWINCH).
10317 */
10318 long
10319write_eintr(fd, buf, bufsize)
10320 int fd;
10321 void *buf;
10322 size_t bufsize;
10323{
10324 long ret = 0;
10325 long wlen;
10326
10327 /* Repeat the write() so long it didn't fail, other than being interrupted
10328 * by a signal. */
10329 while (ret < (long)bufsize)
10330 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010331 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010332 if (wlen < 0)
10333 {
10334 if (errno != EINTR)
10335 break;
10336 }
10337 else
10338 ret += wlen;
10339 }
10340 return ret;
10341}
10342#endif