blob: 0843d042961432561d96089046a0fc0f5ff13b1b [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
Bram Moolenaar071d4272004-06-13 20:20:40 +000027/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000028#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000029
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000030#if defined(sun) && defined(S_ISCHR)
31# define OPEN_CHR_FILES
32static int is_dev_fd_file(char_u *fname);
33#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000034#ifdef FEAT_MBYTE
35static char_u *next_fenc __ARGS((char_u **pp));
36# ifdef FEAT_EVAL
37static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
38# endif
39#endif
40#ifdef FEAT_VIMINFO
41static void check_marks_read __ARGS((void));
42#endif
43#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +020044static 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 +000045#endif
46#ifdef UNIX
47static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
48#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000049static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000050static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000051static void msg_add_eol __ARGS((void));
52static int check_mtime __ARGS((buf_T *buf, struct stat *s));
53static int time_differs __ARGS((long t1, long t2));
54#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000055static 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 +000056static int au_find_group __ARGS((char_u *name));
57
58# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000059# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000060# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000061#endif
62
63#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
64# define HAS_BW_FLAGS
65# define FIO_LATIN1 0x01 /* convert Latin1 */
66# define FIO_UTF8 0x02 /* convert UTF-8 */
67# define FIO_UCS2 0x04 /* convert UCS-2 */
68# define FIO_UCS4 0x08 /* convert UCS-4 */
69# define FIO_UTF16 0x10 /* convert UTF-16 */
70# ifdef WIN3264
71# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
72# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
73# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
74# endif
75# ifdef MACOS_X
76# define FIO_MACROMAN 0x20 /* convert MacRoman */
77# endif
78# define FIO_ENDIAN_L 0x80 /* little endian */
79# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
80# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
81# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
82# define FIO_ALL -1 /* allow all formats */
83#endif
84
85/* When converting, a read() or write() may leave some bytes to be converted
86 * for the next call. The value is guessed... */
87#define CONV_RESTLEN 30
88
89/* We have to guess how much a sequence of bytes may expand when converting
90 * with iconv() to be able to allocate a buffer. */
91#define ICONV_MULT 8
92
93/*
94 * Structure to pass arguments from buf_write() to buf_write_bytes().
95 */
96struct bw_info
97{
98 int bw_fd; /* file descriptor */
99 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000100 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000101#ifdef HAS_BW_FLAGS
102 int bw_flags; /* FIO_ flags */
103#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +0200104#ifdef FEAT_CRYPT
105 buf_T *bw_buffer; /* buffer being written */
106#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107#ifdef FEAT_MBYTE
108 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
109 int bw_restlen; /* nr of bytes in bw_rest[] */
110 int bw_first; /* first write call */
111 char_u *bw_conv_buf; /* buffer for writing converted chars */
112 int bw_conv_buflen; /* size of bw_conv_buf */
113 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000114 linenr_T bw_conv_error_lnum; /* first line with error or zero */
115 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000116# ifdef USE_ICONV
117 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
118# endif
119#endif
120};
121
122static int buf_write_bytes __ARGS((struct bw_info *ip));
123
124#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000125static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000126static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000127static int need_conversion __ARGS((char_u *fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000128static int get_fio_flags __ARGS((char_u *ptr));
129static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
130static int make_bom __ARGS((char_u *buf, char_u *name));
131# ifdef WIN3264
132static int get_win_fio_flags __ARGS((char_u *ptr));
133# endif
134# ifdef MACOS_X
135static int get_mac_fio_flags __ARGS((char_u *ptr));
136# endif
137#endif
138static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000139#ifdef TEMPDIRNAMES
Bram Moolenaareaf03392009-11-17 11:08:52 +0000140static void vim_settempdir __ARGS((char_u *tempdir));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000141#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000142#ifdef FEAT_AUTOCMD
143static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
144#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000145
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146 void
147filemess(buf, name, s, attr)
148 buf_T *buf;
149 char_u *name;
150 char_u *s;
151 int attr;
152{
153 int msg_scroll_save;
154
155 if (msg_silent != 0)
156 return;
157 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
158 /* If it's extremely long, truncate it. */
159 if (STRLEN(IObuff) > IOSIZE - 80)
160 IObuff[IOSIZE - 80] = NUL;
161 STRCAT(IObuff, s);
162 /*
163 * For the first message may have to start a new line.
164 * For further ones overwrite the previous one, reset msg_scroll before
165 * calling filemess().
166 */
167 msg_scroll_save = msg_scroll;
168 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
169 msg_scroll = FALSE;
170 if (!msg_scroll) /* wait a bit when overwriting an error msg */
171 check_for_delay(FALSE);
172 msg_start();
173 msg_scroll = msg_scroll_save;
174 msg_scrolled_ign = TRUE;
175 /* may truncate the message to avoid a hit-return prompt */
176 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
177 msg_clr_eos();
178 out_flush();
179 msg_scrolled_ign = FALSE;
180}
181
182/*
183 * Read lines from file "fname" into the buffer after line "from".
184 *
185 * 1. We allocate blocks with lalloc, as big as possible.
186 * 2. Each block is filled with characters from the file with a single read().
187 * 3. The lines are inserted in the buffer with ml_append().
188 *
189 * (caller must check that fname != NULL, unless READ_STDIN is used)
190 *
191 * "lines_to_skip" is the number of lines that must be skipped
192 * "lines_to_read" is the number of lines that are appended
193 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
194 *
195 * flags:
196 * READ_NEW starting to edit a new buffer
197 * READ_FILTER reading filter output
198 * READ_STDIN read from stdin instead of a file
199 * READ_BUFFER read from curbuf instead of a file (converting after reading
200 * stdin)
201 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200202 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203 *
204 * return FAIL for failure, OK otherwise
205 */
206 int
207readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
208 char_u *fname;
209 char_u *sfname;
210 linenr_T from;
211 linenr_T lines_to_skip;
212 linenr_T lines_to_read;
213 exarg_T *eap; /* can be NULL! */
214 int flags;
215{
216 int fd = 0;
217 int newfile = (flags & READ_NEW);
218 int check_readonly;
219 int filtering = (flags & READ_FILTER);
220 int read_stdin = (flags & READ_STDIN);
221 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000222 int set_options = newfile || read_buffer
223 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000224 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
225 colnr_T read_buf_col = 0; /* next char to read from this line */
226 char_u c;
227 linenr_T lnum = from;
228 char_u *ptr = NULL; /* pointer into read buffer */
229 char_u *buffer = NULL; /* read buffer */
230 char_u *new_buffer = NULL; /* init to shut up gcc */
231 char_u *line_start = NULL; /* init to shut up gcc */
232 int wasempty; /* buffer was empty before reading */
233 colnr_T len;
234 long size = 0;
235 char_u *p;
Bram Moolenaar914703b2010-05-31 21:59:46 +0200236 off_t filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000237 int skip_read = FALSE;
238#ifdef FEAT_CRYPT
239 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200240 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000241#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200242#ifdef FEAT_PERSISTENT_UNDO
243 context_sha256_T sha_ctx;
244 int read_undo_file = FALSE;
245#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000246 int split = 0; /* number of split lines */
247#define UNKNOWN 0x0fffffff /* file size is unknown */
248 linenr_T linecnt;
249 int error = FALSE; /* errors encountered */
250 int ff_error = EOL_UNKNOWN; /* file format with errors */
251 long linerest = 0; /* remaining chars in line */
252#ifdef UNIX
253 int perm = 0;
254 int swap_mode = -1; /* protection bits for swap file */
255#else
256 int perm;
257#endif
258 int fileformat = 0; /* end-of-line format */
259 int keep_fileformat = FALSE;
260 struct stat st;
261 int file_readonly;
262 linenr_T skip_count = 0;
263 linenr_T read_count = 0;
264 int msg_save = msg_scroll;
265 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
266 * last read was missing the eol */
267 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
268 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
269 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
270 int file_rewind = FALSE;
271#ifdef FEAT_MBYTE
272 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000273 linenr_T conv_error = 0; /* line nr with conversion error */
274 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000275 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
276 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000277 int bad_char_behavior = BAD_REPLACE;
278 /* BAD_KEEP, BAD_DROP or character to
279 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280 char_u *tmpname = NULL; /* name of 'charconvert' output file */
281 int fio_flags = 0;
282 char_u *fenc; /* fileencoding to use */
283 int fenc_alloced; /* fenc_next is in allocated memory */
284 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
285 int advance_fenc = FALSE;
286 long real_size = 0;
287# ifdef USE_ICONV
288 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
289# ifdef FEAT_EVAL
290 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
291 'charconvert' next */
292# endif
293# endif
294 int converted = FALSE; /* TRUE if conversion done */
295 int notconverted = FALSE; /* TRUE if conversion wanted but it
296 wasn't possible */
297 char_u conv_rest[CONV_RESTLEN];
298 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
299#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000300#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200301 buf_T *old_curbuf;
302 char_u *old_b_ffname;
303 char_u *old_b_fname;
304 int using_b_ffname;
305 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000306#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200307
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100308 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000309
310 /*
311 * If there is no file name yet, use the one for the read file.
312 * BF_NOTEDITED is set to reflect this.
313 * Don't do this for a read from a filter.
314 * Only do this when 'cpoptions' contains the 'f' flag.
315 */
316 if (curbuf->b_ffname == NULL
317 && !filtering
318 && fname != NULL
319 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
320 && !(flags & READ_DUMMY))
321 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000322 if (set_rw_fname(fname, sfname) == FAIL)
323 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324 }
325
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200326#ifdef FEAT_AUTOCMD
327 /* Remember the initial values of curbuf, curbuf->b_ffname and
328 * curbuf->b_fname to detect whether they are altered as a result of
329 * executing nasty autocommands. Also check if "fname" and "sfname"
330 * point to one of these values. */
331 old_curbuf = curbuf;
332 old_b_ffname = curbuf->b_ffname;
333 old_b_fname = curbuf->b_fname;
334 using_b_ffname = (fname == curbuf->b_ffname)
335 || (sfname == curbuf->b_ffname);
336 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
337#endif
338
Bram Moolenaardf177f62005-02-22 08:39:57 +0000339 /* After reading a file the cursor line changes but we don't want to
340 * display the line. */
341 ex_no_reprint = TRUE;
342
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000343 /* don't display the file info for another buffer now */
344 need_fileinfo = FALSE;
345
Bram Moolenaar071d4272004-06-13 20:20:40 +0000346 /*
347 * For Unix: Use the short file name whenever possible.
348 * Avoids problems with networks and when directory names are changed.
349 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
350 * another directory, which we don't detect.
351 */
352 if (sfname == NULL)
353 sfname = fname;
354#if defined(UNIX) || defined(__EMX__)
355 fname = sfname;
356#endif
357
358#ifdef FEAT_AUTOCMD
359 /*
360 * The BufReadCmd and FileReadCmd events intercept the reading process by
361 * executing the associated commands instead.
362 */
363 if (!filtering && !read_stdin && !read_buffer)
364 {
365 pos_T pos;
366
367 pos = curbuf->b_op_start;
368
369 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
370 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
371 curbuf->b_op_start.col = 0;
372
373 if (newfile)
374 {
375 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
376 FALSE, curbuf, eap))
377#ifdef FEAT_EVAL
378 return aborting() ? FAIL : OK;
379#else
380 return OK;
381#endif
382 }
383 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
384 FALSE, NULL, eap))
385#ifdef FEAT_EVAL
386 return aborting() ? FAIL : OK;
387#else
388 return OK;
389#endif
390
391 curbuf->b_op_start = pos;
392 }
393#endif
394
395 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
396 msg_scroll = FALSE; /* overwrite previous file message */
397 else
398 msg_scroll = TRUE; /* don't overwrite previous file message */
399
400 /*
401 * If the name ends in a path separator, we can't open it. Check here,
402 * because reading the file may actually work, but then creating the swap
403 * file may destroy it! Reported on MS-DOS and Win 95.
404 * If the name is too long we might crash further on, quit here.
405 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000406 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000407 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000408 p = fname + STRLEN(fname);
409 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000410 {
411 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
412 msg_end();
413 msg_scroll = msg_save;
414 return FAIL;
415 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416 }
417
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 if (!read_stdin && !read_buffer)
419 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200420#ifdef UNIX
421 /*
422 * On Unix it is possible to read a directory, so we have to
423 * check for it before the mch_open().
424 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000425 perm = mch_getperm(fname);
426 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
427# ifdef S_ISFIFO
428 && !S_ISFIFO(perm) /* ... or fifo */
429# endif
430# ifdef S_ISSOCK
431 && !S_ISSOCK(perm) /* ... or socket */
432# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000433# ifdef OPEN_CHR_FILES
434 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
435 /* ... or a character special file named /dev/fd/<n> */
436# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000437 )
438 {
439 if (S_ISDIR(perm))
440 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
441 else
442 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
443 msg_end();
444 msg_scroll = msg_save;
445 return FAIL;
446 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200447#endif
448#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000449 /*
450 * MS-Windows allows opening a device, but we will probably get stuck
451 * trying to read it.
452 */
453 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
454 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000455 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000456 msg_end();
457 msg_scroll = msg_save;
458 return FAIL;
459 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000460#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200461 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000462
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200463 /* Set default or forced 'fileformat' and 'binary'. */
464 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000465
466 /*
467 * When opening a new file we take the readonly flag from the file.
468 * Default is r/w, can be set to r/o below.
469 * Don't reset it when in readonly mode
470 * Only set/reset b_p_ro when BF_CHECK_RO is set.
471 */
472 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000473 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000474 curbuf->b_p_ro = FALSE;
475
476 if (newfile && !read_stdin && !read_buffer)
477 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200478 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000479 if (mch_stat((char *)fname, &st) >= 0)
480 {
481 buf_store_time(curbuf, &st, fname);
482 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000483#ifdef UNIX
484 /*
485 * Use the protection bits of the original file for the swap file.
486 * This makes it possible for others to read the name of the
487 * edited file from the swapfile, but only if they can read the
488 * edited file.
489 * Remove the "write" and "execute" bits for group and others
490 * (they must not write the swapfile).
491 * Add the "read" and "write" bits for the user, otherwise we may
492 * not be able to write to the file ourselves.
493 * Setting the bits is done below, after creating the swap file.
494 */
495 swap_mode = (st.st_mode & 0644) | 0600;
496#endif
497#ifdef FEAT_CW_EDITOR
498 /* Get the FSSpec on MacOS
499 * TODO: Update it properly when the buffer name changes
500 */
501 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
502#endif
503#ifdef VMS
504 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000505 curbuf->b_fab_rat = st.st_fab_rat;
506 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000507#endif
508 }
509 else
510 {
511 curbuf->b_mtime = 0;
512 curbuf->b_mtime_read = 0;
513 curbuf->b_orig_size = 0;
514 curbuf->b_orig_mode = 0;
515 }
516
517 /* Reset the "new file" flag. It will be set again below when the
518 * file doesn't exist. */
519 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
520 }
521
522/*
523 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar071d4272004-06-13 20:20:40 +0000524 * for MSDOS and Amiga: check readonly by trying to open the file for writing
525 */
526 file_readonly = FALSE;
527 if (read_stdin)
528 {
529#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
530 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
531 setmode(0, O_BINARY);
532#endif
533 }
534 else if (!read_buffer)
535 {
536#ifdef USE_MCH_ACCESS
537 if (
538# ifdef UNIX
539 !(perm & 0222) ||
540# endif
541 mch_access((char *)fname, W_OK))
542 file_readonly = TRUE;
543 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
544#else
545 if (!newfile
546 || readonlymode
547 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
548 {
549 file_readonly = TRUE;
550 /* try to open ro */
551 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
552 }
553#endif
554 }
555
556 if (fd < 0) /* cannot open at all */
557 {
558#ifndef UNIX
559 int isdir_f;
560#endif
561 msg_scroll = msg_save;
562#ifndef UNIX
563 /*
564 * On MSDOS and Amiga we can't open a directory, check here.
565 */
566 isdir_f = (mch_isdir(fname));
567 perm = mch_getperm(fname); /* check if the file exists */
568 if (isdir_f)
569 {
570 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
571 curbuf->b_p_ro = TRUE; /* must use "w!" now */
572 }
573 else
574#endif
575 if (newfile)
576 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200577 if (perm < 0
578#ifdef ENOENT
579 && errno == ENOENT
580#endif
581 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000582 {
583 /*
584 * Set the 'new-file' flag, so that when the file has
585 * been created by someone else, a ":w" will complain.
586 */
587 curbuf->b_flags |= BF_NEW;
588
589 /* Create a swap file now, so that other Vims are warned
590 * that we are editing this file. Don't do this for a
591 * "nofile" or "nowrite" buffer type. */
592#ifdef FEAT_QUICKFIX
593 if (!bt_dontwrite(curbuf))
594#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000595 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000596 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000597#ifdef FEAT_AUTOCMD
598 /* SwapExists autocommand may mess things up */
599 if (curbuf != old_curbuf
600 || (using_b_ffname
601 && (old_b_ffname != curbuf->b_ffname))
602 || (using_b_fname
603 && (old_b_fname != curbuf->b_fname)))
604 {
605 EMSG(_(e_auchangedbuf));
606 return FAIL;
607 }
608#endif
609 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000610 if (dir_of_file_exists(fname))
611 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
612 else
613 filemess(curbuf, sfname,
614 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000615#ifdef FEAT_VIMINFO
616 /* Even though this is a new file, it might have been
617 * edited before and deleted. Get the old marks. */
618 check_marks_read();
619#endif
620#ifdef FEAT_MBYTE
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200621 /* Set forced 'fileencoding'. */
622 if (eap != NULL)
623 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000624#endif
625#ifdef FEAT_AUTOCMD
626 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
627 FALSE, curbuf, eap);
628#endif
629 /* remember the current fileformat */
630 save_file_ff(curbuf);
631
632#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
633 if (aborting()) /* autocmds may abort script processing */
634 return FAIL;
635#endif
636 return OK; /* a new file is not an error */
637 }
638 else
639 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000640 filemess(curbuf, sfname, (char_u *)(
641# ifdef EFBIG
642 (errno == EFBIG) ? _("[File too big]") :
643# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200644# ifdef EOVERFLOW
645 (errno == EOVERFLOW) ? _("[File too big]") :
646# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000647 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000648 curbuf->b_p_ro = TRUE; /* must use "w!" now */
649 }
650 }
651
652 return FAIL;
653 }
654
655 /*
656 * Only set the 'ro' flag for readonly files the first time they are
657 * loaded. Help files always get readonly mode
658 */
659 if ((check_readonly && file_readonly) || curbuf->b_help)
660 curbuf->b_p_ro = TRUE;
661
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000662 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000663 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000664 /* Don't change 'eol' if reading from buffer as it will already be
665 * correctly set when reading stdin. */
666 if (!read_buffer)
667 {
668 curbuf->b_p_eol = TRUE;
669 curbuf->b_start_eol = TRUE;
670 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000671#ifdef FEAT_MBYTE
672 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000673 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000674#endif
675 }
676
677 /* Create a swap file now, so that other Vims are warned that we are
678 * editing this file.
679 * Don't do this for a "nofile" or "nowrite" buffer type. */
680#ifdef FEAT_QUICKFIX
681 if (!bt_dontwrite(curbuf))
682#endif
683 {
684 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000685#ifdef FEAT_AUTOCMD
686 if (!read_stdin && (curbuf != old_curbuf
687 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
688 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
689 {
690 EMSG(_(e_auchangedbuf));
691 if (!read_buffer)
692 close(fd);
693 return FAIL;
694 }
695#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000696#ifdef UNIX
697 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000698 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
699 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000700 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
701#endif
702 }
703
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000704#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000705 /* If "Quit" selected at ATTENTION dialog, don't load the file */
706 if (swap_exists_action == SEA_QUIT)
707 {
708 if (!read_buffer && !read_stdin)
709 close(fd);
710 return FAIL;
711 }
712#endif
713
714 ++no_wait_return; /* don't wait for return yet */
715
716 /*
717 * Set '[ mark to the line above where the lines go (line 1 if zero).
718 */
719 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
720 curbuf->b_op_start.col = 0;
721
722#ifdef FEAT_AUTOCMD
723 if (!read_buffer)
724 {
725 int m = msg_scroll;
726 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727
728 /*
729 * The file must be closed again, the autocommands may want to change
730 * the file before reading it.
731 */
732 if (!read_stdin)
733 close(fd); /* ignore errors */
734
735 /*
736 * The output from the autocommands should not overwrite anything and
737 * should not be overwritten: Set msg_scroll, restore its value if no
738 * output was done.
739 */
740 msg_scroll = TRUE;
741 if (filtering)
742 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
743 FALSE, curbuf, eap);
744 else if (read_stdin)
745 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
746 FALSE, curbuf, eap);
747 else if (newfile)
748 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
749 FALSE, curbuf, eap);
750 else
751 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
752 FALSE, NULL, eap);
753 if (msg_scrolled == n)
754 msg_scroll = m;
755
756#ifdef FEAT_EVAL
757 if (aborting()) /* autocmds may abort script processing */
758 {
759 --no_wait_return;
760 msg_scroll = msg_save;
761 curbuf->b_p_ro = TRUE; /* must use "w!" now */
762 return FAIL;
763 }
764#endif
765 /*
766 * Don't allow the autocommands to change the current buffer.
767 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000768 *
769 * Don't allow the autocommands to change the buffer name either
770 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000771 */
772 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000773 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
774 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
776 {
777 --no_wait_return;
778 msg_scroll = msg_save;
779 if (fd < 0)
780 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
781 else
782 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
783 curbuf->b_p_ro = TRUE; /* must use "w!" now */
784 return FAIL;
785 }
786 }
787#endif /* FEAT_AUTOCMD */
788
789 /* Autocommands may add lines to the file, need to check if it is empty */
790 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
791
792 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
793 {
794 /*
795 * Show the user that we are busy reading the input. Sometimes this
796 * may take a while. When reading from stdin another program may
797 * still be running, don't move the cursor to the last line, unless
798 * always using the GUI.
799 */
800 if (read_stdin)
801 {
802#ifndef ALWAYS_USE_GUI
803 mch_msg(_("Vim: Reading from stdin...\n"));
804#endif
805#ifdef FEAT_GUI
806 /* Also write a message in the GUI window, if there is one. */
807 if (gui.in_use && !gui.dying && !gui.starting)
808 {
809 p = (char_u *)_("Reading from stdin...");
810 gui_write(p, (int)STRLEN(p));
811 }
812#endif
813 }
814 else if (!read_buffer)
815 filemess(curbuf, sfname, (char_u *)"", 0);
816 }
817
818 msg_scroll = FALSE; /* overwrite the file message */
819
820 /*
821 * Set linecnt now, before the "retry" caused by a wrong guess for
822 * fileformat, and after the autocommands, which may change them.
823 */
824 linecnt = curbuf->b_ml.ml_line_count;
825
826#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000827 /* "++bad=" argument. */
828 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000829 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000830 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000831 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000832 curbuf->b_bad_char = eap->bad_char;
833 }
834 else
835 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000836
Bram Moolenaar071d4272004-06-13 20:20:40 +0000837 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000838 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000839 */
840 if (eap != NULL && eap->force_enc != 0)
841 {
842 fenc = enc_canonize(eap->cmd + eap->force_enc);
843 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000844 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000845 }
846 else if (curbuf->b_p_bin)
847 {
848 fenc = (char_u *)""; /* binary: don't convert */
849 fenc_alloced = FALSE;
850 }
851 else if (curbuf->b_help)
852 {
853 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000854 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000855
856 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
857 * fails it must be latin1.
858 * Always do this when 'encoding' is "utf-8". Otherwise only do
859 * this when needed to avoid [converted] remarks all the time.
860 * It is needed when the first line contains non-ASCII characters.
861 * That is only in *.??x files. */
862 fenc = (char_u *)"latin1";
863 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000864 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000865 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000866 fc = fname[STRLEN(fname) - 1];
867 if (TOLOWER_ASC(fc) == 'x')
868 {
869 /* Read the first line (and a bit more). Immediately rewind to
870 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100871 len = read_eintr(fd, firstline, 80);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000872 lseek(fd, (off_t)0L, SEEK_SET);
873 for (p = firstline; p < firstline + len; ++p)
874 if (*p >= 0x80)
875 {
876 c = TRUE;
877 break;
878 }
879 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000880 }
881
882 if (c)
883 {
884 fenc_next = fenc;
885 fenc = (char_u *)"utf-8";
886
887 /* When the file is utf-8 but a character doesn't fit in
888 * 'encoding' don't retry. In help text editing utf-8 bytes
889 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000890 if (!enc_utf8)
891 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892 }
893 fenc_alloced = FALSE;
894 }
895 else if (*p_fencs == NUL)
896 {
897 fenc = curbuf->b_p_fenc; /* use format from buffer */
898 fenc_alloced = FALSE;
899 }
900 else
901 {
902 fenc_next = p_fencs; /* try items in 'fileencodings' */
903 fenc = next_fenc(&fenc_next);
904 fenc_alloced = TRUE;
905 }
906#endif
907
908 /*
909 * Jump back here to retry reading the file in different ways.
910 * Reasons to retry:
911 * - encoding conversion failed: try another one from "fenc_next"
912 * - BOM detected and fenc was set, need to setup conversion
913 * - "fileformat" check failed: try another
914 *
915 * Variables set for special retry actions:
916 * "file_rewind" Rewind the file to start reading it again.
917 * "advance_fenc" Advance "fenc" using "fenc_next".
918 * "skip_read" Re-use already read bytes (BOM detected).
919 * "did_iconv" iconv() conversion failed, try 'charconvert'.
920 * "keep_fileformat" Don't reset "fileformat".
921 *
922 * Other status indicators:
923 * "tmpname" When != NULL did conversion with 'charconvert'.
924 * Output file has to be deleted afterwards.
925 * "iconv_fd" When != -1 did conversion with iconv().
926 */
927retry:
928
929 if (file_rewind)
930 {
931 if (read_buffer)
932 {
933 read_buf_lnum = 1;
934 read_buf_col = 0;
935 }
936 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
937 {
938 /* Can't rewind the file, give up. */
939 error = TRUE;
940 goto failed;
941 }
942 /* Delete the previously read lines. */
943 while (lnum > from)
944 ml_delete(lnum--, FALSE);
945 file_rewind = FALSE;
946#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000947 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000948 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000949 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000950 curbuf->b_start_bomb = FALSE;
951 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000952 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000953#endif
954 }
955
956 /*
957 * When retrying with another "fenc" and the first time "fileformat"
958 * will be reset.
959 */
960 if (keep_fileformat)
961 keep_fileformat = FALSE;
962 else
963 {
964 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000965 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000966 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000967 try_unix = try_dos = try_mac = FALSE;
968 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000969 else if (curbuf->b_p_bin)
970 fileformat = EOL_UNIX; /* binary: use Unix format */
971 else if (*p_ffs == NUL)
972 fileformat = get_fileformat(curbuf);/* use format from buffer */
973 else
974 fileformat = EOL_UNKNOWN; /* detect from file */
975 }
976
977#ifdef FEAT_MBYTE
978# ifdef USE_ICONV
979 if (iconv_fd != (iconv_t)-1)
980 {
981 /* aborted conversion with iconv(), close the descriptor */
982 iconv_close(iconv_fd);
983 iconv_fd = (iconv_t)-1;
984 }
985# endif
986
987 if (advance_fenc)
988 {
989 /*
990 * Try the next entry in 'fileencodings'.
991 */
992 advance_fenc = FALSE;
993
994 if (eap != NULL && eap->force_enc != 0)
995 {
996 /* Conversion given with "++cc=" wasn't possible, read
997 * without conversion. */
998 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000999 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001000 if (fenc_alloced)
1001 vim_free(fenc);
1002 fenc = (char_u *)"";
1003 fenc_alloced = FALSE;
1004 }
1005 else
1006 {
1007 if (fenc_alloced)
1008 vim_free(fenc);
1009 if (fenc_next != NULL)
1010 {
1011 fenc = next_fenc(&fenc_next);
1012 fenc_alloced = (fenc_next != NULL);
1013 }
1014 else
1015 {
1016 fenc = (char_u *)"";
1017 fenc_alloced = FALSE;
1018 }
1019 }
1020 if (tmpname != NULL)
1021 {
1022 mch_remove(tmpname); /* delete converted file */
1023 vim_free(tmpname);
1024 tmpname = NULL;
1025 }
1026 }
1027
1028 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001029 * Conversion may be required when the encoding of the file is different
1030 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031 */
1032 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001033 converted = need_conversion(fenc);
1034 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001035 {
1036
1037 /* "ucs-bom" means we need to check the first bytes of the file
1038 * for a BOM. */
1039 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1040 fio_flags = FIO_UCSBOM;
1041
1042 /*
1043 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1044 * done. This is handled below after read(). Prepare the
1045 * fio_flags to avoid having to parse the string each time.
1046 * Also check for Unicode to Latin1 conversion, because iconv()
1047 * appears not to handle this correctly. This works just like
1048 * conversion to UTF-8 except how the resulting character is put in
1049 * the buffer.
1050 */
1051 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1052 fio_flags = get_fio_flags(fenc);
1053
1054# ifdef WIN3264
1055 /*
1056 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1057 * is handled with MultiByteToWideChar().
1058 */
1059 if (fio_flags == 0)
1060 fio_flags = get_win_fio_flags(fenc);
1061# endif
1062
1063# ifdef MACOS_X
1064 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1065 if (fio_flags == 0)
1066 fio_flags = get_mac_fio_flags(fenc);
1067# endif
1068
1069# ifdef USE_ICONV
1070 /*
1071 * Try using iconv() if we can't convert internally.
1072 */
1073 if (fio_flags == 0
1074# ifdef FEAT_EVAL
1075 && !did_iconv
1076# endif
1077 )
1078 iconv_fd = (iconv_t)my_iconv_open(
1079 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1080# endif
1081
1082# ifdef FEAT_EVAL
1083 /*
1084 * Use the 'charconvert' expression when conversion is required
1085 * and we can't do it internally or with iconv().
1086 */
1087 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1088# ifdef USE_ICONV
1089 && iconv_fd == (iconv_t)-1
1090# endif
1091 )
1092 {
1093# ifdef USE_ICONV
1094 did_iconv = FALSE;
1095# endif
1096 /* Skip conversion when it's already done (retry for wrong
1097 * "fileformat"). */
1098 if (tmpname == NULL)
1099 {
1100 tmpname = readfile_charconvert(fname, fenc, &fd);
1101 if (tmpname == NULL)
1102 {
1103 /* Conversion failed. Try another one. */
1104 advance_fenc = TRUE;
1105 if (fd < 0)
1106 {
1107 /* Re-opening the original file failed! */
1108 EMSG(_("E202: Conversion made file unreadable!"));
1109 error = TRUE;
1110 goto failed;
1111 }
1112 goto retry;
1113 }
1114 }
1115 }
1116 else
1117# endif
1118 {
1119 if (fio_flags == 0
1120# ifdef USE_ICONV
1121 && iconv_fd == (iconv_t)-1
1122# endif
1123 )
1124 {
1125 /* Conversion wanted but we can't.
1126 * Try the next conversion in 'fileencodings' */
1127 advance_fenc = TRUE;
1128 goto retry;
1129 }
1130 }
1131 }
1132
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001133 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001134 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001135 * stdin or fixed at a specific encoding. */
1136 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001137#endif
1138
1139 if (!skip_read)
1140 {
1141 linerest = 0;
1142 filesize = 0;
1143 skip_count = lines_to_skip;
1144 read_count = lines_to_read;
1145#ifdef FEAT_MBYTE
1146 conv_restlen = 0;
1147#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001148#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001149 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1150 && curbuf->b_ffname != NULL
1151 && curbuf->b_p_udf
1152 && !filtering
1153 && !read_stdin
1154 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001155 if (read_undo_file)
1156 sha256_start(&sha_ctx);
1157#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001158#ifdef FEAT_CRYPT
1159 if (curbuf->b_cryptstate != NULL)
1160 {
1161 /* Need to free the state, but keep the key, don't want to ask for
1162 * it again. */
1163 crypt_free_state(curbuf->b_cryptstate);
1164 curbuf->b_cryptstate = NULL;
1165 }
1166#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167 }
1168
1169 while (!error && !got_int)
1170 {
1171 /*
1172 * We allocate as much space for the file as we can get, plus
1173 * space for the old line plus room for one terminating NUL.
1174 * The amount is limited by the fact that read() only can read
1175 * upto max_unsigned characters (and other things).
1176 */
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001177#if VIM_SIZEOF_INT <= 2
Bram Moolenaar071d4272004-06-13 20:20:40 +00001178 if (linerest >= 0x7ff0)
1179 {
1180 ++split;
1181 *ptr = NL; /* split line by inserting a NL */
1182 size = 1;
1183 }
1184 else
1185#endif
1186 {
1187 if (!skip_read)
1188 {
Bram Moolenaara2aa31a2014-02-23 22:52:40 +01001189#if VIM_SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001190# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191 size = SSIZE_MAX; /* use max I/O size, 52K */
1192# else
1193 size = 0x10000L; /* use buffer >= 64K */
1194# endif
1195#else
1196 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1197#endif
1198
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001199 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200 {
1201 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1202 FALSE)) != NULL)
1203 break;
1204 }
1205 if (new_buffer == NULL)
1206 {
1207 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1208 error = TRUE;
1209 break;
1210 }
1211 if (linerest) /* copy characters from the previous buffer */
1212 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1213 vim_free(buffer);
1214 buffer = new_buffer;
1215 ptr = buffer + linerest;
1216 line_start = buffer;
1217
1218#ifdef FEAT_MBYTE
1219 /* May need room to translate into.
1220 * For iconv() we don't really know the required space, use a
1221 * factor ICONV_MULT.
1222 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1223 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1224 * become up to 4 bytes, size must be multiple of 2
1225 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1226 * multiple of 2
1227 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1228 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001229 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001230# ifdef USE_ICONV
1231 if (iconv_fd != (iconv_t)-1)
1232 size = size / ICONV_MULT;
1233 else
1234# endif
1235 if (fio_flags & FIO_LATIN1)
1236 size = size / 2;
1237 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1238 size = (size * 2 / 3) & ~1;
1239 else if (fio_flags & FIO_UCS4)
1240 size = (size * 2 / 3) & ~3;
1241 else if (fio_flags == FIO_UCSBOM)
1242 size = size / ICONV_MULT; /* worst case */
1243# ifdef WIN3264
1244 else if (fio_flags & FIO_CODEPAGE)
1245 size = size / ICONV_MULT; /* also worst case */
1246# endif
1247# ifdef MACOS_X
1248 else if (fio_flags & FIO_MACROMAN)
1249 size = size / ICONV_MULT; /* also worst case */
1250# endif
1251#endif
1252
1253#ifdef FEAT_MBYTE
1254 if (conv_restlen > 0)
1255 {
1256 /* Insert unconverted bytes from previous line. */
1257 mch_memmove(ptr, conv_rest, conv_restlen);
1258 ptr += conv_restlen;
1259 size -= conv_restlen;
1260 }
1261#endif
1262
1263 if (read_buffer)
1264 {
1265 /*
1266 * Read bytes from curbuf. Used for converting text read
1267 * from stdin.
1268 */
1269 if (read_buf_lnum > from)
1270 size = 0;
1271 else
1272 {
1273 int n, ni;
1274 long tlen;
1275
1276 tlen = 0;
1277 for (;;)
1278 {
1279 p = ml_get(read_buf_lnum) + read_buf_col;
1280 n = (int)STRLEN(p);
1281 if ((int)tlen + n + 1 > size)
1282 {
1283 /* Filled up to "size", append partial line.
1284 * Change NL to NUL to reverse the effect done
1285 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001286 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001287 for (ni = 0; ni < n; ++ni)
1288 {
1289 if (p[ni] == NL)
1290 ptr[tlen++] = NUL;
1291 else
1292 ptr[tlen++] = p[ni];
1293 }
1294 read_buf_col += n;
1295 break;
1296 }
1297 else
1298 {
1299 /* Append whole line and new-line. Change NL
1300 * to NUL to reverse the effect done below. */
1301 for (ni = 0; ni < n; ++ni)
1302 {
1303 if (p[ni] == NL)
1304 ptr[tlen++] = NUL;
1305 else
1306 ptr[tlen++] = p[ni];
1307 }
1308 ptr[tlen++] = NL;
1309 read_buf_col = 0;
1310 if (++read_buf_lnum > from)
1311 {
1312 /* When the last line didn't have an
1313 * end-of-line don't add it now either. */
1314 if (!curbuf->b_p_eol)
1315 --tlen;
1316 size = tlen;
1317 break;
1318 }
1319 }
1320 }
1321 }
1322 }
1323 else
1324 {
1325 /*
1326 * Read bytes from the file.
1327 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001328 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001329 }
1330
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001331#ifdef FEAT_CRYPT
1332 /*
1333 * At start of file: Check for magic number of encryption.
1334 */
1335 if (filesize == 0 && size > 0)
1336 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1337 &filesize, newfile, sfname,
1338 &did_ask_for_key);
1339 /*
1340 * Decrypt the read bytes. This is done before checking for
1341 * EOF because the crypt layer may be buffering.
1342 */
1343 if (cryptkey != NULL && size > 0)
1344 {
1345 if (crypt_works_inplace(curbuf->b_cryptstate))
1346 {
1347 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
1348 }
1349 else
1350 {
1351 char_u *newptr = NULL;
1352 int decrypted_size;
1353
1354 decrypted_size = crypt_decode_alloc(
1355 curbuf->b_cryptstate, ptr, size, &newptr);
1356
1357 /* If the crypt layer is buffering, not producing
1358 * anything yet, need to read more. */
1359 if (size > 0 && decrypted_size == 0)
1360 continue;
1361
1362 if (linerest == 0)
1363 {
1364 /* Simple case: reuse returned buffer (may be
1365 * NULL, checked later). */
1366 new_buffer = newptr;
1367 }
1368 else
1369 {
1370 long_u new_size;
1371
1372 /* Need new buffer to add bytes carried over. */
1373 new_size = (long_u)(decrypted_size + linerest + 1);
1374 new_buffer = lalloc(new_size, FALSE);
1375 if (new_buffer == NULL)
1376 {
1377 do_outofmem_msg(new_size);
1378 error = TRUE;
1379 break;
1380 }
1381
1382 mch_memmove(new_buffer, buffer, linerest);
1383 if (newptr != NULL)
1384 mch_memmove(new_buffer + linerest, newptr,
1385 decrypted_size);
1386 }
1387
1388 if (new_buffer != NULL)
1389 {
1390 vim_free(buffer);
1391 buffer = new_buffer;
1392 new_buffer = NULL;
1393 line_start = buffer;
1394 ptr = buffer + linerest;
1395 }
1396 size = decrypted_size;
1397 }
1398 }
1399#endif
1400
Bram Moolenaar071d4272004-06-13 20:20:40 +00001401 if (size <= 0)
1402 {
1403 if (size < 0) /* read error */
1404 error = TRUE;
1405#ifdef FEAT_MBYTE
1406 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001407 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001408 /*
1409 * Reached end-of-file but some trailing bytes could
1410 * not be converted. Truncated file?
1411 */
1412
1413 /* When we did a conversion report an error. */
1414 if (fio_flags != 0
1415# ifdef USE_ICONV
1416 || iconv_fd != (iconv_t)-1
1417# endif
1418 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001419 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001420 if (can_retry)
1421 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001422 if (conv_error == 0)
1423 conv_error = curbuf->b_ml.ml_line_count
1424 - linecnt + 1;
1425 }
1426 /* Remember the first linenr with an illegal byte */
1427 else if (illegal_byte == 0)
1428 illegal_byte = curbuf->b_ml.ml_line_count
1429 - linecnt + 1;
1430 if (bad_char_behavior == BAD_DROP)
1431 {
1432 *(ptr - conv_restlen) = NUL;
1433 conv_restlen = 0;
1434 }
1435 else
1436 {
1437 /* Replace the trailing bytes with the replacement
1438 * character if we were converting; if we weren't,
1439 * leave the UTF8 checking code to do it, as it
1440 * works slightly differently. */
1441 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1442# ifdef USE_ICONV
1443 || iconv_fd != (iconv_t)-1
1444# endif
1445 ))
1446 {
1447 while (conv_restlen > 0)
1448 {
1449 *(--ptr) = bad_char_behavior;
1450 --conv_restlen;
1451 }
1452 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001453 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001454# ifdef USE_ICONV
1455 if (iconv_fd != (iconv_t)-1)
1456 {
1457 iconv_close(iconv_fd);
1458 iconv_fd = (iconv_t)-1;
1459 }
1460# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001461 }
1462 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001463#endif
1464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001465 }
1466 skip_read = FALSE;
1467
1468#ifdef FEAT_MBYTE
1469 /*
1470 * At start of file (or after crypt magic number): Check for BOM.
1471 * Also check for a BOM for other Unicode encodings, but not after
1472 * converting with 'charconvert' or when a BOM has already been
1473 * found.
1474 */
1475 if ((filesize == 0
1476# ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001477 || (cryptkey != NULL
1478 && filesize == crypt_get_header_len(
1479 crypt_get_method_nr(curbuf)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001480# endif
1481 )
1482 && (fio_flags == FIO_UCSBOM
1483 || (!curbuf->b_p_bomb
1484 && tmpname == NULL
1485 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1486 {
1487 char_u *ccname;
1488 int blen;
1489
1490 /* no BOM detection in a short file or in binary mode */
1491 if (size < 2 || curbuf->b_p_bin)
1492 ccname = NULL;
1493 else
1494 ccname = check_for_bom(ptr, size, &blen,
1495 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1496 if (ccname != NULL)
1497 {
1498 /* Remove BOM from the text */
1499 filesize += blen;
1500 size -= blen;
1501 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001502 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001503 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001504 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001505 curbuf->b_start_bomb = TRUE;
1506 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001507 }
1508
1509 if (fio_flags == FIO_UCSBOM)
1510 {
1511 if (ccname == NULL)
1512 {
1513 /* No BOM detected: retry with next encoding. */
1514 advance_fenc = TRUE;
1515 }
1516 else
1517 {
1518 /* BOM detected: set "fenc" and jump back */
1519 if (fenc_alloced)
1520 vim_free(fenc);
1521 fenc = ccname;
1522 fenc_alloced = FALSE;
1523 }
1524 /* retry reading without getting new bytes or rewinding */
1525 skip_read = TRUE;
1526 goto retry;
1527 }
1528 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001529
1530 /* Include not converted bytes. */
1531 ptr -= conv_restlen;
1532 size += conv_restlen;
1533 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534#endif
1535 /*
1536 * Break here for a read error or end-of-file.
1537 */
1538 if (size <= 0)
1539 break;
1540
1541#ifdef FEAT_MBYTE
1542
Bram Moolenaar071d4272004-06-13 20:20:40 +00001543# ifdef USE_ICONV
1544 if (iconv_fd != (iconv_t)-1)
1545 {
1546 /*
1547 * Attempt conversion of the read bytes to 'encoding' using
1548 * iconv().
1549 */
1550 const char *fromp;
1551 char *top;
1552 size_t from_size;
1553 size_t to_size;
1554
1555 fromp = (char *)ptr;
1556 from_size = size;
1557 ptr += size;
1558 top = (char *)ptr;
1559 to_size = real_size - size;
1560
1561 /*
1562 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001563 * another conversion. Except for when there is no
1564 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001566 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1567 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001568 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1569 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001570 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001571 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001572 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001573 if (conv_error == 0)
1574 conv_error = readfile_linenr(linecnt,
1575 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001576
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001577 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001578 ++fromp;
1579 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001580 if (bad_char_behavior == BAD_KEEP)
1581 {
1582 *top++ = *(fromp - 1);
1583 --to_size;
1584 }
1585 else if (bad_char_behavior != BAD_DROP)
1586 {
1587 *top++ = bad_char_behavior;
1588 --to_size;
1589 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001590 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001591
1592 if (from_size > 0)
1593 {
1594 /* Some remaining characters, keep them for the next
1595 * round. */
1596 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1597 conv_restlen = (int)from_size;
1598 }
1599
1600 /* move the linerest to before the converted characters */
1601 line_start = ptr - linerest;
1602 mch_memmove(line_start, buffer, (size_t)linerest);
1603 size = (long)((char_u *)top - ptr);
1604 }
1605# endif
1606
1607# ifdef WIN3264
1608 if (fio_flags & FIO_CODEPAGE)
1609 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001610 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001611 WCHAR ucs2buf[3];
1612 int ucs2len;
1613 int codepage = FIO_GET_CP(fio_flags);
1614 int bytelen;
1615 int found_bad;
1616 char replstr[2];
1617
Bram Moolenaar071d4272004-06-13 20:20:40 +00001618 /*
1619 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001620 * a codepage, using standard MS-Windows functions. This
1621 * requires two steps:
1622 * 1. convert from 'fileencoding' to ucs-2
1623 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001624 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001625 * Because there may be illegal bytes AND an incomplete byte
1626 * sequence at the end, we may have to do the conversion one
1627 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001629
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001630 /* Replacement string for WideCharToMultiByte(). */
1631 if (bad_char_behavior > 0)
1632 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001633 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001634 replstr[0] = '?';
1635 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001636
1637 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001638 * Move the bytes to the end of the buffer, so that we have
1639 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001640 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001641 src = ptr + real_size - size;
1642 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001643
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001644 /*
1645 * Do the conversion.
1646 */
1647 dst = ptr;
1648 size = size;
1649 while (size > 0)
1650 {
1651 found_bad = FALSE;
1652
1653# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1654 if (codepage == CP_UTF8)
1655 {
1656 /* Handle CP_UTF8 input ourselves to be able to handle
1657 * trailing bytes properly.
1658 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001659 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001660 if (bytelen > size)
1661 {
1662 /* Only got some bytes of a character. Normally
1663 * it's put in "conv_rest", but if it's too long
1664 * deal with it as if they were illegal bytes. */
1665 if (bytelen <= CONV_RESTLEN)
1666 break;
1667
1668 /* weird overlong byte sequence */
1669 bytelen = size;
1670 found_bad = TRUE;
1671 }
1672 else
1673 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001674 int u8c = utf_ptr2char(src);
1675
Bram Moolenaar86e01082005-12-29 22:45:34 +00001676 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001677 found_bad = TRUE;
1678 ucs2buf[0] = u8c;
1679 ucs2len = 1;
1680 }
1681 }
1682 else
1683# endif
1684 {
1685 /* We don't know how long the byte sequence is, try
1686 * from one to three bytes. */
1687 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1688 ++bytelen)
1689 {
1690 ucs2len = MultiByteToWideChar(codepage,
1691 MB_ERR_INVALID_CHARS,
1692 (LPCSTR)src, bytelen,
1693 ucs2buf, 3);
1694 if (ucs2len > 0)
1695 break;
1696 }
1697 if (ucs2len == 0)
1698 {
1699 /* If we have only one byte then it's probably an
1700 * incomplete byte sequence. Otherwise discard
1701 * one byte as a bad character. */
1702 if (size == 1)
1703 break;
1704 found_bad = TRUE;
1705 bytelen = 1;
1706 }
1707 }
1708
1709 if (!found_bad)
1710 {
1711 int i;
1712
1713 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1714 if (enc_utf8)
1715 {
1716 /* From UCS-2 to UTF-8. Cannot fail. */
1717 for (i = 0; i < ucs2len; ++i)
1718 dst += utf_char2bytes(ucs2buf[i], dst);
1719 }
1720 else
1721 {
1722 BOOL bad = FALSE;
1723 int dstlen;
1724
1725 /* From UCS-2 to "enc_codepage". If the
1726 * conversion uses the default character "?",
1727 * the data doesn't fit in this encoding. */
1728 dstlen = WideCharToMultiByte(enc_codepage, 0,
1729 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001730 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001731 replstr, &bad);
1732 if (bad)
1733 found_bad = TRUE;
1734 else
1735 dst += dstlen;
1736 }
1737 }
1738
1739 if (found_bad)
1740 {
1741 /* Deal with bytes we can't convert. */
1742 if (can_retry)
1743 goto rewind_retry;
1744 if (conv_error == 0)
1745 conv_error = readfile_linenr(linecnt, ptr, dst);
1746 if (bad_char_behavior != BAD_DROP)
1747 {
1748 if (bad_char_behavior == BAD_KEEP)
1749 {
1750 mch_memmove(dst, src, bytelen);
1751 dst += bytelen;
1752 }
1753 else
1754 *dst++ = bad_char_behavior;
1755 }
1756 }
1757
1758 src += bytelen;
1759 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001761
1762 if (size > 0)
1763 {
1764 /* An incomplete byte sequence remaining. */
1765 mch_memmove(conv_rest, src, size);
1766 conv_restlen = size;
1767 }
1768
1769 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001770 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001771 }
1772 else
1773# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001774# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001775 if (fio_flags & FIO_MACROMAN)
1776 {
1777 /*
1778 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001779 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001780 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001781 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001782 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001783 }
1784 else
1785# endif
1786 if (fio_flags != 0)
1787 {
1788 int u8c;
1789 char_u *dest;
1790 char_u *tail = NULL;
1791
1792 /*
1793 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1794 * "enc_utf8" not set: Convert Unicode to Latin1.
1795 * Go from end to start through the buffer, because the number
1796 * of bytes may increase.
1797 * "dest" points to after where the UTF-8 bytes go, "p" points
1798 * to after the next character to convert.
1799 */
1800 dest = ptr + real_size;
1801 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1802 {
1803 p = ptr + size;
1804 if (fio_flags == FIO_UTF8)
1805 {
1806 /* Check for a trailing incomplete UTF-8 sequence */
1807 tail = ptr + size - 1;
1808 while (tail > ptr && (*tail & 0xc0) == 0x80)
1809 --tail;
1810 if (tail + utf_byte2len(*tail) <= ptr + size)
1811 tail = NULL;
1812 else
1813 p = tail;
1814 }
1815 }
1816 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1817 {
1818 /* Check for a trailing byte */
1819 p = ptr + (size & ~1);
1820 if (size & 1)
1821 tail = p;
1822 if ((fio_flags & FIO_UTF16) && p > ptr)
1823 {
1824 /* Check for a trailing leading word */
1825 if (fio_flags & FIO_ENDIAN_L)
1826 {
1827 u8c = (*--p << 8);
1828 u8c += *--p;
1829 }
1830 else
1831 {
1832 u8c = *--p;
1833 u8c += (*--p << 8);
1834 }
1835 if (u8c >= 0xd800 && u8c <= 0xdbff)
1836 tail = p;
1837 else
1838 p += 2;
1839 }
1840 }
1841 else /* FIO_UCS4 */
1842 {
1843 /* Check for trailing 1, 2 or 3 bytes */
1844 p = ptr + (size & ~3);
1845 if (size & 3)
1846 tail = p;
1847 }
1848
1849 /* If there is a trailing incomplete sequence move it to
1850 * conv_rest[]. */
1851 if (tail != NULL)
1852 {
1853 conv_restlen = (int)((ptr + size) - tail);
1854 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1855 size -= conv_restlen;
1856 }
1857
1858
1859 while (p > ptr)
1860 {
1861 if (fio_flags & FIO_LATIN1)
1862 u8c = *--p;
1863 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1864 {
1865 if (fio_flags & FIO_ENDIAN_L)
1866 {
1867 u8c = (*--p << 8);
1868 u8c += *--p;
1869 }
1870 else
1871 {
1872 u8c = *--p;
1873 u8c += (*--p << 8);
1874 }
1875 if ((fio_flags & FIO_UTF16)
1876 && u8c >= 0xdc00 && u8c <= 0xdfff)
1877 {
1878 int u16c;
1879
1880 if (p == ptr)
1881 {
1882 /* Missing leading word. */
1883 if (can_retry)
1884 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001885 if (conv_error == 0)
1886 conv_error = readfile_linenr(linecnt,
1887 ptr, p);
1888 if (bad_char_behavior == BAD_DROP)
1889 continue;
1890 if (bad_char_behavior != BAD_KEEP)
1891 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001892 }
1893
1894 /* found second word of double-word, get the first
1895 * word and compute the resulting character */
1896 if (fio_flags & FIO_ENDIAN_L)
1897 {
1898 u16c = (*--p << 8);
1899 u16c += *--p;
1900 }
1901 else
1902 {
1903 u16c = *--p;
1904 u16c += (*--p << 8);
1905 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001906 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1907 + (u8c & 0x3ff);
1908
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909 /* Check if the word is indeed a leading word. */
1910 if (u16c < 0xd800 || u16c > 0xdbff)
1911 {
1912 if (can_retry)
1913 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001914 if (conv_error == 0)
1915 conv_error = readfile_linenr(linecnt,
1916 ptr, p);
1917 if (bad_char_behavior == BAD_DROP)
1918 continue;
1919 if (bad_char_behavior != BAD_KEEP)
1920 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001922 }
1923 }
1924 else if (fio_flags & FIO_UCS4)
1925 {
1926 if (fio_flags & FIO_ENDIAN_L)
1927 {
1928 u8c = (*--p << 24);
1929 u8c += (*--p << 16);
1930 u8c += (*--p << 8);
1931 u8c += *--p;
1932 }
1933 else /* big endian */
1934 {
1935 u8c = *--p;
1936 u8c += (*--p << 8);
1937 u8c += (*--p << 16);
1938 u8c += (*--p << 24);
1939 }
1940 }
1941 else /* UTF-8 */
1942 {
1943 if (*--p < 0x80)
1944 u8c = *p;
1945 else
1946 {
1947 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001948 p -= len;
1949 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001950 if (len == 0)
1951 {
1952 /* Not a valid UTF-8 character, retry with
1953 * another fenc when possible, otherwise just
1954 * report the error. */
1955 if (can_retry)
1956 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001957 if (conv_error == 0)
1958 conv_error = readfile_linenr(linecnt,
1959 ptr, p);
1960 if (bad_char_behavior == BAD_DROP)
1961 continue;
1962 if (bad_char_behavior != BAD_KEEP)
1963 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001964 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001965 }
1966 }
1967 if (enc_utf8) /* produce UTF-8 */
1968 {
1969 dest -= utf_char2len(u8c);
1970 (void)utf_char2bytes(u8c, dest);
1971 }
1972 else /* produce Latin1 */
1973 {
1974 --dest;
1975 if (u8c >= 0x100)
1976 {
1977 /* character doesn't fit in latin1, retry with
1978 * another fenc when possible, otherwise just
1979 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001980 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001981 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001982 if (conv_error == 0)
1983 conv_error = readfile_linenr(linecnt, ptr, p);
1984 if (bad_char_behavior == BAD_DROP)
1985 ++dest;
1986 else if (bad_char_behavior == BAD_KEEP)
1987 *dest = u8c;
1988 else if (eap != NULL && eap->bad_char != 0)
1989 *dest = bad_char_behavior;
1990 else
1991 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 }
1993 else
1994 *dest = u8c;
1995 }
1996 }
1997
1998 /* move the linerest to before the converted characters */
1999 line_start = dest - linerest;
2000 mch_memmove(line_start, buffer, (size_t)linerest);
2001 size = (long)((ptr + real_size) - dest);
2002 ptr = dest;
2003 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002004 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002006 int incomplete_tail = FALSE;
2007
2008 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2009 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002011 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002012 int l;
2013
2014 if (todo <= 0)
2015 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 if (*p >= 0x80)
2017 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002018 /* A length of 1 means it's an illegal byte. Accept
2019 * an incomplete character at the end though, the next
2020 * read() will get the next bytes, we'll check it
2021 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002022 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002023 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002024 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002025 /* Avoid retrying with a different encoding when
2026 * a truncated file is more likely, or attempting
2027 * to read the rest of an incomplete sequence when
2028 * we have already done so. */
2029 if (p > ptr || filesize > 0)
2030 incomplete_tail = TRUE;
2031 /* Incomplete byte sequence, move it to conv_rest[]
2032 * and try to read the rest of it, unless we've
2033 * already done so. */
2034 if (p > ptr)
2035 {
2036 conv_restlen = todo;
2037 mch_memmove(conv_rest, p, conv_restlen);
2038 size -= conv_restlen;
2039 break;
2040 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002041 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002042 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002043 {
2044 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002045 * do that, unless at EOF where a truncated
2046 * file is more likely than a conversion error. */
2047 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002048 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002049# ifdef USE_ICONV
2050 /* When we did a conversion report an error. */
2051 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2052 conv_error = readfile_linenr(linecnt, ptr, p);
2053# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002054 /* Remember the first linenr with an illegal byte */
2055 if (conv_error == 0 && illegal_byte == 0)
2056 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002057
2058 /* Drop, keep or replace the bad byte. */
2059 if (bad_char_behavior == BAD_DROP)
2060 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002061 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002062 --p;
2063 --size;
2064 }
2065 else if (bad_char_behavior != BAD_KEEP)
2066 *p = bad_char_behavior;
2067 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002068 else
2069 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002070 }
2071 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002072 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 {
2074 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002075rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002076 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002077# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002078 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2079 /* iconv() failed, try 'charconvert' */
2080 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002081 else
2082# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002083 /* use next item from 'fileencodings' */
2084 advance_fenc = TRUE;
2085 file_rewind = TRUE;
2086 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002087 }
2088 }
2089#endif
2090
2091 /* count the number of characters (after conversion!) */
2092 filesize += size;
2093
2094 /*
2095 * when reading the first part of a file: guess EOL type
2096 */
2097 if (fileformat == EOL_UNKNOWN)
2098 {
2099 /* First try finding a NL, for Dos and Unix */
2100 if (try_dos || try_unix)
2101 {
2102 for (p = ptr; p < ptr + size; ++p)
2103 {
2104 if (*p == NL)
2105 {
2106 if (!try_unix
2107 || (try_dos && p > ptr && p[-1] == CAR))
2108 fileformat = EOL_DOS;
2109 else
2110 fileformat = EOL_UNIX;
2111 break;
2112 }
2113 }
2114
2115 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2116 if (fileformat == EOL_UNIX && try_mac)
2117 {
2118 /* Need to reset the counters when retrying fenc. */
2119 try_mac = 1;
2120 try_unix = 1;
2121 for (; p >= ptr && *p != CAR; p--)
2122 ;
2123 if (p >= ptr)
2124 {
2125 for (p = ptr; p < ptr + size; ++p)
2126 {
2127 if (*p == NL)
2128 try_unix++;
2129 else if (*p == CAR)
2130 try_mac++;
2131 }
2132 if (try_mac > try_unix)
2133 fileformat = EOL_MAC;
2134 }
2135 }
2136 }
2137
2138 /* No NL found: may use Mac format */
2139 if (fileformat == EOL_UNKNOWN && try_mac)
2140 fileformat = EOL_MAC;
2141
2142 /* Still nothing found? Use first format in 'ffs' */
2143 if (fileformat == EOL_UNKNOWN)
2144 fileformat = default_fileformat();
2145
2146 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002147 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002148 set_fileformat(fileformat, OPT_LOCAL);
2149 }
2150 }
2151
2152 /*
2153 * This loop is executed once for every character read.
2154 * Keep it fast!
2155 */
2156 if (fileformat == EOL_MAC)
2157 {
2158 --ptr;
2159 while (++ptr, --size >= 0)
2160 {
2161 /* catch most common case first */
2162 if ((c = *ptr) != NUL && c != CAR && c != NL)
2163 continue;
2164 if (c == NUL)
2165 *ptr = NL; /* NULs are replaced by newlines! */
2166 else if (c == NL)
2167 *ptr = CAR; /* NLs are replaced by CRs! */
2168 else
2169 {
2170 if (skip_count == 0)
2171 {
2172 *ptr = NUL; /* end of line */
2173 len = (colnr_T) (ptr - line_start + 1);
2174 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2175 {
2176 error = TRUE;
2177 break;
2178 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002179#ifdef FEAT_PERSISTENT_UNDO
2180 if (read_undo_file)
2181 sha256_update(&sha_ctx, line_start, len);
2182#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002183 ++lnum;
2184 if (--read_count == 0)
2185 {
2186 error = TRUE; /* break loop */
2187 line_start = ptr; /* nothing left to write */
2188 break;
2189 }
2190 }
2191 else
2192 --skip_count;
2193 line_start = ptr + 1;
2194 }
2195 }
2196 }
2197 else
2198 {
2199 --ptr;
2200 while (++ptr, --size >= 0)
2201 {
2202 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2203 continue;
2204 if (c == NUL)
2205 *ptr = NL; /* NULs are replaced by newlines! */
2206 else
2207 {
2208 if (skip_count == 0)
2209 {
2210 *ptr = NUL; /* end of line */
2211 len = (colnr_T)(ptr - line_start + 1);
2212 if (fileformat == EOL_DOS)
2213 {
2214 if (ptr[-1] == CAR) /* remove CR */
2215 {
2216 ptr[-1] = NUL;
2217 --len;
2218 }
2219 /*
2220 * Reading in Dos format, but no CR-LF found!
2221 * When 'fileformats' includes "unix", delete all
2222 * the lines read so far and start all over again.
2223 * Otherwise give an error message later.
2224 */
2225 else if (ff_error != EOL_DOS)
2226 {
2227 if ( try_unix
2228 && !read_stdin
2229 && (read_buffer
2230 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2231 {
2232 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002233 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002234 set_fileformat(EOL_UNIX, OPT_LOCAL);
2235 file_rewind = TRUE;
2236 keep_fileformat = TRUE;
2237 goto retry;
2238 }
2239 ff_error = EOL_DOS;
2240 }
2241 }
2242 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2243 {
2244 error = TRUE;
2245 break;
2246 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002247#ifdef FEAT_PERSISTENT_UNDO
2248 if (read_undo_file)
2249 sha256_update(&sha_ctx, line_start, len);
2250#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002251 ++lnum;
2252 if (--read_count == 0)
2253 {
2254 error = TRUE; /* break loop */
2255 line_start = ptr; /* nothing left to write */
2256 break;
2257 }
2258 }
2259 else
2260 --skip_count;
2261 line_start = ptr + 1;
2262 }
2263 }
2264 }
2265 linerest = (long)(ptr - line_start);
2266 ui_breakcheck();
2267 }
2268
2269failed:
2270 /* not an error, max. number of lines reached */
2271 if (error && read_count == 0)
2272 error = FALSE;
2273
2274 /*
2275 * If we get EOF in the middle of a line, note the fact and
2276 * complete the line ourselves.
2277 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2278 */
2279 if (!error
2280 && !got_int
2281 && linerest != 0
2282 && !(!curbuf->b_p_bin
2283 && fileformat == EOL_DOS
2284 && *line_start == Ctrl_Z
2285 && ptr == line_start + 1))
2286 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002287 /* remember for when writing */
2288 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002289 curbuf->b_p_eol = FALSE;
2290 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002291 len = (colnr_T)(ptr - line_start + 1);
2292 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002293 error = TRUE;
2294 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002295 {
2296#ifdef FEAT_PERSISTENT_UNDO
2297 if (read_undo_file)
2298 sha256_update(&sha_ctx, line_start, len);
2299#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002301 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302 }
2303
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002304 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002305 save_file_ff(curbuf); /* remember the current file format */
2306
2307#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002308 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002309 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002310 crypt_free_state(curbuf->b_cryptstate);
2311 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002312 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002313 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2314 crypt_free_key(cryptkey);
2315 /* Don't set cryptkey to NULL, it's used below as a flag that
2316 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002317#endif
2318
2319#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002320 /* If editing a new file: set 'fenc' for the current buffer.
2321 * Also for ":read ++edit file". */
2322 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002323 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002324 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325 if (fenc_alloced)
2326 vim_free(fenc);
2327# ifdef USE_ICONV
2328 if (iconv_fd != (iconv_t)-1)
2329 {
2330 iconv_close(iconv_fd);
2331 iconv_fd = (iconv_t)-1;
2332 }
2333# endif
2334#endif
2335
2336 if (!read_buffer && !read_stdin)
2337 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002338#ifdef HAVE_FD_CLOEXEC
2339 else
2340 {
2341 int fdflags = fcntl(fd, F_GETFD);
2342 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2343 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2344 }
2345#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002346 vim_free(buffer);
2347
2348#ifdef HAVE_DUP
2349 if (read_stdin)
2350 {
2351 /* Use stderr for stdin, makes shell commands work. */
2352 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002353 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002354 }
2355#endif
2356
2357#ifdef FEAT_MBYTE
2358 if (tmpname != NULL)
2359 {
2360 mch_remove(tmpname); /* delete converted file */
2361 vim_free(tmpname);
2362 }
2363#endif
2364 --no_wait_return; /* may wait for return now */
2365
2366 /*
2367 * In recovery mode everything but autocommands is skipped.
2368 */
2369 if (!recoverymode)
2370 {
2371 /* need to delete the last line, which comes from the empty buffer */
2372 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2373 {
2374#ifdef FEAT_NETBEANS_INTG
2375 netbeansFireChanges = 0;
2376#endif
2377 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2378#ifdef FEAT_NETBEANS_INTG
2379 netbeansFireChanges = 1;
2380#endif
2381 --linecnt;
2382 }
2383 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2384 if (filesize == 0)
2385 linecnt = 0;
2386 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002387 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002388 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002389#ifdef FEAT_DIFF
2390 /* After reading the text into the buffer the diff info needs to
2391 * be updated. */
2392 diff_invalidate(curbuf);
2393#endif
2394#ifdef FEAT_FOLDING
2395 /* All folds in the window are invalid now. Mark them for update
2396 * before triggering autocommands. */
2397 foldUpdateAll(curwin);
2398#endif
2399 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002400 else if (linecnt) /* appended at least one line */
2401 appended_lines_mark(from, linecnt);
2402
Bram Moolenaar071d4272004-06-13 20:20:40 +00002403#ifndef ALWAYS_USE_GUI
2404 /*
2405 * If we were reading from the same terminal as where messages go,
2406 * the screen will have been messed up.
2407 * Switch on raw mode now and clear the screen.
2408 */
2409 if (read_stdin)
2410 {
2411 settmode(TMODE_RAW); /* set to raw mode */
2412 starttermcap();
2413 screenclear();
2414 }
2415#endif
2416
2417 if (got_int)
2418 {
2419 if (!(flags & READ_DUMMY))
2420 {
2421 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2422 if (newfile)
2423 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2424 }
2425 msg_scroll = msg_save;
2426#ifdef FEAT_VIMINFO
2427 check_marks_read();
2428#endif
2429 return OK; /* an interrupt isn't really an error */
2430 }
2431
2432 if (!filtering && !(flags & READ_DUMMY))
2433 {
2434 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2435 c = FALSE;
2436
2437#ifdef UNIX
2438# ifdef S_ISFIFO
2439 if (S_ISFIFO(perm)) /* fifo or socket */
2440 {
2441 STRCAT(IObuff, _("[fifo/socket]"));
2442 c = TRUE;
2443 }
2444# else
2445# ifdef S_IFIFO
2446 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2447 {
2448 STRCAT(IObuff, _("[fifo]"));
2449 c = TRUE;
2450 }
2451# endif
2452# ifdef S_IFSOCK
2453 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2454 {
2455 STRCAT(IObuff, _("[socket]"));
2456 c = TRUE;
2457 }
2458# endif
2459# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002460# ifdef OPEN_CHR_FILES
2461 if (S_ISCHR(perm)) /* or character special */
2462 {
2463 STRCAT(IObuff, _("[character special]"));
2464 c = TRUE;
2465 }
2466# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467#endif
2468 if (curbuf->b_p_ro)
2469 {
2470 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2471 c = TRUE;
2472 }
2473 if (read_no_eol_lnum)
2474 {
2475 msg_add_eol();
2476 c = TRUE;
2477 }
2478 if (ff_error == EOL_DOS)
2479 {
2480 STRCAT(IObuff, _("[CR missing]"));
2481 c = TRUE;
2482 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002483 if (split)
2484 {
2485 STRCAT(IObuff, _("[long lines split]"));
2486 c = TRUE;
2487 }
2488#ifdef FEAT_MBYTE
2489 if (notconverted)
2490 {
2491 STRCAT(IObuff, _("[NOT converted]"));
2492 c = TRUE;
2493 }
2494 else if (converted)
2495 {
2496 STRCAT(IObuff, _("[converted]"));
2497 c = TRUE;
2498 }
2499#endif
2500#ifdef FEAT_CRYPT
2501 if (cryptkey != NULL)
2502 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002503 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 c = TRUE;
2505 }
2506#endif
2507#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002508 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002509 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002510 sprintf((char *)IObuff + STRLEN(IObuff),
2511 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 c = TRUE;
2513 }
2514 else if (illegal_byte > 0)
2515 {
2516 sprintf((char *)IObuff + STRLEN(IObuff),
2517 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2518 c = TRUE;
2519 }
2520 else
2521#endif
2522 if (error)
2523 {
2524 STRCAT(IObuff, _("[READ ERRORS]"));
2525 c = TRUE;
2526 }
2527 if (msg_add_fileformat(fileformat))
2528 c = TRUE;
2529#ifdef FEAT_CRYPT
2530 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002531 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002532 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002533 else
2534#endif
2535 msg_add_lines(c, (long)linecnt, filesize);
2536
2537 vim_free(keep_msg);
2538 keep_msg = NULL;
2539 msg_scrolled_ign = TRUE;
2540#ifdef ALWAYS_USE_GUI
2541 /* Don't show the message when reading stdin, it would end up in a
2542 * message box (which might be shown when exiting!) */
2543 if (read_stdin || read_buffer)
2544 p = msg_may_trunc(FALSE, IObuff);
2545 else
2546#endif
2547 p = msg_trunc_attr(IObuff, FALSE, 0);
2548 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002549 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 /* Need to repeat the message after redrawing when:
2551 * - When reading from stdin (the screen will be cleared next).
2552 * - When restart_edit is set (otherwise there will be a delay
2553 * before redrawing).
2554 * - When the screen was scrolled but there is no wait-return
2555 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002556 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002557 msg_scrolled_ign = FALSE;
2558 }
2559
2560 /* with errors writing the file requires ":w!" */
2561 if (newfile && (error
2562#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002563 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002564 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002565#endif
2566 ))
2567 curbuf->b_p_ro = TRUE;
2568
2569 u_clearline(); /* cannot use "U" command after adding lines */
2570
2571 /*
2572 * In Ex mode: cursor at last new line.
2573 * Otherwise: cursor at first new line.
2574 */
2575 if (exmode_active)
2576 curwin->w_cursor.lnum = from + linecnt;
2577 else
2578 curwin->w_cursor.lnum = from + 1;
2579 check_cursor_lnum();
2580 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2581
2582 /*
2583 * Set '[ and '] marks to the newly read lines.
2584 */
2585 curbuf->b_op_start.lnum = from + 1;
2586 curbuf->b_op_start.col = 0;
2587 curbuf->b_op_end.lnum = from + linecnt;
2588 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002589
2590#ifdef WIN32
2591 /*
2592 * Work around a weird problem: When a file has two links (only
2593 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002594 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002595 * It's correct again after reading the file, thus reset the timestamp
2596 * here.
2597 */
2598 if (newfile && !read_stdin && !read_buffer
2599 && mch_stat((char *)fname, &st) >= 0)
2600 {
2601 buf_store_time(curbuf, &st, fname);
2602 curbuf->b_mtime_read = curbuf->b_mtime;
2603 }
2604#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605 }
2606 msg_scroll = msg_save;
2607
2608#ifdef FEAT_VIMINFO
2609 /*
2610 * Get the marks before executing autocommands, so they can be used there.
2611 */
2612 check_marks_read();
2613#endif
2614
Bram Moolenaar071d4272004-06-13 20:20:40 +00002615 /*
2616 * Trick: We remember if the last line of the read didn't have
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002617 * an eol even when 'binary' is off, for when writing it again with
2618 * 'binary' on. This is required for
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2620 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002621 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002623 /* When reloading a buffer put the cursor at the first line that is
2624 * different. */
2625 if (flags & READ_KEEP_UNDO)
2626 u_find_first_changed();
2627
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002628#ifdef FEAT_PERSISTENT_UNDO
2629 /*
2630 * When opening a new file locate undo info and read it.
2631 */
2632 if (read_undo_file)
2633 {
2634 char_u hash[UNDO_HASH_SIZE];
2635
2636 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002637 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002638 }
2639#endif
2640
Bram Moolenaardf177f62005-02-22 08:39:57 +00002641#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 if (!read_stdin && !read_buffer)
2643 {
2644 int m = msg_scroll;
2645 int n = msg_scrolled;
2646
2647 /* Save the fileformat now, otherwise the buffer will be considered
2648 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002649 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002650 save_file_ff(curbuf);
2651
2652 /*
2653 * The output from the autocommands should not overwrite anything and
2654 * should not be overwritten: Set msg_scroll, restore its value if no
2655 * output was done.
2656 */
2657 msg_scroll = TRUE;
2658 if (filtering)
2659 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2660 FALSE, curbuf, eap);
2661 else if (newfile)
2662 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2663 FALSE, curbuf, eap);
2664 else
2665 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2666 FALSE, NULL, eap);
2667 if (msg_scrolled == n)
2668 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002669# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002670 if (aborting()) /* autocmds may abort script processing */
2671 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002672# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002673 }
2674#endif
2675
2676 if (recoverymode && error)
2677 return FAIL;
2678 return OK;
2679}
2680
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002681#ifdef OPEN_CHR_FILES
2682/*
2683 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2684 * which is the name of files used for process substitution output by
2685 * some shells on some operating systems, e.g., bash on SunOS.
2686 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2687 */
2688 static int
2689is_dev_fd_file(fname)
2690 char_u *fname;
2691{
2692 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2693 && VIM_ISDIGIT(fname[8])
2694 && *skipdigits(fname + 9) == NUL
2695 && (fname[9] != NUL
2696 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2697}
2698#endif
2699
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002700#ifdef FEAT_MBYTE
2701
2702/*
2703 * From the current line count and characters read after that, estimate the
2704 * line number where we are now.
2705 * Used for error messages that include a line number.
2706 */
2707 static linenr_T
2708readfile_linenr(linecnt, p, endp)
2709 linenr_T linecnt; /* line count before reading more bytes */
2710 char_u *p; /* start of more bytes read */
2711 char_u *endp; /* end of more bytes read */
2712{
2713 char_u *s;
2714 linenr_T lnum;
2715
2716 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2717 for (s = p; s < endp; ++s)
2718 if (*s == '\n')
2719 ++lnum;
2720 return lnum;
2721}
2722#endif
2723
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002725 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2726 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002727 * Returns OK or FAIL.
2728 */
2729 int
2730prep_exarg(eap, buf)
2731 exarg_T *eap;
2732 buf_T *buf;
2733{
2734 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2735#ifdef FEAT_MBYTE
2736 + STRLEN(buf->b_p_fenc)
2737#endif
2738 + 15));
2739 if (eap->cmd == NULL)
2740 return FAIL;
2741
2742#ifdef FEAT_MBYTE
2743 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2744 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002745 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746#else
2747 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2748#endif
2749 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002750
2751 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002752 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002753 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002754 return OK;
2755}
2756
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002757/*
2758 * Set default or forced 'fileformat' and 'binary'.
2759 */
2760 void
2761set_file_options(set_options, eap)
2762 int set_options;
2763 exarg_T *eap;
2764{
2765 /* set default 'fileformat' */
2766 if (set_options)
2767 {
2768 if (eap != NULL && eap->force_ff != 0)
2769 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2770 else if (*p_ffs != NUL)
2771 set_fileformat(default_fileformat(), OPT_LOCAL);
2772 }
2773
2774 /* set or reset 'binary' */
2775 if (eap != NULL && eap->force_bin != 0)
2776 {
2777 int oldval = curbuf->b_p_bin;
2778
2779 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2780 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2781 }
2782}
2783
2784#if defined(FEAT_MBYTE) || defined(PROTO)
2785/*
2786 * Set forced 'fileencoding'.
2787 */
2788 void
2789set_forced_fenc(eap)
2790 exarg_T *eap;
2791{
2792 if (eap->force_enc != 0)
2793 {
2794 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2795
2796 if (fenc != NULL)
2797 set_string_option_direct((char_u *)"fenc", -1,
2798 fenc, OPT_FREE|OPT_LOCAL, 0);
2799 vim_free(fenc);
2800 }
2801}
2802
Bram Moolenaar071d4272004-06-13 20:20:40 +00002803/*
2804 * Find next fileencoding to use from 'fileencodings'.
2805 * "pp" points to fenc_next. It's advanced to the next item.
2806 * When there are no more items, an empty string is returned and *pp is set to
2807 * NULL.
2808 * When *pp is not set to NULL, the result is in allocated memory.
2809 */
2810 static char_u *
2811next_fenc(pp)
2812 char_u **pp;
2813{
2814 char_u *p;
2815 char_u *r;
2816
2817 if (**pp == NUL)
2818 {
2819 *pp = NULL;
2820 return (char_u *)"";
2821 }
2822 p = vim_strchr(*pp, ',');
2823 if (p == NULL)
2824 {
2825 r = enc_canonize(*pp);
2826 *pp += STRLEN(*pp);
2827 }
2828 else
2829 {
2830 r = vim_strnsave(*pp, (int)(p - *pp));
2831 *pp = p + 1;
2832 if (r != NULL)
2833 {
2834 p = enc_canonize(r);
2835 vim_free(r);
2836 r = p;
2837 }
2838 }
2839 if (r == NULL) /* out of memory */
2840 {
2841 r = (char_u *)"";
2842 *pp = NULL;
2843 }
2844 return r;
2845}
2846
2847# ifdef FEAT_EVAL
2848/*
2849 * Convert a file with the 'charconvert' expression.
2850 * This closes the file which is to be read, converts it and opens the
2851 * resulting file for reading.
2852 * Returns name of the resulting converted file (the caller should delete it
2853 * after reading it).
2854 * Returns NULL if the conversion failed ("*fdp" is not set) .
2855 */
2856 static char_u *
2857readfile_charconvert(fname, fenc, fdp)
2858 char_u *fname; /* name of input file */
2859 char_u *fenc; /* converted from */
2860 int *fdp; /* in/out: file descriptor of file */
2861{
2862 char_u *tmpname;
2863 char_u *errmsg = NULL;
2864
2865 tmpname = vim_tempname('r');
2866 if (tmpname == NULL)
2867 errmsg = (char_u *)_("Can't find temp file for conversion");
2868 else
2869 {
2870 close(*fdp); /* close the input file, ignore errors */
2871 *fdp = -1;
2872 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2873 fname, tmpname) == FAIL)
2874 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2875 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2876 O_RDONLY | O_EXTRA, 0)) < 0)
2877 errmsg = (char_u *)_("can't read output of 'charconvert'");
2878 }
2879
2880 if (errmsg != NULL)
2881 {
2882 /* Don't use emsg(), it breaks mappings, the retry with
2883 * another type of conversion might still work. */
2884 MSG(errmsg);
2885 if (tmpname != NULL)
2886 {
2887 mch_remove(tmpname); /* delete converted file */
2888 vim_free(tmpname);
2889 tmpname = NULL;
2890 }
2891 }
2892
2893 /* If the input file is closed, open it (caller should check for error). */
2894 if (*fdp < 0)
2895 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2896
2897 return tmpname;
2898}
2899# endif
2900
2901#endif
2902
2903#ifdef FEAT_VIMINFO
2904/*
2905 * Read marks for the current buffer from the viminfo file, when we support
2906 * buffer marks and the buffer has a name.
2907 */
2908 static void
2909check_marks_read()
2910{
2911 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2912 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002913 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002914
2915 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2916 * the ' parameter after opening a buffer. */
2917 curbuf->b_marks_read = TRUE;
2918}
2919#endif
2920
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002921#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002922/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002923 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002924 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2925 * *filesizep are updated.
2926 * Return the (new) encryption key, NULL for no encryption.
2927 */
2928 static char_u *
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002929check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002930 char_u *cryptkey; /* previous encryption key or NULL */
2931 char_u *ptr; /* pointer to read bytes */
2932 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002933 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 int newfile; /* editing a new buffer */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002935 char_u *fname; /* file name to display */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002936 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002937{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002938 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002939 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002940
2941 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002942 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002943 /* Mark the buffer as read-only until the decryption has taken place.
2944 * Avoids accidentally overwriting the file with garbage. */
2945 curbuf->b_p_ro = TRUE;
2946
Bram Moolenaar2be79502014-08-13 21:58:28 +02002947 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002948 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002949 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 {
2951 if (*curbuf->b_p_key)
2952 cryptkey = curbuf->b_p_key;
2953 else
2954 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002955 /* When newfile is TRUE, store the typed key in the 'key'
2956 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002957 * Don't ask for the key again when first time Enter was hit.
2958 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002959 smsg((char_u *)_(need_key_msg), fname);
2960 msg_scroll = TRUE;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002961 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002962 *did_ask = TRUE;
2963
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964 /* check if empty key entered */
2965 if (cryptkey != NULL && *cryptkey == NUL)
2966 {
2967 if (cryptkey != curbuf->b_p_key)
2968 vim_free(cryptkey);
2969 cryptkey = NULL;
2970 }
2971 }
2972 }
2973
2974 if (cryptkey != NULL)
2975 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002976 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002977
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002978 curbuf->b_cryptstate = crypt_create_from_header(
2979 method, cryptkey, ptr);
2980 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002981
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002982 /* Remove cryptmethod specific header from the text. */
2983 header_len = crypt_get_header_len(method);
2984 *filesizep += header_len;
2985 *sizep -= header_len;
2986 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
2987
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002988 /* Restore the read-only flag. */
2989 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002990 }
2991 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002992 /* When starting to edit a new file which does not have encryption, clear
2993 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002994 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002995 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2996
2997 return cryptkey;
2998}
Bram Moolenaar80794b12010-06-13 05:20:42 +02002999#endif /* FEAT_CRYPT */
3000
Bram Moolenaar071d4272004-06-13 20:20:40 +00003001#ifdef UNIX
3002 static void
3003set_file_time(fname, atime, mtime)
3004 char_u *fname;
3005 time_t atime; /* access time */
3006 time_t mtime; /* modification time */
3007{
3008# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3009 struct utimbuf buf;
3010
3011 buf.actime = atime;
3012 buf.modtime = mtime;
3013 (void)utime((char *)fname, &buf);
3014# else
3015# if defined(HAVE_UTIMES)
3016 struct timeval tvp[2];
3017
3018 tvp[0].tv_sec = atime;
3019 tvp[0].tv_usec = 0;
3020 tvp[1].tv_sec = mtime;
3021 tvp[1].tv_usec = 0;
3022# ifdef NeXT
3023 (void)utimes((char *)fname, tvp);
3024# else
3025 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3026# endif
3027# endif
3028# endif
3029}
3030#endif /* UNIX */
3031
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003032#if defined(VMS) && !defined(MIN)
3033/* Older DECC compiler for VAX doesn't define MIN() */
3034# define MIN(a, b) ((a) < (b) ? (a) : (b))
3035#endif
3036
Bram Moolenaar071d4272004-06-13 20:20:40 +00003037/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003038 * Return TRUE if a file appears to be read-only from the file permissions.
3039 */
3040 int
3041check_file_readonly(fname, perm)
3042 char_u *fname; /* full path to file */
3043 int perm; /* known permissions on file */
3044{
3045#ifndef USE_MCH_ACCESS
3046 int fd = 0;
3047#endif
3048
3049 return (
3050#ifdef USE_MCH_ACCESS
3051# ifdef UNIX
3052 (perm & 0222) == 0 ||
3053# endif
3054 mch_access((char *)fname, W_OK)
3055#else
3056 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3057 ? TRUE : (close(fd), FALSE)
3058#endif
3059 );
3060}
3061
3062
3063/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003064 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003065 *
3066 * We do our own buffering here because fwrite() is so slow.
3067 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003068 * If "forceit" is true, we don't care for errors when attempting backups.
3069 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003070 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003071 *
3072 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3073 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003074 *
3075 * This function must NOT use NameBuff (because it's called by autowrite()).
3076 *
3077 * return FAIL for failure, OK otherwise
3078 */
3079 int
3080buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3081 reset_changed, filtering)
3082 buf_T *buf;
3083 char_u *fname;
3084 char_u *sfname;
3085 linenr_T start, end;
3086 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3087 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003088 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 int forceit;
3090 int reset_changed;
3091 int filtering;
3092{
3093 int fd;
3094 char_u *backup = NULL;
3095 int backup_copy = FALSE; /* copy the original file? */
3096 int dobackup;
3097 char_u *ffname;
3098 char_u *wfname = NULL; /* name of file to write to */
3099 char_u *s;
3100 char_u *ptr;
3101 char_u c;
3102 int len;
3103 linenr_T lnum;
3104 long nchars;
3105 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003106 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003107 char_u *errnum = NULL;
3108 char_u *buffer;
3109 char_u smallbuf[SMBUFSIZE];
3110 char_u *backup_ext;
3111 int bufsize;
3112 long perm; /* file permissions */
3113 int retval = OK;
3114 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3115 int msg_save = msg_scroll;
3116 int overwriting; /* TRUE if writing over original */
3117 int no_eol = FALSE; /* no end-of-line written */
3118 int device = FALSE; /* writing to a device */
3119 struct stat st_old;
3120 int prev_got_int = got_int;
3121 int file_readonly = FALSE; /* overwritten file is read-only */
3122 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3123#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3124 int made_writable = FALSE; /* 'w' bit has been set */
3125#endif
3126 /* writing everything */
3127 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3128#ifdef FEAT_AUTOCMD
3129 linenr_T old_line_count = buf->b_ml.ml_line_count;
3130#endif
3131 int attr;
3132 int fileformat;
3133 int write_bin;
3134 struct bw_info write_info; /* info for buf_write_bytes() */
3135#ifdef FEAT_MBYTE
3136 int converted = FALSE;
3137 int notconverted = FALSE;
3138 char_u *fenc; /* effective 'fileencoding' */
3139 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3140#endif
3141#ifdef HAS_BW_FLAGS
3142 int wb_flags = 0;
3143#endif
3144#ifdef HAVE_ACL
3145 vim_acl_T acl = NULL; /* ACL copied from original file to
3146 backup or new file */
3147#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003148#ifdef FEAT_PERSISTENT_UNDO
3149 int write_undo_file = FALSE;
3150 context_sha256_T sha_ctx;
3151#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003152 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003153
3154 if (fname == NULL || *fname == NUL) /* safety check */
3155 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003156 if (buf->b_ml.ml_mfp == NULL)
3157 {
3158 /* This can happen during startup when there is a stray "w" in the
3159 * vimrc file. */
3160 EMSG(_(e_emptybuf));
3161 return FAIL;
3162 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003163
3164 /*
3165 * Disallow writing from .exrc and .vimrc in current directory for
3166 * security reasons.
3167 */
3168 if (check_secure())
3169 return FAIL;
3170
3171 /* Avoid a crash for a long name. */
3172 if (STRLEN(fname) >= MAXPATHL)
3173 {
3174 EMSG(_(e_longname));
3175 return FAIL;
3176 }
3177
3178#ifdef FEAT_MBYTE
3179 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3180 write_info.bw_conv_buf = NULL;
3181 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003182 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003183 write_info.bw_restlen = 0;
3184# ifdef USE_ICONV
3185 write_info.bw_iconv_fd = (iconv_t)-1;
3186# endif
3187#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003188#ifdef FEAT_CRYPT
3189 write_info.bw_buffer = buf;
3190#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191
Bram Moolenaardf177f62005-02-22 08:39:57 +00003192 /* After writing a file changedtick changes but we don't want to display
3193 * the line. */
3194 ex_no_reprint = TRUE;
3195
Bram Moolenaar071d4272004-06-13 20:20:40 +00003196 /*
3197 * If there is no file name yet, use the one for the written file.
3198 * BF_NOTEDITED is set to reflect this (in case the write fails).
3199 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003200 * Don't do this when appending.
3201 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003203 if (buf->b_ffname == NULL
3204 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205 && whole
3206 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003207#ifdef FEAT_QUICKFIX
3208 && !bt_nofile(buf)
3209#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003211 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003212 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3213 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003214 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003216 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003217 }
3218
3219 if (sfname == NULL)
3220 sfname = fname;
3221 /*
3222 * For Unix: Use the short file name whenever possible.
3223 * Avoids problems with networks and when directory names are changed.
3224 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3225 * another directory, which we don't detect
3226 */
3227 ffname = fname; /* remember full fname */
3228#ifdef UNIX
3229 fname = sfname;
3230#endif
3231
3232 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3233 overwriting = TRUE;
3234 else
3235 overwriting = FALSE;
3236
3237 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003238 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003239
3240 ++no_wait_return; /* don't wait for return yet */
3241
3242 /*
3243 * Set '[ and '] marks to the lines to be written.
3244 */
3245 buf->b_op_start.lnum = start;
3246 buf->b_op_start.col = 0;
3247 buf->b_op_end.lnum = end;
3248 buf->b_op_end.col = 0;
3249
3250#ifdef FEAT_AUTOCMD
3251 {
3252 aco_save_T aco;
3253 int buf_ffname = FALSE;
3254 int buf_sfname = FALSE;
3255 int buf_fname_f = FALSE;
3256 int buf_fname_s = FALSE;
3257 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003258 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003259 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003260
3261 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003262 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263 * Set curbuf to the buffer to be written.
3264 * Careful: The autocommands may call buf_write() recursively!
3265 */
3266 if (ffname == buf->b_ffname)
3267 buf_ffname = TRUE;
3268 if (sfname == buf->b_sfname)
3269 buf_sfname = TRUE;
3270 if (fname == buf->b_ffname)
3271 buf_fname_f = TRUE;
3272 if (fname == buf->b_sfname)
3273 buf_fname_s = TRUE;
3274
3275 /* set curwin/curbuf to buf and save a few things */
3276 aucmd_prepbuf(&aco, buf);
3277
3278 if (append)
3279 {
3280 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3281 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003282 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003283#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003284 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003285 nofile_err = TRUE;
3286 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003287#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003288 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003289 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003290 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003291 }
3292 else if (filtering)
3293 {
3294 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3295 NULL, sfname, FALSE, curbuf, eap);
3296 }
3297 else if (reset_changed && whole)
3298 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003299 int was_changed = curbufIsChanged();
3300
3301 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3302 sfname, sfname, FALSE, curbuf, eap);
3303 if (did_cmd)
3304 {
3305 if (was_changed && !curbufIsChanged())
3306 {
3307 /* Written everything correctly and BufWriteCmd has reset
3308 * 'modified': Correct the undo information so that an
3309 * undo now sets 'modified'. */
3310 u_unchanged(curbuf);
3311 u_update_save_nr(curbuf);
3312 }
3313 }
3314 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003315 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003316#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003317 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003318 nofile_err = TRUE;
3319 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003320#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003321 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003322 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003323 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324 }
3325 else
3326 {
3327 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3328 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003329 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003330#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003331 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003332 nofile_err = TRUE;
3333 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003334#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003335 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003336 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003337 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338 }
3339
3340 /* restore curwin/curbuf and a few other things */
3341 aucmd_restbuf(&aco);
3342
3343 /*
3344 * In three situations we return here and don't write the file:
3345 * 1. the autocommands deleted or unloaded the buffer.
3346 * 2. The autocommands abort script processing.
3347 * 3. If one of the "Cmd" autocommands was executed.
3348 */
3349 if (!buf_valid(buf))
3350 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003351 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003352 || did_cmd || nofile_err
3353#ifdef FEAT_EVAL
3354 || aborting()
3355#endif
3356 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 {
3358 --no_wait_return;
3359 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003360 if (nofile_err)
3361 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3362
Bram Moolenaar1e015462005-09-25 22:16:38 +00003363 if (nofile_err
3364#ifdef FEAT_EVAL
3365 || aborting()
3366#endif
3367 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003368 /* An aborting error, interrupt or exception in the
3369 * autocommands. */
3370 return FAIL;
3371 if (did_cmd)
3372 {
3373 if (buf == NULL)
3374 /* The buffer was deleted. We assume it was written
3375 * (can't retry anyway). */
3376 return OK;
3377 if (overwriting)
3378 {
3379 /* Assume the buffer was written, update the timestamp. */
3380 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003381 if (append)
3382 buf->b_flags &= ~BF_NEW;
3383 else
3384 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003385 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003386 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003387 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003388 /* Buffer still changed, the autocommands didn't work
3389 * properly. */
3390 return FAIL;
3391 return OK;
3392 }
3393#ifdef FEAT_EVAL
3394 if (!aborting())
3395#endif
3396 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3397 return FAIL;
3398 }
3399
3400 /*
3401 * The autocommands may have changed the number of lines in the file.
3402 * When writing the whole file, adjust the end.
3403 * When writing part of the file, assume that the autocommands only
3404 * changed the number of lines that are to be written (tricky!).
3405 */
3406 if (buf->b_ml.ml_line_count != old_line_count)
3407 {
3408 if (whole) /* write all */
3409 end = buf->b_ml.ml_line_count;
3410 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3411 end += buf->b_ml.ml_line_count - old_line_count;
3412 else /* less lines */
3413 {
3414 end -= old_line_count - buf->b_ml.ml_line_count;
3415 if (end < start)
3416 {
3417 --no_wait_return;
3418 msg_scroll = msg_save;
3419 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3420 return FAIL;
3421 }
3422 }
3423 }
3424
3425 /*
3426 * The autocommands may have changed the name of the buffer, which may
3427 * be kept in fname, ffname and sfname.
3428 */
3429 if (buf_ffname)
3430 ffname = buf->b_ffname;
3431 if (buf_sfname)
3432 sfname = buf->b_sfname;
3433 if (buf_fname_f)
3434 fname = buf->b_ffname;
3435 if (buf_fname_s)
3436 fname = buf->b_sfname;
3437 }
3438#endif
3439
3440#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003441 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003442 {
3443 if (whole)
3444 {
3445 /*
3446 * b_changed can be 0 after an undo, but we still need to write
3447 * the buffer to NetBeans.
3448 */
3449 if (buf->b_changed || isNetbeansModified(buf))
3450 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003451 --no_wait_return; /* may wait for return now */
3452 msg_scroll = msg_save;
3453 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003454 return retval;
3455 }
3456 else
3457 {
3458 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003459 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460 buffer = NULL;
3461 goto fail;
3462 }
3463 }
3464 else
3465 {
3466 errnum = (char_u *)"E657: ";
3467 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3468 buffer = NULL;
3469 goto fail;
3470 }
3471 }
3472#endif
3473
3474 if (shortmess(SHM_OVER) && !exiting)
3475 msg_scroll = FALSE; /* overwrite previous file message */
3476 else
3477 msg_scroll = TRUE; /* don't overwrite previous file message */
3478 if (!filtering)
3479 filemess(buf,
3480#ifndef UNIX
3481 sfname,
3482#else
3483 fname,
3484#endif
3485 (char_u *)"", 0); /* show that we are busy */
3486 msg_scroll = FALSE; /* always overwrite the file message now */
3487
3488 buffer = alloc(BUFSIZE);
3489 if (buffer == NULL) /* can't allocate big buffer, use small
3490 * one (to be able to write when out of
3491 * memory) */
3492 {
3493 buffer = smallbuf;
3494 bufsize = SMBUFSIZE;
3495 }
3496 else
3497 bufsize = BUFSIZE;
3498
3499 /*
3500 * Get information about original file (if there is one).
3501 */
3502#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003503 st_old.st_dev = 0;
3504 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003505 perm = -1;
3506 if (mch_stat((char *)fname, &st_old) < 0)
3507 newfile = TRUE;
3508 else
3509 {
3510 perm = st_old.st_mode;
3511 if (!S_ISREG(st_old.st_mode)) /* not a file */
3512 {
3513 if (S_ISDIR(st_old.st_mode))
3514 {
3515 errnum = (char_u *)"E502: ";
3516 errmsg = (char_u *)_("is a directory");
3517 goto fail;
3518 }
3519 if (mch_nodetype(fname) != NODE_WRITABLE)
3520 {
3521 errnum = (char_u *)"E503: ";
3522 errmsg = (char_u *)_("is not a file or writable device");
3523 goto fail;
3524 }
3525 /* It's a device of some kind (or a fifo) which we can write to
3526 * but for which we can't make a backup. */
3527 device = TRUE;
3528 newfile = TRUE;
3529 perm = -1;
3530 }
3531 }
3532#else /* !UNIX */
3533 /*
3534 * Check for a writable device name.
3535 */
3536 c = mch_nodetype(fname);
3537 if (c == NODE_OTHER)
3538 {
3539 errnum = (char_u *)"E503: ";
3540 errmsg = (char_u *)_("is not a file or writable device");
3541 goto fail;
3542 }
3543 if (c == NODE_WRITABLE)
3544 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003545# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3546 /* MS-Windows allows opening a device, but we will probably get stuck
3547 * trying to write to it. */
3548 if (!p_odev)
3549 {
3550 errnum = (char_u *)"E796: ";
3551 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3552 goto fail;
3553 }
3554# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555 device = TRUE;
3556 newfile = TRUE;
3557 perm = -1;
3558 }
3559 else
3560 {
3561 perm = mch_getperm(fname);
3562 if (perm < 0)
3563 newfile = TRUE;
3564 else if (mch_isdir(fname))
3565 {
3566 errnum = (char_u *)"E502: ";
3567 errmsg = (char_u *)_("is a directory");
3568 goto fail;
3569 }
3570 if (overwriting)
3571 (void)mch_stat((char *)fname, &st_old);
3572 }
3573#endif /* !UNIX */
3574
3575 if (!device && !newfile)
3576 {
3577 /*
3578 * Check if the file is really writable (when renaming the file to
3579 * make a backup we won't discover it later).
3580 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003581 file_readonly = check_file_readonly(fname, (int)perm);
3582
Bram Moolenaar071d4272004-06-13 20:20:40 +00003583 if (!forceit && file_readonly)
3584 {
3585 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3586 {
3587 errnum = (char_u *)"E504: ";
3588 errmsg = (char_u *)_(err_readonly);
3589 }
3590 else
3591 {
3592 errnum = (char_u *)"E505: ";
3593 errmsg = (char_u *)_("is read-only (add ! to override)");
3594 }
3595 goto fail;
3596 }
3597
3598 /*
3599 * Check if the timestamp hasn't changed since reading the file.
3600 */
3601 if (overwriting)
3602 {
3603 retval = check_mtime(buf, &st_old);
3604 if (retval == FAIL)
3605 goto fail;
3606 }
3607 }
3608
3609#ifdef HAVE_ACL
3610 /*
3611 * For systems that support ACL: get the ACL from the original file.
3612 */
3613 if (!newfile)
3614 acl = mch_get_acl(fname);
3615#endif
3616
3617 /*
3618 * If 'backupskip' is not empty, don't make a backup for some files.
3619 */
3620 dobackup = (p_wb || p_bk || *p_pm != NUL);
3621#ifdef FEAT_WILDIGN
3622 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3623 dobackup = FALSE;
3624#endif
3625
3626 /*
3627 * Save the value of got_int and reset it. We don't want a previous
3628 * interruption cancel writing, only hitting CTRL-C while writing should
3629 * abort it.
3630 */
3631 prev_got_int = got_int;
3632 got_int = FALSE;
3633
3634 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3635 buf->b_saving = TRUE;
3636
3637 /*
3638 * If we are not appending or filtering, the file exists, and the
3639 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3640 * When 'patchmode' is set also make a backup when appending.
3641 *
3642 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3643 * off. This helps when editing large files on almost-full disks.
3644 */
3645 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3646 {
3647#if defined(UNIX) || defined(WIN32)
3648 struct stat st;
3649#endif
3650
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003651 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652 backup_copy = TRUE;
3653#if defined(UNIX) || defined(WIN32)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003654 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655 {
3656 int i;
3657
3658# ifdef UNIX
3659 /*
3660 * Don't rename the file when:
3661 * - it's a hard link
3662 * - it's a symbolic link
3663 * - we don't have write permission in the directory
3664 * - we can't set the owner/group of the new file
3665 */
3666 if (st_old.st_nlink > 1
3667 || mch_lstat((char *)fname, &st) < 0
3668 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003669 || st.st_ino != st_old.st_ino
3670# ifndef HAVE_FCHOWN
3671 || st.st_uid != st_old.st_uid
3672 || st.st_gid != st_old.st_gid
3673# endif
3674 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003675 backup_copy = TRUE;
3676 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003677# else
3678# ifdef WIN32
3679 /* On NTFS file systems hard links are possible. */
3680 if (mch_is_linked(fname))
3681 backup_copy = TRUE;
3682 else
3683# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003684# endif
3685 {
3686 /*
3687 * Check if we can create a file and set the owner/group to
3688 * the ones from the original file.
3689 * First find a file name that doesn't exist yet (use some
3690 * arbitrary numbers).
3691 */
3692 STRCPY(IObuff, fname);
3693 for (i = 4913; ; i += 123)
3694 {
3695 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003696 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003697 break;
3698 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003699 fd = mch_open((char *)IObuff,
3700 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701 if (fd < 0) /* can't write in directory */
3702 backup_copy = TRUE;
3703 else
3704 {
3705# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003706# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003707 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003708# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003709 if (mch_stat((char *)IObuff, &st) < 0
3710 || st.st_uid != st_old.st_uid
3711 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003712 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003713 backup_copy = TRUE;
3714# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003715 /* Close the file before removing it, on MS-Windows we
3716 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003717 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003718 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003719# ifdef MSWIN
3720 /* MS-Windows may trigger a virus scanner to open the
3721 * file, we can't delete it then. Keep trying for half a
3722 * second. */
3723 {
3724 int try;
3725
3726 for (try = 0; try < 10; ++try)
3727 {
3728 if (mch_lstat((char *)IObuff, &st) < 0)
3729 break;
3730 ui_delay(50L, TRUE); /* wait 50 msec */
3731 mch_remove(IObuff);
3732 }
3733 }
3734# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003735 }
3736 }
3737 }
3738
Bram Moolenaar071d4272004-06-13 20:20:40 +00003739 /*
3740 * Break symlinks and/or hardlinks if we've been asked to.
3741 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003742 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003744# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003745 int lstat_res;
3746
3747 lstat_res = mch_lstat((char *)fname, &st);
3748
3749 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003750 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751 && lstat_res == 0
3752 && st.st_ino != st_old.st_ino)
3753 backup_copy = FALSE;
3754
3755 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003756 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003757 && st_old.st_nlink > 1
3758 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3759 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003760# else
3761# if defined(WIN32)
3762 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003763 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003764 backup_copy = FALSE;
3765
3766 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003767 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003768 backup_copy = FALSE;
3769# endif
3770# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003772
3773#endif
3774
3775 /* make sure we have a valid backup extension to use */
3776 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003778 else
3779 backup_ext = p_bex;
3780
3781 if (backup_copy
3782 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3783 {
3784 int bfd;
3785 char_u *copybuf, *wp;
3786 int some_error = FALSE;
3787 struct stat st_new;
3788 char_u *dirp;
3789 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003790#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003791 int did_set_shortname;
3792#endif
3793
3794 copybuf = alloc(BUFSIZE + 1);
3795 if (copybuf == NULL)
3796 {
3797 some_error = TRUE; /* out of memory */
3798 goto nobackup;
3799 }
3800
3801 /*
3802 * Try to make the backup in each directory in the 'bdir' option.
3803 *
3804 * Unix semantics has it, that we may have a writable file,
3805 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3806 * - the directory is not writable,
3807 * - the file may be a symbolic link,
3808 * - the file may belong to another user/group, etc.
3809 *
3810 * For these reasons, the existing writable file must be truncated
3811 * and reused. Creation of a backup COPY will be attempted.
3812 */
3813 dirp = p_bdir;
3814 while (*dirp)
3815 {
3816#ifdef UNIX
3817 st_new.st_ino = 0;
3818 st_new.st_dev = 0;
3819 st_new.st_gid = 0;
3820#endif
3821
3822 /*
3823 * Isolate one directory name, using an entry in 'bdir'.
3824 */
3825 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3826 rootname = get_file_in_dir(fname, copybuf);
3827 if (rootname == NULL)
3828 {
3829 some_error = TRUE; /* out of memory */
3830 goto nobackup;
3831 }
3832
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003833#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003834 did_set_shortname = FALSE;
3835#endif
3836
3837 /*
3838 * May try twice if 'shortname' not set.
3839 */
3840 for (;;)
3841 {
3842 /*
3843 * Make backup file name.
3844 */
3845 backup = buf_modname(
3846#ifdef SHORT_FNAME
3847 TRUE,
3848#else
3849 (buf->b_p_sn || buf->b_shortname),
3850#endif
3851 rootname, backup_ext, FALSE);
3852 if (backup == NULL)
3853 {
3854 vim_free(rootname);
3855 some_error = TRUE; /* out of memory */
3856 goto nobackup;
3857 }
3858
3859 /*
3860 * Check if backup file already exists.
3861 */
3862 if (mch_stat((char *)backup, &st_new) >= 0)
3863 {
3864#ifdef UNIX
3865 /*
3866 * Check if backup file is same as original file.
3867 * May happen when modname() gave the same file back.
3868 * E.g. silly link, or file name-length reached.
3869 * If we don't check here, we either ruin the file
3870 * when copying or erase it after writing. jw.
3871 */
3872 if (st_new.st_dev == st_old.st_dev
3873 && st_new.st_ino == st_old.st_ino)
3874 {
3875 vim_free(backup);
3876 backup = NULL; /* no backup file to delete */
3877# ifndef SHORT_FNAME
3878 /*
3879 * may try again with 'shortname' set
3880 */
3881 if (!(buf->b_shortname || buf->b_p_sn))
3882 {
3883 buf->b_shortname = TRUE;
3884 did_set_shortname = TRUE;
3885 continue;
3886 }
3887 /* setting shortname didn't help */
3888 if (did_set_shortname)
3889 buf->b_shortname = FALSE;
3890# endif
3891 break;
3892 }
3893#endif
3894
3895 /*
3896 * If we are not going to keep the backup file, don't
3897 * delete an existing one, try to use another name.
3898 * Change one character, just before the extension.
3899 */
3900 if (!p_bk)
3901 {
3902 wp = backup + STRLEN(backup) - 1
3903 - STRLEN(backup_ext);
3904 if (wp < backup) /* empty file name ??? */
3905 wp = backup;
3906 *wp = 'z';
3907 while (*wp > 'a'
3908 && mch_stat((char *)backup, &st_new) >= 0)
3909 --*wp;
3910 /* They all exist??? Must be something wrong. */
3911 if (*wp == 'a')
3912 {
3913 vim_free(backup);
3914 backup = NULL;
3915 }
3916 }
3917 }
3918 break;
3919 }
3920 vim_free(rootname);
3921
3922 /*
3923 * Try to create the backup file
3924 */
3925 if (backup != NULL)
3926 {
3927 /* remove old backup, if present */
3928 mch_remove(backup);
3929 /* Open with O_EXCL to avoid the file being created while
3930 * we were sleeping (symlink hacker attack?) */
3931 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003932 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3933 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003934 if (bfd < 0)
3935 {
3936 vim_free(backup);
3937 backup = NULL;
3938 }
3939 else
3940 {
3941 /* set file protection same as original file, but
3942 * strip s-bit */
3943 (void)mch_setperm(backup, perm & 0777);
3944
3945#ifdef UNIX
3946 /*
3947 * Try to set the group of the backup same as the
3948 * original file. If this fails, set the protection
3949 * bits for the group same as the protection bits for
3950 * others.
3951 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003952 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003953# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003954 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003955# endif
3956 )
3957 mch_setperm(backup,
3958 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003959# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003960 mch_copy_sec(fname, backup);
3961# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962#endif
3963
3964 /*
3965 * copy the file.
3966 */
3967 write_info.bw_fd = bfd;
3968 write_info.bw_buf = copybuf;
3969#ifdef HAS_BW_FLAGS
3970 write_info.bw_flags = FIO_NOCONVERT;
3971#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003972 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973 BUFSIZE)) > 0)
3974 {
3975 if (buf_write_bytes(&write_info) == FAIL)
3976 {
3977 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3978 break;
3979 }
3980 ui_breakcheck();
3981 if (got_int)
3982 {
3983 errmsg = (char_u *)_(e_interr);
3984 break;
3985 }
3986 }
3987
3988 if (close(bfd) < 0 && errmsg == NULL)
3989 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3990 if (write_info.bw_len < 0)
3991 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3992#ifdef UNIX
3993 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3994#endif
3995#ifdef HAVE_ACL
3996 mch_set_acl(backup, acl);
3997#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003998#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003999 mch_copy_sec(fname, backup);
4000#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004001 break;
4002 }
4003 }
4004 }
4005 nobackup:
4006 close(fd); /* ignore errors for closing read file */
4007 vim_free(copybuf);
4008
4009 if (backup == NULL && errmsg == NULL)
4010 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4011 /* ignore errors when forceit is TRUE */
4012 if ((some_error || errmsg != NULL) && !forceit)
4013 {
4014 retval = FAIL;
4015 goto fail;
4016 }
4017 errmsg = NULL;
4018 }
4019 else
4020 {
4021 char_u *dirp;
4022 char_u *p;
4023 char_u *rootname;
4024
4025 /*
4026 * Make a backup by renaming the original file.
4027 */
4028 /*
4029 * If 'cpoptions' includes the "W" flag, we don't want to
4030 * overwrite a read-only file. But rename may be possible
4031 * anyway, thus we need an extra check here.
4032 */
4033 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4034 {
4035 errnum = (char_u *)"E504: ";
4036 errmsg = (char_u *)_(err_readonly);
4037 goto fail;
4038 }
4039
4040 /*
4041 *
4042 * Form the backup file name - change path/fo.o.h to
4043 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4044 * that works is used.
4045 */
4046 dirp = p_bdir;
4047 while (*dirp)
4048 {
4049 /*
4050 * Isolate one directory name and make the backup file name.
4051 */
4052 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4053 rootname = get_file_in_dir(fname, IObuff);
4054 if (rootname == NULL)
4055 backup = NULL;
4056 else
4057 {
4058 backup = buf_modname(
4059#ifdef SHORT_FNAME
4060 TRUE,
4061#else
4062 (buf->b_p_sn || buf->b_shortname),
4063#endif
4064 rootname, backup_ext, FALSE);
4065 vim_free(rootname);
4066 }
4067
4068 if (backup != NULL)
4069 {
4070 /*
4071 * If we are not going to keep the backup file, don't
4072 * delete an existing one, try to use another name.
4073 * Change one character, just before the extension.
4074 */
4075 if (!p_bk && mch_getperm(backup) >= 0)
4076 {
4077 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4078 if (p < backup) /* empty file name ??? */
4079 p = backup;
4080 *p = 'z';
4081 while (*p > 'a' && mch_getperm(backup) >= 0)
4082 --*p;
4083 /* They all exist??? Must be something wrong! */
4084 if (*p == 'a')
4085 {
4086 vim_free(backup);
4087 backup = NULL;
4088 }
4089 }
4090 }
4091 if (backup != NULL)
4092 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004093 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004094 * Delete any existing backup and move the current version
4095 * to the backup. For safety, we don't remove the backup
4096 * until the write has finished successfully. And if the
4097 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004098 */
4099 /*
4100 * If the renaming of the original file to the backup file
4101 * works, quit here.
4102 */
4103 if (vim_rename(fname, backup) == 0)
4104 break;
4105
4106 vim_free(backup); /* don't do the rename below */
4107 backup = NULL;
4108 }
4109 }
4110 if (backup == NULL && !forceit)
4111 {
4112 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4113 goto fail;
4114 }
4115 }
4116 }
4117
4118#if defined(UNIX) && !defined(ARCHIE)
4119 /* When using ":w!" and the file was read-only: make it writable */
4120 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4121 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4122 {
4123 perm |= 0200;
4124 (void)mch_setperm(fname, perm);
4125 made_writable = TRUE;
4126 }
4127#endif
4128
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004129 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004130 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4131 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004132 {
4133 buf->b_p_ro = FALSE;
4134#ifdef FEAT_TITLE
4135 need_maketitle = TRUE; /* set window title later */
4136#endif
4137#ifdef FEAT_WINDOWS
4138 status_redraw_all(); /* redraw status lines later */
4139#endif
4140 }
4141
4142 if (end > buf->b_ml.ml_line_count)
4143 end = buf->b_ml.ml_line_count;
4144 if (buf->b_ml.ml_flags & ML_EMPTY)
4145 start = end + 1;
4146
4147 /*
4148 * If the original file is being overwritten, there is a small chance that
4149 * we crash in the middle of writing. Therefore the file is preserved now.
4150 * This makes all block numbers positive so that recovery does not need
4151 * the original file.
4152 * Don't do this if there is a backup file and we are exiting.
4153 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004154 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155 && !(exiting && backup != NULL))
4156 {
4157 ml_preserve(buf, FALSE);
4158 if (got_int)
4159 {
4160 errmsg = (char_u *)_(e_interr);
4161 goto restore_backup;
4162 }
4163 }
4164
4165#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4166 /*
4167 * Before risking to lose the original file verify if there's
4168 * a resource fork to preserve, and if cannot be done warn
4169 * the users. This happens when overwriting without backups.
4170 */
4171 if (backup == NULL && overwriting && !append)
4172 if (mch_has_resource_fork(fname))
4173 {
4174 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4175 goto restore_backup;
4176 }
4177#endif
4178
4179#ifdef VMS
4180 vms_remove_version(fname); /* remove version */
4181#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004182 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 * multi-byte conversion. */
4184 wfname = fname;
4185
4186#ifdef FEAT_MBYTE
4187 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4188 if (eap != NULL && eap->force_enc != 0)
4189 {
4190 fenc = eap->cmd + eap->force_enc;
4191 fenc = enc_canonize(fenc);
4192 fenc_tofree = fenc;
4193 }
4194 else
4195 fenc = buf->b_p_fenc;
4196
4197 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004198 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004200 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004201
4202 /*
4203 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4204 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4205 * Prepare the flags for it and allocate bw_conv_buf when needed.
4206 */
4207 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4208 {
4209 wb_flags = get_fio_flags(fenc);
4210 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4211 {
4212 /* Need to allocate a buffer to translate into. */
4213 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4214 write_info.bw_conv_buflen = bufsize * 2;
4215 else /* FIO_UCS4 */
4216 write_info.bw_conv_buflen = bufsize * 4;
4217 write_info.bw_conv_buf
4218 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4219 if (write_info.bw_conv_buf == NULL)
4220 end = 0;
4221 }
4222 }
4223
4224# ifdef WIN3264
4225 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4226 {
4227 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4228 write_info.bw_conv_buflen = bufsize * 4;
4229 write_info.bw_conv_buf
4230 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4231 if (write_info.bw_conv_buf == NULL)
4232 end = 0;
4233 }
4234# endif
4235
4236# ifdef MACOS_X
4237 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4238 {
4239 write_info.bw_conv_buflen = bufsize * 3;
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# endif
4246
4247# if defined(FEAT_EVAL) || defined(USE_ICONV)
4248 if (converted && wb_flags == 0)
4249 {
4250# ifdef USE_ICONV
4251 /*
4252 * Use iconv() conversion when conversion is needed and it's not done
4253 * internally.
4254 */
4255 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4256 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4257 if (write_info.bw_iconv_fd != (iconv_t)-1)
4258 {
4259 /* We're going to use iconv(), allocate a buffer to convert in. */
4260 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4261 write_info.bw_conv_buf
4262 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4263 if (write_info.bw_conv_buf == NULL)
4264 end = 0;
4265 write_info.bw_first = TRUE;
4266 }
4267# ifdef FEAT_EVAL
4268 else
4269# endif
4270# endif
4271
4272# ifdef FEAT_EVAL
4273 /*
4274 * When the file needs to be converted with 'charconvert' after
4275 * writing, write to a temp file instead and let the conversion
4276 * overwrite the original file.
4277 */
4278 if (*p_ccv != NUL)
4279 {
4280 wfname = vim_tempname('w');
4281 if (wfname == NULL) /* Can't write without a tempfile! */
4282 {
4283 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4284 goto restore_backup;
4285 }
4286 }
4287# endif
4288 }
4289# endif
4290 if (converted && wb_flags == 0
4291# ifdef USE_ICONV
4292 && write_info.bw_iconv_fd == (iconv_t)-1
4293# endif
4294# ifdef FEAT_EVAL
4295 && wfname == fname
4296# endif
4297 )
4298 {
4299 if (!forceit)
4300 {
4301 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4302 goto restore_backup;
4303 }
4304 notconverted = TRUE;
4305 }
4306#endif
4307
4308 /*
4309 * Open the file "wfname" for writing.
4310 * We may try to open the file twice: If we can't write to the
4311 * file and forceit is TRUE we delete the existing file and try to create
4312 * a new one. If this still fails we may have lost the original file!
4313 * (this may happen when the user reached his quotum for number of files).
4314 * Appending will fail if the file does not exist and forceit is FALSE.
4315 */
4316 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4317 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4318 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004319 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004320 {
4321 /*
4322 * A forced write will try to create a new file if the old one is
4323 * still readonly. This may also happen when the directory is
4324 * read-only. In that case the mch_remove() will fail.
4325 */
4326 if (errmsg == NULL)
4327 {
4328#ifdef UNIX
4329 struct stat st;
4330
4331 /* Don't delete the file when it's a hard or symbolic link. */
4332 if ((!newfile && st_old.st_nlink > 1)
4333 || (mch_lstat((char *)fname, &st) == 0
4334 && (st.st_dev != st_old.st_dev
4335 || st.st_ino != st_old.st_ino)))
4336 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4337 else
4338#endif
4339 {
4340 errmsg = (char_u *)_("E212: Can't open file for writing");
4341 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4342 && perm >= 0)
4343 {
4344#ifdef UNIX
4345 /* we write to the file, thus it should be marked
4346 writable after all */
4347 if (!(perm & 0200))
4348 made_writable = TRUE;
4349 perm |= 0200;
4350 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4351 perm &= 0777;
4352#endif
4353 if (!append) /* don't remove when appending */
4354 mch_remove(wfname);
4355 continue;
4356 }
4357 }
4358 }
4359
4360restore_backup:
4361 {
4362 struct stat st;
4363
4364 /*
4365 * If we failed to open the file, we don't need a backup. Throw it
4366 * away. If we moved or removed the original file try to put the
4367 * backup in its place.
4368 */
4369 if (backup != NULL && wfname == fname)
4370 {
4371 if (backup_copy)
4372 {
4373 /*
4374 * There is a small chance that we removed the original,
4375 * try to move the copy in its place.
4376 * This may not work if the vim_rename() fails.
4377 * In that case we leave the copy around.
4378 */
4379 /* If file does not exist, put the copy in its place */
4380 if (mch_stat((char *)fname, &st) < 0)
4381 vim_rename(backup, fname);
4382 /* if original file does exist throw away the copy */
4383 if (mch_stat((char *)fname, &st) >= 0)
4384 mch_remove(backup);
4385 }
4386 else
4387 {
4388 /* try to put the original file back */
4389 vim_rename(backup, fname);
4390 }
4391 }
4392
4393 /* if original file no longer exists give an extra warning */
4394 if (!newfile && mch_stat((char *)fname, &st) < 0)
4395 end = 0;
4396 }
4397
4398#ifdef FEAT_MBYTE
4399 if (wfname != fname)
4400 vim_free(wfname);
4401#endif
4402 goto fail;
4403 }
4404 errmsg = NULL;
4405
4406#if defined(MACOS_CLASSIC) || defined(WIN3264)
4407 /* TODO: Is it need for MACOS_X? (Dany) */
4408 /*
4409 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004410 * This is done in order to preserve the resource fork and the
4411 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412 */
4413 if (backup != NULL && overwriting && !append)
4414 {
4415 if (backup_copy)
4416 (void)mch_copy_file_attribute(wfname, backup);
4417 else
4418 (void)mch_copy_file_attribute(backup, wfname);
4419 }
4420
4421 if (!overwriting && !append)
4422 {
4423 if (buf->b_ffname != NULL)
4424 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004425 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004426 }
4427#endif
4428
4429 write_info.bw_fd = fd;
4430
4431#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004432 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004433 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004434 char_u *header;
4435 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004436
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004437 buf->b_cryptstate = crypt_create_for_writing(crypt_get_method_nr(buf),
4438 buf->b_p_key, &header, &header_len);
4439 if (buf->b_cryptstate == NULL || header == NULL)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004440 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004441 else
4442 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004443 /* Write magic number, so that Vim knows how this file is
4444 * encrypted when reading it back. */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004445 write_info.bw_buf = header;
4446 write_info.bw_len = header_len;
4447 write_info.bw_flags = FIO_NOCONVERT;
4448 if (buf_write_bytes(&write_info) == FAIL)
4449 end = 0;
4450 wb_flags |= FIO_ENCRYPTED;
4451 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453 }
4454#endif
4455
4456 write_info.bw_buf = buffer;
4457 nchars = 0;
4458
4459 /* use "++bin", "++nobin" or 'binary' */
4460 if (eap != NULL && eap->force_bin != 0)
4461 write_bin = (eap->force_bin == FORCE_BIN);
4462 else
4463 write_bin = buf->b_p_bin;
4464
4465#ifdef FEAT_MBYTE
4466 /*
4467 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004468 * Skip it when appending and the file already existed, the BOM only makes
4469 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004470 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004471 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004472 {
4473 write_info.bw_len = make_bom(buffer, fenc);
4474 if (write_info.bw_len > 0)
4475 {
4476 /* don't convert, do encryption */
4477 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4478 if (buf_write_bytes(&write_info) == FAIL)
4479 end = 0;
4480 else
4481 nchars += write_info.bw_len;
4482 }
4483 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004484 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004485#endif
4486
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004487#ifdef FEAT_PERSISTENT_UNDO
4488 write_undo_file = (buf->b_p_udf && overwriting && !append
4489 && !filtering && reset_changed);
4490 if (write_undo_file)
4491 /* Prepare for computing the hash value of the text. */
4492 sha256_start(&sha_ctx);
4493#endif
4494
Bram Moolenaar071d4272004-06-13 20:20:40 +00004495 write_info.bw_len = bufsize;
4496#ifdef HAS_BW_FLAGS
4497 write_info.bw_flags = wb_flags;
4498#endif
4499 fileformat = get_fileformat_force(buf, eap);
4500 s = buffer;
4501 len = 0;
4502 for (lnum = start; lnum <= end; ++lnum)
4503 {
4504 /*
4505 * The next while loop is done once for each character written.
4506 * Keep it fast!
4507 */
4508 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004509#ifdef FEAT_PERSISTENT_UNDO
4510 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004511 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004512#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004513 while ((c = *++ptr) != NUL)
4514 {
4515 if (c == NL)
4516 *s = NUL; /* replace newlines with NULs */
4517 else if (c == CAR && fileformat == EOL_MAC)
4518 *s = NL; /* Mac: replace CRs with NLs */
4519 else
4520 *s = c;
4521 ++s;
4522 if (++len != bufsize)
4523 continue;
4524 if (buf_write_bytes(&write_info) == FAIL)
4525 {
4526 end = 0; /* write error: break loop */
4527 break;
4528 }
4529 nchars += bufsize;
4530 s = buffer;
4531 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004532#ifdef FEAT_MBYTE
4533 write_info.bw_start_lnum = lnum;
4534#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004535 }
4536 /* write failed or last line has no EOL: stop here */
4537 if (end == 0
4538 || (lnum == end
4539 && write_bin
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004540 && (lnum == buf->b_no_eol_lnum
Bram Moolenaar071d4272004-06-13 20:20:40 +00004541 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4542 {
4543 ++lnum; /* written the line, count it */
4544 no_eol = TRUE;
4545 break;
4546 }
4547 if (fileformat == EOL_UNIX)
4548 *s++ = NL;
4549 else
4550 {
4551 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4552 if (fileformat == EOL_DOS) /* write CR-NL */
4553 {
4554 if (++len == bufsize)
4555 {
4556 if (buf_write_bytes(&write_info) == FAIL)
4557 {
4558 end = 0; /* write error: break loop */
4559 break;
4560 }
4561 nchars += bufsize;
4562 s = buffer;
4563 len = 0;
4564 }
4565 *s++ = NL;
4566 }
4567 }
4568 if (++len == bufsize && end)
4569 {
4570 if (buf_write_bytes(&write_info) == FAIL)
4571 {
4572 end = 0; /* write error: break loop */
4573 break;
4574 }
4575 nchars += bufsize;
4576 s = buffer;
4577 len = 0;
4578
4579 ui_breakcheck();
4580 if (got_int)
4581 {
4582 end = 0; /* Interrupted, break loop */
4583 break;
4584 }
4585 }
4586#ifdef VMS
4587 /*
4588 * On VMS there is a problem: newlines get added when writing blocks
4589 * at a time. Fix it by writing a line at a time.
4590 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004591 * Explanation: VAX/DECC RTL insists that records in some RMS
4592 * structures end with a newline (carriage return) character, and if
4593 * they don't it adds one.
4594 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004595 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004596 if (buf->b_fab_rfm == FAB$C_VFC
4597 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004598 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004599 int b2write;
4600
4601 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4602 ? MIN(4096, bufsize)
4603 : MIN(buf->b_fab_mrs, bufsize));
4604
4605 b2write = len;
4606 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004607 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004608 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4609 if (buf_write_bytes(&write_info) == FAIL)
4610 {
4611 end = 0;
4612 break;
4613 }
4614 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004615 }
4616 write_info.bw_len = bufsize;
4617 nchars += len;
4618 s = buffer;
4619 len = 0;
4620 }
4621#endif
4622 }
4623 if (len > 0 && end > 0)
4624 {
4625 write_info.bw_len = len;
4626 if (buf_write_bytes(&write_info) == FAIL)
4627 end = 0; /* write error */
4628 nchars += len;
4629 }
4630
4631#if defined(UNIX) && defined(HAVE_FSYNC)
4632 /* On many journalling file systems there is a bug that causes both the
4633 * original and the backup file to be lost when halting the system right
4634 * after writing the file. That's because only the meta-data is
4635 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004636 * been written to disk and we don't lose it.
4637 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004638 * (could be a pipe).
4639 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4640 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004641 {
4642 errmsg = (char_u *)_("E667: Fsync failed");
4643 end = 0;
4644 }
4645#endif
4646
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004647#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004648 /* Probably need to set the security context. */
4649 if (!backup_copy)
4650 mch_copy_sec(backup, wfname);
4651#endif
4652
Bram Moolenaara5792f52005-11-23 21:25:05 +00004653#ifdef UNIX
4654 /* When creating a new file, set its owner/group to that of the original
4655 * file. Get the new device and inode number. */
4656 if (backup != NULL && !backup_copy)
4657 {
4658# ifdef HAVE_FCHOWN
4659 struct stat st;
4660
4661 /* don't change the owner when it's already OK, some systems remove
4662 * permission or ACL stuff */
4663 if (mch_stat((char *)wfname, &st) < 0
4664 || st.st_uid != st_old.st_uid
4665 || st.st_gid != st_old.st_gid)
4666 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004667 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004668 if (perm >= 0) /* set permission again, may have changed */
4669 (void)mch_setperm(wfname, perm);
4670 }
4671# endif
4672 buf_setino(buf);
4673 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004674 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004675 /* Set the inode when creating a new file. */
4676 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004677#endif
4678
Bram Moolenaar071d4272004-06-13 20:20:40 +00004679 if (close(fd) != 0)
4680 {
4681 errmsg = (char_u *)_("E512: Close failed");
4682 end = 0;
4683 }
4684
4685#ifdef UNIX
4686 if (made_writable)
4687 perm &= ~0200; /* reset 'w' bit for security reasons */
4688#endif
4689 if (perm >= 0) /* set perm. of new file same as old file */
4690 (void)mch_setperm(wfname, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004691#ifdef HAVE_ACL
4692 /* Probably need to set the ACL before changing the user (can't set the
4693 * ACL on a file the user doesn't own). */
4694 if (!backup_copy)
4695 mch_set_acl(wfname, acl);
4696#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004697#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004698 if (buf->b_cryptstate != NULL)
4699 {
4700 crypt_free_state(buf->b_cryptstate);
4701 buf->b_cryptstate = NULL;
4702 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004703#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004704
Bram Moolenaar071d4272004-06-13 20:20:40 +00004705#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4706 if (wfname != fname)
4707 {
4708 /*
4709 * The file was written to a temp file, now it needs to be converted
4710 * with 'charconvert' to (overwrite) the output file.
4711 */
4712 if (end != 0)
4713 {
4714 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4715 wfname, fname) == FAIL)
4716 {
4717 write_info.bw_conv_error = TRUE;
4718 end = 0;
4719 }
4720 }
4721 mch_remove(wfname);
4722 vim_free(wfname);
4723 }
4724#endif
4725
4726 if (end == 0)
4727 {
4728 if (errmsg == NULL)
4729 {
4730#ifdef FEAT_MBYTE
4731 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004732 {
4733 if (write_info.bw_conv_error_lnum == 0)
4734 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4735 else
4736 {
4737 errmsg_allocated = TRUE;
4738 errmsg = alloc(300);
4739 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4740 (long)write_info.bw_conv_error_lnum);
4741 }
4742 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743 else
4744#endif
4745 if (got_int)
4746 errmsg = (char_u *)_(e_interr);
4747 else
4748 errmsg = (char_u *)_("E514: write error (file system full?)");
4749 }
4750
4751 /*
4752 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004753 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004754 * original file when trying to make a backup when writing the file a
4755 * second time.
4756 * When "backup_copy" is set we need to copy the backup over the new
4757 * file. Otherwise rename the backup file.
4758 * If this is OK, don't give the extra warning message.
4759 */
4760 if (backup != NULL)
4761 {
4762 if (backup_copy)
4763 {
4764 /* This may take a while, if we were interrupted let the user
4765 * know we got the message. */
4766 if (got_int)
4767 {
4768 MSG(_(e_interr));
4769 out_flush();
4770 }
4771 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4772 {
4773 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004774 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4775 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004776 {
4777 /* copy the file. */
4778 write_info.bw_buf = smallbuf;
4779#ifdef HAS_BW_FLAGS
4780 write_info.bw_flags = FIO_NOCONVERT;
4781#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004782 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004783 SMBUFSIZE)) > 0)
4784 if (buf_write_bytes(&write_info) == FAIL)
4785 break;
4786
4787 if (close(write_info.bw_fd) >= 0
4788 && write_info.bw_len == 0)
4789 end = 1; /* success */
4790 }
4791 close(fd); /* ignore errors for closing read file */
4792 }
4793 }
4794 else
4795 {
4796 if (vim_rename(backup, fname) == 0)
4797 end = 1;
4798 }
4799 }
4800 goto fail;
4801 }
4802
4803 lnum -= start; /* compute number of written lines */
4804 --no_wait_return; /* may wait for return now */
4805
4806#if !(defined(UNIX) || defined(VMS))
4807 fname = sfname; /* use shortname now, for the messages */
4808#endif
4809 if (!filtering)
4810 {
4811 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4812 c = FALSE;
4813#ifdef FEAT_MBYTE
4814 if (write_info.bw_conv_error)
4815 {
4816 STRCAT(IObuff, _(" CONVERSION ERROR"));
4817 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004818 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004819 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004820 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004821 }
4822 else if (notconverted)
4823 {
4824 STRCAT(IObuff, _("[NOT converted]"));
4825 c = TRUE;
4826 }
4827 else if (converted)
4828 {
4829 STRCAT(IObuff, _("[converted]"));
4830 c = TRUE;
4831 }
4832#endif
4833 if (device)
4834 {
4835 STRCAT(IObuff, _("[Device]"));
4836 c = TRUE;
4837 }
4838 else if (newfile)
4839 {
4840 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4841 c = TRUE;
4842 }
4843 if (no_eol)
4844 {
4845 msg_add_eol();
4846 c = TRUE;
4847 }
4848 /* may add [unix/dos/mac] */
4849 if (msg_add_fileformat(fileformat))
4850 c = TRUE;
4851#ifdef FEAT_CRYPT
4852 if (wb_flags & FIO_ENCRYPTED)
4853 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004854 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 c = TRUE;
4856 }
4857#endif
4858 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4859 if (!shortmess(SHM_WRITE))
4860 {
4861 if (append)
4862 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4863 else
4864 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4865 }
4866
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004867 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868 }
4869
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004870 /* When written everything correctly: reset 'modified'. Unless not
4871 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004872 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873#ifdef FEAT_MBYTE
4874 && !write_info.bw_conv_error
4875#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004876 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4877 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878 {
4879 unchanged(buf, TRUE);
Bram Moolenaar086329d2014-10-31 19:51:36 +01004880#ifdef FEAT_AUTOCMD
4881 /* buf->b_changedtick is always incremented in unchanged() but that
4882 * should not trigger a TextChanged event. */
4883 if (last_changedtick + 1 == buf->b_changedtick
4884 && last_changedtick_buf == buf)
4885 last_changedtick = buf->b_changedtick;
4886#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004887 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004888 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004889 }
4890
4891 /*
4892 * If written to the current file, update the timestamp of the swap file
4893 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4894 */
4895 if (overwriting)
4896 {
4897 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004898 if (append)
4899 buf->b_flags &= ~BF_NEW;
4900 else
4901 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004902 }
4903
4904 /*
4905 * If we kept a backup until now, and we are in patch mode, then we make
4906 * the backup file our 'original' file.
4907 */
4908 if (*p_pm && dobackup)
4909 {
4910 char *org = (char *)buf_modname(
4911#ifdef SHORT_FNAME
4912 TRUE,
4913#else
4914 (buf->b_p_sn || buf->b_shortname),
4915#endif
4916 fname, p_pm, FALSE);
4917
4918 if (backup != NULL)
4919 {
4920 struct stat st;
4921
4922 /*
4923 * If the original file does not exist yet
4924 * the current backup file becomes the original file
4925 */
4926 if (org == NULL)
4927 EMSG(_("E205: Patchmode: can't save original file"));
4928 else if (mch_stat(org, &st) < 0)
4929 {
4930 vim_rename(backup, (char_u *)org);
4931 vim_free(backup); /* don't delete the file */
4932 backup = NULL;
4933#ifdef UNIX
4934 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4935#endif
4936 }
4937 }
4938 /*
4939 * If there is no backup file, remember that a (new) file was
4940 * created.
4941 */
4942 else
4943 {
4944 int empty_fd;
4945
4946 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004947 || (empty_fd = mch_open(org,
4948 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004949 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004950 EMSG(_("E206: patchmode: can't touch empty original file"));
4951 else
4952 close(empty_fd);
4953 }
4954 if (org != NULL)
4955 {
4956 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4957 vim_free(org);
4958 }
4959 }
4960
4961 /*
4962 * Remove the backup unless 'backup' option is set
4963 */
4964 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4965 EMSG(_("E207: Can't delete backup file"));
4966
4967#ifdef FEAT_SUN_WORKSHOP
4968 if (usingSunWorkShop)
4969 workshop_file_saved((char *) ffname);
4970#endif
4971
4972 goto nofail;
4973
4974 /*
4975 * Finish up. We get here either after failure or success.
4976 */
4977fail:
4978 --no_wait_return; /* may wait for return now */
4979nofail:
4980
4981 /* Done saving, we accept changed buffer warnings again */
4982 buf->b_saving = FALSE;
4983
4984 vim_free(backup);
4985 if (buffer != smallbuf)
4986 vim_free(buffer);
4987#ifdef FEAT_MBYTE
4988 vim_free(fenc_tofree);
4989 vim_free(write_info.bw_conv_buf);
4990# ifdef USE_ICONV
4991 if (write_info.bw_iconv_fd != (iconv_t)-1)
4992 {
4993 iconv_close(write_info.bw_iconv_fd);
4994 write_info.bw_iconv_fd = (iconv_t)-1;
4995 }
4996# endif
4997#endif
4998#ifdef HAVE_ACL
4999 mch_free_acl(acl);
5000#endif
5001
5002 if (errmsg != NULL)
5003 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005004 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005005
5006 attr = hl_attr(HLF_E); /* set highlight for error messages */
5007 msg_add_fname(buf,
5008#ifndef UNIX
5009 sfname
5010#else
5011 fname
5012#endif
5013 ); /* put file name in IObuff with quotes */
5014 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5015 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5016 /* If the error message has the form "is ...", put the error number in
5017 * front of the file name. */
5018 if (errnum != NULL)
5019 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005020 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021 mch_memmove(IObuff, errnum, (size_t)numlen);
5022 }
5023 STRCAT(IObuff, errmsg);
5024 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005025 if (errmsg_allocated)
5026 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005027
5028 retval = FAIL;
5029 if (end == 0)
5030 {
5031 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5032 attr | MSG_HIST);
5033 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5034 attr | MSG_HIST);
5035
5036 /* Update the timestamp to avoid an "overwrite changed file"
5037 * prompt when writing again. */
5038 if (mch_stat((char *)fname, &st_old) >= 0)
5039 {
5040 buf_store_time(buf, &st_old, fname);
5041 buf->b_mtime_read = buf->b_mtime;
5042 }
5043 }
5044 }
5045 msg_scroll = msg_save;
5046
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005047#ifdef FEAT_PERSISTENT_UNDO
5048 /*
5049 * When writing the whole file and 'undofile' is set, also write the undo
5050 * file.
5051 */
5052 if (retval == OK && write_undo_file)
5053 {
5054 char_u hash[UNDO_HASH_SIZE];
5055
5056 sha256_finish(&sha_ctx, hash);
5057 u_write_undo(NULL, FALSE, buf, hash);
5058 }
5059#endif
5060
Bram Moolenaar071d4272004-06-13 20:20:40 +00005061#ifdef FEAT_AUTOCMD
5062#ifdef FEAT_EVAL
5063 if (!should_abort(retval))
5064#else
5065 if (!got_int)
5066#endif
5067 {
5068 aco_save_T aco;
5069
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005070 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5071
Bram Moolenaar071d4272004-06-13 20:20:40 +00005072 /*
5073 * Apply POST autocommands.
5074 * Careful: The autocommands may call buf_write() recursively!
5075 */
5076 aucmd_prepbuf(&aco, buf);
5077
5078 if (append)
5079 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5080 FALSE, curbuf, eap);
5081 else if (filtering)
5082 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5083 FALSE, curbuf, eap);
5084 else if (reset_changed && whole)
5085 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5086 FALSE, curbuf, eap);
5087 else
5088 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5089 FALSE, curbuf, eap);
5090
5091 /* restore curwin/curbuf and a few other things */
5092 aucmd_restbuf(&aco);
5093
5094#ifdef FEAT_EVAL
5095 if (aborting()) /* autocmds may abort script processing */
5096 retval = FALSE;
5097#endif
5098 }
5099#endif
5100
5101 got_int |= prev_got_int;
5102
5103#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5104 /* Update machine specific information. */
5105 mch_post_buffer_write(buf);
5106#endif
5107 return retval;
5108}
5109
5110/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005111 * Set the name of the current buffer. Use when the buffer doesn't have a
5112 * name and a ":r" or ":w" command with a file name is used.
5113 */
5114 static int
5115set_rw_fname(fname, sfname)
5116 char_u *fname;
5117 char_u *sfname;
5118{
5119#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005120 buf_T *buf = curbuf;
5121
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005122 /* It's like the unnamed buffer is deleted.... */
5123 if (curbuf->b_p_bl)
5124 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5125 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5126# ifdef FEAT_EVAL
5127 if (aborting()) /* autocmds may abort script processing */
5128 return FAIL;
5129# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005130 if (curbuf != buf)
5131 {
5132 /* We are in another buffer now, don't do the renaming. */
5133 EMSG(_(e_auchangedbuf));
5134 return FAIL;
5135 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005136#endif
5137
5138 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5139 curbuf->b_flags |= BF_NOTEDITED;
5140
5141#ifdef FEAT_AUTOCMD
5142 /* ....and a new named one is created */
5143 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5144 if (curbuf->b_p_bl)
5145 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5146# ifdef FEAT_EVAL
5147 if (aborting()) /* autocmds may abort script processing */
5148 return FAIL;
5149# endif
5150
5151 /* Do filetype detection now if 'filetype' is empty. */
5152 if (*curbuf->b_p_ft == NUL)
5153 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005154 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005155 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005156 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005157 }
5158#endif
5159
5160 return OK;
5161}
5162
5163/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005164 * Put file name into IObuff with quotes.
5165 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005166 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005167msg_add_fname(buf, fname)
5168 buf_T *buf;
5169 char_u *fname;
5170{
5171 if (fname == NULL)
5172 fname = (char_u *)"-stdin-";
5173 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5174 IObuff[0] = '"';
5175 STRCAT(IObuff, "\" ");
5176}
5177
5178/*
5179 * Append message for text mode to IObuff.
5180 * Return TRUE if something appended.
5181 */
5182 static int
5183msg_add_fileformat(eol_type)
5184 int eol_type;
5185{
5186#ifndef USE_CRNL
5187 if (eol_type == EOL_DOS)
5188 {
5189 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5190 return TRUE;
5191 }
5192#endif
5193#ifndef USE_CR
5194 if (eol_type == EOL_MAC)
5195 {
5196 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5197 return TRUE;
5198 }
5199#endif
5200#if defined(USE_CRNL) || defined(USE_CR)
5201 if (eol_type == EOL_UNIX)
5202 {
5203 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5204 return TRUE;
5205 }
5206#endif
5207 return FALSE;
5208}
5209
5210/*
5211 * Append line and character count to IObuff.
5212 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005213 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005214msg_add_lines(insert_space, lnum, nchars)
5215 int insert_space;
5216 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005217 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005218{
5219 char_u *p;
5220
5221 p = IObuff + STRLEN(IObuff);
5222
5223 if (insert_space)
5224 *p++ = ' ';
5225 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005226 sprintf((char *)p,
5227#ifdef LONG_LONG_OFF_T
Bram Moolenaar581966e2014-02-23 22:58:17 +01005228 "%ldL, %lldC", lnum, (long long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005229#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005230 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5231 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005232#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005233 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005234 else
5235 {
5236 if (lnum == 1)
5237 STRCPY(p, _("1 line, "));
5238 else
5239 sprintf((char *)p, _("%ld lines, "), lnum);
5240 p += STRLEN(p);
5241 if (nchars == 1)
5242 STRCPY(p, _("1 character"));
5243 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005244 sprintf((char *)p,
5245#ifdef LONG_LONG_OFF_T
Bram Moolenaar581966e2014-02-23 22:58:17 +01005246 _("%lld characters"), (long long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005247#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005248 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5249 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005250#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005251 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005252 }
5253}
5254
5255/*
5256 * Append message for missing line separator to IObuff.
5257 */
5258 static void
5259msg_add_eol()
5260{
5261 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5262}
5263
5264/*
5265 * Check modification time of file, before writing to it.
5266 * The size isn't checked, because using a tool like "gzip" takes care of
5267 * using the same timestamp but can't set the size.
5268 */
5269 static int
5270check_mtime(buf, st)
5271 buf_T *buf;
5272 struct stat *st;
5273{
5274 if (buf->b_mtime_read != 0
5275 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5276 {
5277 msg_scroll = TRUE; /* don't overwrite messages here */
5278 msg_silent = 0; /* must give this prompt */
5279 /* don't use emsg() here, don't want to flush the buffers */
5280 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5281 hl_attr(HLF_E));
5282 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5283 TRUE) == 'n')
5284 return FAIL;
5285 msg_scroll = FALSE; /* always overwrite the file message now */
5286 }
5287 return OK;
5288}
5289
5290 static int
5291time_differs(t1, t2)
5292 long t1, t2;
5293{
5294#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5295 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5296 * the seconds. Since the roundoff is done when flushing the inode, the
5297 * time may change unexpectedly by one second!!! */
5298 return (t1 - t2 > 1 || t2 - t1 > 1);
5299#else
5300 return (t1 != t2);
5301#endif
5302}
5303
5304/*
5305 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005306 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005307 *
5308 * Return FAIL for failure, OK otherwise.
5309 */
5310 static int
5311buf_write_bytes(ip)
5312 struct bw_info *ip;
5313{
5314 int wlen;
5315 char_u *buf = ip->bw_buf; /* data to write */
5316 int len = ip->bw_len; /* length of data */
5317#ifdef HAS_BW_FLAGS
5318 int flags = ip->bw_flags; /* extra flags */
5319#endif
5320
5321#ifdef FEAT_MBYTE
5322 /*
5323 * Skip conversion when writing the crypt magic number or the BOM.
5324 */
5325 if (!(flags & FIO_NOCONVERT))
5326 {
5327 char_u *p;
5328 unsigned c;
5329 int n;
5330
5331 if (flags & FIO_UTF8)
5332 {
5333 /*
5334 * Convert latin1 in the buffer to UTF-8 in the file.
5335 */
5336 p = ip->bw_conv_buf; /* translate to buffer */
5337 for (wlen = 0; wlen < len; ++wlen)
5338 p += utf_char2bytes(buf[wlen], p);
5339 buf = ip->bw_conv_buf;
5340 len = (int)(p - ip->bw_conv_buf);
5341 }
5342 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5343 {
5344 /*
5345 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5346 * Latin1 chars in the file.
5347 */
5348 if (flags & FIO_LATIN1)
5349 p = buf; /* translate in-place (can only get shorter) */
5350 else
5351 p = ip->bw_conv_buf; /* translate to buffer */
5352 for (wlen = 0; wlen < len; wlen += n)
5353 {
5354 if (wlen == 0 && ip->bw_restlen != 0)
5355 {
5356 int l;
5357
5358 /* Use remainder of previous call. Append the start of
5359 * buf[] to get a full sequence. Might still be too
5360 * short! */
5361 l = CONV_RESTLEN - ip->bw_restlen;
5362 if (l > len)
5363 l = len;
5364 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005365 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005366 if (n > ip->bw_restlen + len)
5367 {
5368 /* We have an incomplete byte sequence at the end to
5369 * be written. We can't convert it without the
5370 * remaining bytes. Keep them for the next call. */
5371 if (ip->bw_restlen + len > CONV_RESTLEN)
5372 return FAIL;
5373 ip->bw_restlen += len;
5374 break;
5375 }
5376 if (n > 1)
5377 c = utf_ptr2char(ip->bw_rest);
5378 else
5379 c = ip->bw_rest[0];
5380 if (n >= ip->bw_restlen)
5381 {
5382 n -= ip->bw_restlen;
5383 ip->bw_restlen = 0;
5384 }
5385 else
5386 {
5387 ip->bw_restlen -= n;
5388 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5389 (size_t)ip->bw_restlen);
5390 n = 0;
5391 }
5392 }
5393 else
5394 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005395 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005396 if (n > len - wlen)
5397 {
5398 /* We have an incomplete byte sequence at the end to
5399 * be written. We can't convert it without the
5400 * remaining bytes. Keep them for the next call. */
5401 if (len - wlen > CONV_RESTLEN)
5402 return FAIL;
5403 ip->bw_restlen = len - wlen;
5404 mch_memmove(ip->bw_rest, buf + wlen,
5405 (size_t)ip->bw_restlen);
5406 break;
5407 }
5408 if (n > 1)
5409 c = utf_ptr2char(buf + wlen);
5410 else
5411 c = buf[wlen];
5412 }
5413
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005414 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5415 {
5416 ip->bw_conv_error = TRUE;
5417 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5418 }
5419 if (c == NL)
5420 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005421 }
5422 if (flags & FIO_LATIN1)
5423 len = (int)(p - buf);
5424 else
5425 {
5426 buf = ip->bw_conv_buf;
5427 len = (int)(p - ip->bw_conv_buf);
5428 }
5429 }
5430
5431# ifdef WIN3264
5432 else if (flags & FIO_CODEPAGE)
5433 {
5434 /*
5435 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5436 * codepage.
5437 */
5438 char_u *from;
5439 size_t fromlen;
5440 char_u *to;
5441 int u8c;
5442 BOOL bad = FALSE;
5443 int needed;
5444
5445 if (ip->bw_restlen > 0)
5446 {
5447 /* Need to concatenate the remainder of the previous call and
5448 * the bytes of the current call. Use the end of the
5449 * conversion buffer for this. */
5450 fromlen = len + ip->bw_restlen;
5451 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5452 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5453 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5454 }
5455 else
5456 {
5457 from = buf;
5458 fromlen = len;
5459 }
5460
5461 to = ip->bw_conv_buf;
5462 if (enc_utf8)
5463 {
5464 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5465 * The buffer has been allocated to be big enough. */
5466 while (fromlen > 0)
5467 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005468 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005469 if (n > (int)fromlen) /* incomplete byte sequence */
5470 break;
5471 u8c = utf_ptr2char(from);
5472 *to++ = (u8c & 0xff);
5473 *to++ = (u8c >> 8);
5474 fromlen -= n;
5475 from += n;
5476 }
5477
5478 /* Copy remainder to ip->bw_rest[] to be used for the next
5479 * call. */
5480 if (fromlen > CONV_RESTLEN)
5481 {
5482 /* weird overlong sequence */
5483 ip->bw_conv_error = TRUE;
5484 return FAIL;
5485 }
5486 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005487 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005488 }
5489 else
5490 {
5491 /* Convert from enc_codepage to UCS-2, to the start of the
5492 * buffer. The buffer has been allocated to be big enough. */
5493 ip->bw_restlen = 0;
5494 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005495 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005496 NULL, 0);
5497 if (needed == 0)
5498 {
5499 /* When conversion fails there may be a trailing byte. */
5500 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005501 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005502 NULL, 0);
5503 if (needed == 0)
5504 {
5505 /* Conversion doesn't work. */
5506 ip->bw_conv_error = TRUE;
5507 return FAIL;
5508 }
5509 /* Save the trailing byte for the next call. */
5510 ip->bw_rest[0] = from[fromlen - 1];
5511 ip->bw_restlen = 1;
5512 }
5513 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005514 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 (LPWSTR)to, needed);
5516 if (needed == 0)
5517 {
5518 /* Safety check: Conversion doesn't work. */
5519 ip->bw_conv_error = TRUE;
5520 return FAIL;
5521 }
5522 to += needed * 2;
5523 }
5524
5525 fromlen = to - ip->bw_conv_buf;
5526 buf = to;
5527# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5528 if (FIO_GET_CP(flags) == CP_UTF8)
5529 {
5530 /* Convert from UCS-2 to UTF-8, using the remainder of the
5531 * conversion buffer. Fails when out of space. */
5532 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5533 {
5534 u8c = *from++;
5535 u8c += (*from++ << 8);
5536 to += utf_char2bytes(u8c, to);
5537 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5538 {
5539 ip->bw_conv_error = TRUE;
5540 return FAIL;
5541 }
5542 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005543 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005544 }
5545 else
5546#endif
5547 {
5548 /* Convert from UCS-2 to the codepage, using the remainder of
5549 * the conversion buffer. If the conversion uses the default
5550 * character "0", the data doesn't fit in this encoding, so
5551 * fail. */
5552 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5553 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005554 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5555 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005556 if (bad)
5557 {
5558 ip->bw_conv_error = TRUE;
5559 return FAIL;
5560 }
5561 }
5562 }
5563# endif
5564
Bram Moolenaar56718732006-03-15 22:53:57 +00005565# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005566 else if (flags & FIO_MACROMAN)
5567 {
5568 /*
5569 * Convert UTF-8 or latin1 to Apple MacRoman.
5570 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571 char_u *from;
5572 size_t fromlen;
5573
5574 if (ip->bw_restlen > 0)
5575 {
5576 /* Need to concatenate the remainder of the previous call and
5577 * the bytes of the current call. Use the end of the
5578 * conversion buffer for this. */
5579 fromlen = len + ip->bw_restlen;
5580 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5581 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5582 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5583 }
5584 else
5585 {
5586 from = buf;
5587 fromlen = len;
5588 }
5589
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005590 if (enc2macroman(from, fromlen,
5591 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5592 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 {
5594 ip->bw_conv_error = TRUE;
5595 return FAIL;
5596 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005597 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 }
5599# endif
5600
5601# ifdef USE_ICONV
5602 if (ip->bw_iconv_fd != (iconv_t)-1)
5603 {
5604 const char *from;
5605 size_t fromlen;
5606 char *to;
5607 size_t tolen;
5608
5609 /* Convert with iconv(). */
5610 if (ip->bw_restlen > 0)
5611 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005612 char *fp;
5613
Bram Moolenaar071d4272004-06-13 20:20:40 +00005614 /* Need to concatenate the remainder of the previous call and
5615 * the bytes of the current call. Use the end of the
5616 * conversion buffer for this. */
5617 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005618 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5619 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5620 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5621 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005622 tolen = ip->bw_conv_buflen - fromlen;
5623 }
5624 else
5625 {
5626 from = (const char *)buf;
5627 fromlen = len;
5628 tolen = ip->bw_conv_buflen;
5629 }
5630 to = (char *)ip->bw_conv_buf;
5631
5632 if (ip->bw_first)
5633 {
5634 size_t save_len = tolen;
5635
5636 /* output the initial shift state sequence */
5637 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5638
5639 /* There is a bug in iconv() on Linux (which appears to be
5640 * wide-spread) which sets "to" to NULL and messes up "tolen".
5641 */
5642 if (to == NULL)
5643 {
5644 to = (char *)ip->bw_conv_buf;
5645 tolen = save_len;
5646 }
5647 ip->bw_first = FALSE;
5648 }
5649
5650 /*
5651 * If iconv() has an error or there is not enough room, fail.
5652 */
5653 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5654 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5655 || fromlen > CONV_RESTLEN)
5656 {
5657 ip->bw_conv_error = TRUE;
5658 return FAIL;
5659 }
5660
5661 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5662 if (fromlen > 0)
5663 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5664 ip->bw_restlen = (int)fromlen;
5665
5666 buf = ip->bw_conv_buf;
5667 len = (int)((char_u *)to - ip->bw_conv_buf);
5668 }
5669# endif
5670 }
5671#endif /* FEAT_MBYTE */
5672
5673#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005674 if (flags & FIO_ENCRYPTED)
5675 {
5676 /* Encrypt the data. Do it in-place if possible, otherwise use an
5677 * allocated buffer. */
5678 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5679 {
5680 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
5681 }
5682 else
5683 {
5684 char_u *outbuf;
5685
5686 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5687 if (len == 0)
5688 return OK; /* Crypt layer is buffering, will flush later. */
5689 wlen = write_eintr(ip->bw_fd, outbuf, len);
5690 vim_free(outbuf);
5691 return (wlen < len) ? FAIL : OK;
5692 }
5693 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005694#endif
5695
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005696 wlen = write_eintr(ip->bw_fd, buf, len);
5697 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005698}
5699
5700#ifdef FEAT_MBYTE
5701/*
5702 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005703 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005704 */
5705 static int
5706ucs2bytes(c, pp, flags)
5707 unsigned c; /* in: character */
5708 char_u **pp; /* in/out: pointer to result */
5709 int flags; /* FIO_ flags */
5710{
5711 char_u *p = *pp;
5712 int error = FALSE;
5713 int cc;
5714
5715
5716 if (flags & FIO_UCS4)
5717 {
5718 if (flags & FIO_ENDIAN_L)
5719 {
5720 *p++ = c;
5721 *p++ = (c >> 8);
5722 *p++ = (c >> 16);
5723 *p++ = (c >> 24);
5724 }
5725 else
5726 {
5727 *p++ = (c >> 24);
5728 *p++ = (c >> 16);
5729 *p++ = (c >> 8);
5730 *p++ = c;
5731 }
5732 }
5733 else if (flags & (FIO_UCS2 | FIO_UTF16))
5734 {
5735 if (c >= 0x10000)
5736 {
5737 if (flags & FIO_UTF16)
5738 {
5739 /* Make two words, ten bits of the character in each. First
5740 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5741 c -= 0x10000;
5742 if (c >= 0x100000)
5743 error = TRUE;
5744 cc = ((c >> 10) & 0x3ff) + 0xd800;
5745 if (flags & FIO_ENDIAN_L)
5746 {
5747 *p++ = cc;
5748 *p++ = ((unsigned)cc >> 8);
5749 }
5750 else
5751 {
5752 *p++ = ((unsigned)cc >> 8);
5753 *p++ = cc;
5754 }
5755 c = (c & 0x3ff) + 0xdc00;
5756 }
5757 else
5758 error = TRUE;
5759 }
5760 if (flags & FIO_ENDIAN_L)
5761 {
5762 *p++ = c;
5763 *p++ = (c >> 8);
5764 }
5765 else
5766 {
5767 *p++ = (c >> 8);
5768 *p++ = c;
5769 }
5770 }
5771 else /* Latin1 */
5772 {
5773 if (c >= 0x100)
5774 {
5775 error = TRUE;
5776 *p++ = 0xBF;
5777 }
5778 else
5779 *p++ = c;
5780 }
5781
5782 *pp = p;
5783 return error;
5784}
5785
5786/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005787 * Return TRUE if file encoding "fenc" requires conversion from or to
5788 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005789 */
5790 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005791need_conversion(fenc)
5792 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005793{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005794 int same_encoding;
5795 int enc_flags;
5796 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005797
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005798 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005799 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005800 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005801 fenc_flags = 0;
5802 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005803 else
5804 {
5805 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5806 * "ucs-4be", etc. */
5807 enc_flags = get_fio_flags(p_enc);
5808 fenc_flags = get_fio_flags(fenc);
5809 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5810 }
5811 if (same_encoding)
5812 {
5813 /* Specified encoding matches with 'encoding'. This requires
5814 * conversion when 'encoding' is Unicode but not UTF-8. */
5815 return enc_unicode != 0;
5816 }
5817
5818 /* Encodings differ. However, conversion is not needed when 'enc' is any
5819 * Unicode encoding and the file is UTF-8. */
5820 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005821}
5822
5823/*
5824 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5825 * internal conversion.
5826 * if "ptr" is an empty string, use 'encoding'.
5827 */
5828 static int
5829get_fio_flags(ptr)
5830 char_u *ptr;
5831{
5832 int prop;
5833
5834 if (*ptr == NUL)
5835 ptr = p_enc;
5836
5837 prop = enc_canon_props(ptr);
5838 if (prop & ENC_UNICODE)
5839 {
5840 if (prop & ENC_2BYTE)
5841 {
5842 if (prop & ENC_ENDIAN_L)
5843 return FIO_UCS2 | FIO_ENDIAN_L;
5844 return FIO_UCS2;
5845 }
5846 if (prop & ENC_4BYTE)
5847 {
5848 if (prop & ENC_ENDIAN_L)
5849 return FIO_UCS4 | FIO_ENDIAN_L;
5850 return FIO_UCS4;
5851 }
5852 if (prop & ENC_2WORD)
5853 {
5854 if (prop & ENC_ENDIAN_L)
5855 return FIO_UTF16 | FIO_ENDIAN_L;
5856 return FIO_UTF16;
5857 }
5858 return FIO_UTF8;
5859 }
5860 if (prop & ENC_LATIN1)
5861 return FIO_LATIN1;
5862 /* must be ENC_DBCS, requires iconv() */
5863 return 0;
5864}
5865
5866#ifdef WIN3264
5867/*
5868 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5869 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5870 * Used for conversion between 'encoding' and 'fileencoding'.
5871 */
5872 static int
5873get_win_fio_flags(ptr)
5874 char_u *ptr;
5875{
5876 int cp;
5877
5878 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5879 if (!enc_utf8 && enc_codepage <= 0)
5880 return 0;
5881
5882 cp = encname2codepage(ptr);
5883 if (cp == 0)
5884 {
5885# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5886 if (STRCMP(ptr, "utf-8") == 0)
5887 cp = CP_UTF8;
5888 else
5889# endif
5890 return 0;
5891 }
5892 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5893}
5894#endif
5895
5896#ifdef MACOS_X
5897/*
5898 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5899 * needed for the internal conversion to/from utf-8 or latin1.
5900 */
5901 static int
5902get_mac_fio_flags(ptr)
5903 char_u *ptr;
5904{
5905 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5906 && (enc_canon_props(ptr) & ENC_MACROMAN))
5907 return FIO_MACROMAN;
5908 return 0;
5909}
5910#endif
5911
5912/*
5913 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5914 * "size" must be at least 2.
5915 * Return the name of the encoding and set "*lenp" to the length.
5916 * Returns NULL when no BOM found.
5917 */
5918 static char_u *
5919check_for_bom(p, size, lenp, flags)
5920 char_u *p;
5921 long size;
5922 int *lenp;
5923 int flags;
5924{
5925 char *name = NULL;
5926 int len = 2;
5927
5928 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005929 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005930 {
5931 name = "utf-8"; /* EF BB BF */
5932 len = 3;
5933 }
5934 else if (p[0] == 0xff && p[1] == 0xfe)
5935 {
5936 if (size >= 4 && p[2] == 0 && p[3] == 0
5937 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5938 {
5939 name = "ucs-4le"; /* FF FE 00 00 */
5940 len = 4;
5941 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005942 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005943 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005944 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5945 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005946 name = "utf-16le"; /* FF FE */
5947 }
5948 else if (p[0] == 0xfe && p[1] == 0xff
5949 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5950 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005951 /* Default to utf-16, it works also for ucs-2 text. */
5952 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005953 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005954 else
5955 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005956 }
5957 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5958 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5959 {
5960 name = "ucs-4"; /* 00 00 FE FF */
5961 len = 4;
5962 }
5963
5964 *lenp = len;
5965 return (char_u *)name;
5966}
5967
5968/*
5969 * Generate a BOM in "buf[4]" for encoding "name".
5970 * Return the length of the BOM (zero when no BOM).
5971 */
5972 static int
5973make_bom(buf, name)
5974 char_u *buf;
5975 char_u *name;
5976{
5977 int flags;
5978 char_u *p;
5979
5980 flags = get_fio_flags(name);
5981
5982 /* Can't put a BOM in a non-Unicode file. */
5983 if (flags == FIO_LATIN1 || flags == 0)
5984 return 0;
5985
5986 if (flags == FIO_UTF8) /* UTF-8 */
5987 {
5988 buf[0] = 0xef;
5989 buf[1] = 0xbb;
5990 buf[2] = 0xbf;
5991 return 3;
5992 }
5993 p = buf;
5994 (void)ucs2bytes(0xfeff, &p, flags);
5995 return (int)(p - buf);
5996}
5997#endif
5998
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00005999#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006000 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006001/*
6002 * Try to find a shortname by comparing the fullname with the current
6003 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006004 * Returns "full_path" or pointer into "full_path" if shortened.
6005 */
6006 char_u *
6007shorten_fname1(full_path)
6008 char_u *full_path;
6009{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006010 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006011 char_u *p = full_path;
6012
Bram Moolenaard9462e32011-04-11 21:35:11 +02006013 dirname = alloc(MAXPATHL);
6014 if (dirname == NULL)
6015 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006016 if (mch_dirname(dirname, MAXPATHL) == OK)
6017 {
6018 p = shorten_fname(full_path, dirname);
6019 if (p == NULL || *p == NUL)
6020 p = full_path;
6021 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006022 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006023 return p;
6024}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006025#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006026
6027/*
6028 * Try to find a shortname by comparing the fullname with the current
6029 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006030 * Returns NULL if not shorter name possible, pointer into "full_path"
6031 * otherwise.
6032 */
6033 char_u *
6034shorten_fname(full_path, dir_name)
6035 char_u *full_path;
6036 char_u *dir_name;
6037{
6038 int len;
6039 char_u *p;
6040
6041 if (full_path == NULL)
6042 return NULL;
6043 len = (int)STRLEN(dir_name);
6044 if (fnamencmp(dir_name, full_path, len) == 0)
6045 {
6046 p = full_path + len;
6047#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6048 /*
6049 * MSDOS: when a file is in the root directory, dir_name will end in a
6050 * slash, since C: by itself does not define a specific dir. In this
6051 * case p may already be correct. <negri>
6052 */
6053 if (!((len > 2) && (*(p - 2) == ':')))
6054#endif
6055 {
6056 if (vim_ispathsep(*p))
6057 ++p;
6058#ifndef VMS /* the path separator is always part of the path */
6059 else
6060 p = NULL;
6061#endif
6062 }
6063 }
6064#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6065 /*
6066 * When using a file in the current drive, remove the drive name:
6067 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6068 * a floppy from "A:\dir" to "B:\dir".
6069 */
6070 else if (len > 3
6071 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6072 && full_path[1] == ':'
6073 && vim_ispathsep(full_path[2]))
6074 p = full_path + 2;
6075#endif
6076 else
6077 p = NULL;
6078 return p;
6079}
6080
6081/*
6082 * Shorten filenames for all buffers.
6083 * When "force" is TRUE: Use full path from now on for files currently being
6084 * edited, both for file name and swap file name. Try to shorten the file
6085 * names a bit, if safe to do so.
6086 * When "force" is FALSE: Only try to shorten absolute file names.
6087 * For buffers that have buftype "nofile" or "scratch": never change the file
6088 * name.
6089 */
6090 void
6091shorten_fnames(force)
6092 int force;
6093{
6094 char_u dirname[MAXPATHL];
6095 buf_T *buf;
6096 char_u *p;
6097
6098 mch_dirname(dirname, MAXPATHL);
6099 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6100 {
6101 if (buf->b_fname != NULL
6102#ifdef FEAT_QUICKFIX
6103 && !bt_nofile(buf)
6104#endif
6105 && !path_with_url(buf->b_fname)
6106 && (force
6107 || buf->b_sfname == NULL
6108 || mch_isFullName(buf->b_sfname)))
6109 {
6110 vim_free(buf->b_sfname);
6111 buf->b_sfname = NULL;
6112 p = shorten_fname(buf->b_ffname, dirname);
6113 if (p != NULL)
6114 {
6115 buf->b_sfname = vim_strsave(p);
6116 buf->b_fname = buf->b_sfname;
6117 }
6118 if (p == NULL || buf->b_fname == NULL)
6119 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006120 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006121
6122 /* Always make the swap file name a full path, a "nofile" buffer may
6123 * also have a swap file. */
6124 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125 }
6126#ifdef FEAT_WINDOWS
6127 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006128 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006129#endif
6130}
6131
6132#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6133 || defined(FEAT_GUI_MSWIN) \
6134 || defined(FEAT_GUI_MAC) \
6135 || defined(PROTO)
6136/*
6137 * Shorten all filenames in "fnames[count]" by current directory.
6138 */
6139 void
6140shorten_filenames(fnames, count)
6141 char_u **fnames;
6142 int count;
6143{
6144 int i;
6145 char_u dirname[MAXPATHL];
6146 char_u *p;
6147
6148 if (fnames == NULL || count < 1)
6149 return;
6150 mch_dirname(dirname, sizeof(dirname));
6151 for (i = 0; i < count; ++i)
6152 {
6153 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6154 {
6155 /* shorten_fname() returns pointer in given "fnames[i]". If free
6156 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6157 * "p" first then free fnames[i]. */
6158 p = vim_strsave(p);
6159 vim_free(fnames[i]);
6160 fnames[i] = p;
6161 }
6162 }
6163}
6164#endif
6165
6166/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006167 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006168 * fo_o_h.ext for MSDOS or when shortname option set.
6169 *
6170 * Assumed that fname is a valid name found in the filesystem we assure that
6171 * the return value is a different name and ends in 'ext'.
6172 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6173 * characters otherwise.
6174 * Space for the returned name is allocated, must be freed later.
6175 * Returns NULL when out of memory.
6176 */
6177 char_u *
6178modname(fname, ext, prepend_dot)
6179 char_u *fname, *ext;
6180 int prepend_dot; /* may prepend a '.' to file name */
6181{
6182 return buf_modname(
6183#ifdef SHORT_FNAME
6184 TRUE,
6185#else
6186 (curbuf->b_p_sn || curbuf->b_shortname),
6187#endif
6188 fname, ext, prepend_dot);
6189}
6190
6191 char_u *
6192buf_modname(shortname, fname, ext, prepend_dot)
6193 int shortname; /* use 8.3 file name */
6194 char_u *fname, *ext;
6195 int prepend_dot; /* may prepend a '.' to file name */
6196{
6197 char_u *retval;
6198 char_u *s;
6199 char_u *e;
6200 char_u *ptr;
6201 int fnamelen, extlen;
6202
6203 extlen = (int)STRLEN(ext);
6204
6205 /*
6206 * If there is no file name we must get the name of the current directory
6207 * (we need the full path in case :cd is used).
6208 */
6209 if (fname == NULL || *fname == NUL)
6210 {
6211 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6212 if (retval == NULL)
6213 return NULL;
6214 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6215 (fnamelen = (int)STRLEN(retval)) == 0)
6216 {
6217 vim_free(retval);
6218 return NULL;
6219 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006220 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006221 {
6222 retval[fnamelen++] = PATHSEP;
6223 retval[fnamelen] = NUL;
6224 }
6225#ifndef SHORT_FNAME
6226 prepend_dot = FALSE; /* nothing to prepend a dot to */
6227#endif
6228 }
6229 else
6230 {
6231 fnamelen = (int)STRLEN(fname);
6232 retval = alloc((unsigned)(fnamelen + extlen + 3));
6233 if (retval == NULL)
6234 return NULL;
6235 STRCPY(retval, fname);
6236#ifdef VMS
6237 vms_remove_version(retval); /* we do not need versions here */
6238#endif
6239 }
6240
6241 /*
6242 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6243 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6244 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6245 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6246 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006247 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006248 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 if (*ext == '.'
Bram Moolenaare60acc12011-05-10 16:41:25 +02006250#ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251 && (!USE_LONG_FNAME || shortname)
Bram Moolenaare60acc12011-05-10 16:41:25 +02006252#else
6253# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006254 && shortname
6255# endif
Bram Moolenaare60acc12011-05-10 16:41:25 +02006256#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 )
6258 if (*ptr == '.') /* replace '.' by '_' */
6259 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006261 {
6262 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006264 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006265 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006266
6267 /* the file name has at most BASENAMELEN characters. */
6268#ifndef SHORT_FNAME
6269 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6270 ptr[BASENAMELEN] = '\0';
6271#endif
6272
6273 s = ptr + STRLEN(ptr);
6274
6275 /*
6276 * For 8.3 file names we may have to reduce the length.
6277 */
6278#ifdef USE_LONG_FNAME
6279 if (!USE_LONG_FNAME || shortname)
6280#else
6281# ifndef SHORT_FNAME
6282 if (shortname)
6283# endif
6284#endif
6285 {
6286 /*
6287 * If there is no file name, or the file name ends in '/', and the
6288 * extension starts with '.', put a '_' before the dot, because just
6289 * ".ext" is invalid.
6290 */
6291 if (fname == NULL || *fname == NUL
6292 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6293 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006294 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006295 *s++ = '_';
6296 }
6297 /*
6298 * If the extension starts with '.', truncate the base name at 8
6299 * characters
6300 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006301 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006302 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006303 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006304 {
6305 s = ptr + 8;
6306 *s = '\0';
6307 }
6308 }
6309 /*
6310 * If the extension doesn't start with '.', and the file name
6311 * doesn't have an extension yet, append a '.'
6312 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006313 else if ((e = vim_strchr(ptr, '.')) == NULL)
6314 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 /*
6316 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006317 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 */
6319 else if ((int)STRLEN(e) + extlen > 4)
6320 s = e + 4 - extlen;
6321 }
6322#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6323 /*
6324 * If there is no file name, and the extension starts with '.', put a
6325 * '_' before the dot, because just ".ext" may be invalid if it's on a
6326 * FAT partition, and on HPFS it doesn't matter.
6327 */
6328 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6329 *s++ = '_';
6330#endif
6331
6332 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006333 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006334 * ext can start with '.' and cannot exceed 3 more characters.
6335 */
6336 STRCPY(s, ext);
6337
6338#ifndef SHORT_FNAME
6339 /*
6340 * Prepend the dot.
6341 */
Bram Moolenaare60acc12011-05-10 16:41:25 +02006342 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.'
Bram Moolenaar071d4272004-06-13 20:20:40 +00006343#ifdef USE_LONG_FNAME
6344 && USE_LONG_FNAME
6345#endif
6346 )
6347 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006348 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006349 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006350 }
6351#endif
6352
6353 /*
6354 * Check that, after appending the extension, the file name is really
6355 * different.
6356 */
6357 if (fname != NULL && STRCMP(fname, retval) == 0)
6358 {
6359 /* we search for a character that can be replaced by '_' */
6360 while (--s >= ptr)
6361 {
6362 if (*s != '_')
6363 {
6364 *s = '_';
6365 break;
6366 }
6367 }
6368 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6369 *ptr = 'v';
6370 }
6371 return retval;
6372}
6373
6374/*
6375 * Like fgets(), but if the file line is too long, it is truncated and the
6376 * rest of the line is thrown away. Returns TRUE for end-of-file.
6377 */
6378 int
6379vim_fgets(buf, size, fp)
6380 char_u *buf;
6381 int size;
6382 FILE *fp;
6383{
6384 char *eof;
6385#define FGETS_SIZE 200
6386 char tbuf[FGETS_SIZE];
6387
6388 buf[size - 2] = NUL;
6389#ifdef USE_CR
6390 eof = fgets_cr((char *)buf, size, fp);
6391#else
6392 eof = fgets((char *)buf, size, fp);
6393#endif
6394 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6395 {
6396 buf[size - 1] = NUL; /* Truncate the line */
6397
6398 /* Now throw away the rest of the line: */
6399 do
6400 {
6401 tbuf[FGETS_SIZE - 2] = NUL;
6402#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006403 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006405 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006406#endif
6407 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6408 }
6409 return (eof == NULL);
6410}
6411
6412#if defined(USE_CR) || defined(PROTO)
6413/*
6414 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6415 * Returns TRUE for end-of-file.
6416 * Only used for the Mac, because it's much slower than vim_fgets().
6417 */
6418 int
6419tag_fgets(buf, size, fp)
6420 char_u *buf;
6421 int size;
6422 FILE *fp;
6423{
6424 int i = 0;
6425 int c;
6426 int eof = FALSE;
6427
6428 for (;;)
6429 {
6430 c = fgetc(fp);
6431 if (c == EOF)
6432 {
6433 eof = TRUE;
6434 break;
6435 }
6436 if (c == '\r')
6437 {
6438 /* Always store a NL for end-of-line. */
6439 if (i < size - 1)
6440 buf[i++] = '\n';
6441 c = fgetc(fp);
6442 if (c != '\n') /* Macintosh format: single CR. */
6443 ungetc(c, fp);
6444 break;
6445 }
6446 if (i < size - 1)
6447 buf[i++] = c;
6448 if (c == '\n')
6449 break;
6450 }
6451 buf[i] = NUL;
6452 return eof;
6453}
6454#endif
6455
6456/*
6457 * rename() only works if both files are on the same file system, this
6458 * function will (attempts to?) copy the file across if rename fails -- webb
6459 * Return -1 for failure, 0 for success.
6460 */
6461 int
6462vim_rename(from, to)
6463 char_u *from;
6464 char_u *to;
6465{
6466 int fd_in;
6467 int fd_out;
6468 int n;
6469 char *errmsg = NULL;
6470 char *buffer;
6471#ifdef AMIGA
6472 BPTR flock;
6473#endif
6474 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006475 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006476#ifdef HAVE_ACL
6477 vim_acl_T acl; /* ACL from original file */
6478#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006479 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006480
6481 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006482 * When the names are identical, there is nothing to do. When they refer
6483 * to the same file (ignoring case and slash/backslash differences) but
6484 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006485 */
6486 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006487 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006488 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006489 use_tmp_file = TRUE;
6490 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006491 return 0;
6492 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006493
6494 /*
6495 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6496 */
6497 if (mch_stat((char *)from, &st) < 0)
6498 return -1;
6499
Bram Moolenaar3576da72008-12-30 15:15:57 +00006500#ifdef UNIX
6501 {
6502 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006503
6504 /* It's possible for the source and destination to be the same file.
6505 * This happens when "from" and "to" differ in case and are on a FAT32
6506 * filesystem. In that case go through a temp file name. */
6507 if (mch_stat((char *)to, &st_to) >= 0
6508 && st.st_dev == st_to.st_dev
6509 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006510 use_tmp_file = TRUE;
6511 }
6512#endif
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006513#ifdef WIN3264
6514 {
6515 BY_HANDLE_FILE_INFORMATION info1, info2;
6516
6517 /* It's possible for the source and destination to be the same file.
6518 * In that case go through a temp file name. This makes rename("foo",
6519 * "./foo") a no-op (in a complicated way). */
6520 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6521 && win32_fileinfo(to, &info2) == FILEINFO_OK
6522 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6523 && info1.nFileIndexHigh == info2.nFileIndexHigh
6524 && info1.nFileIndexLow == info2.nFileIndexLow)
6525 use_tmp_file = TRUE;
6526 }
6527#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006528
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006529 if (use_tmp_file)
6530 {
6531 char tempname[MAXPATHL + 1];
6532
6533 /*
6534 * Find a name that doesn't exist and is in the same directory.
6535 * Rename "from" to "tempname" and then rename "tempname" to "to".
6536 */
6537 if (STRLEN(from) >= MAXPATHL - 5)
6538 return -1;
6539 STRCPY(tempname, from);
6540 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006541 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006542 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6543 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006544 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006545 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006546 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006547 if (mch_rename(tempname, (char *)to) == 0)
6548 return 0;
6549 /* Strange, the second step failed. Try moving the
6550 * file back and return failure. */
6551 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006552 return -1;
6553 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006554 /* If it fails for one temp name it will most likely fail
6555 * for any temp name, give up. */
6556 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006557 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006558 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006559 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006560 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006561
Bram Moolenaar071d4272004-06-13 20:20:40 +00006562 /*
6563 * Delete the "to" file, this is required on some systems to make the
6564 * mch_rename() work, on other systems it makes sure that we don't have
6565 * two files when the mch_rename() fails.
6566 */
6567
6568#ifdef AMIGA
6569 /*
6570 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6571 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006572 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573 * deleting the "from" file (horror!) we lock it during the remove.
6574 *
6575 * When used for making a backup before writing the file: This should not
6576 * happen with ":w", because startscript() should detect this problem and
6577 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6578 * name. This problem does exist with ":w filename", but then the
6579 * original file will be somewhere else so the backup isn't really
6580 * important. If autoscripting is off the rename may fail.
6581 */
6582 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6583#endif
6584 mch_remove(to);
6585#ifdef AMIGA
6586 if (flock)
6587 UnLock(flock);
6588#endif
6589
6590 /*
6591 * First try a normal rename, return if it works.
6592 */
6593 if (mch_rename((char *)from, (char *)to) == 0)
6594 return 0;
6595
6596 /*
6597 * Rename() failed, try copying the file.
6598 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006599 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006600#ifdef HAVE_ACL
6601 /* For systems that support ACL: get the ACL from the original file. */
6602 acl = mch_get_acl(from);
6603#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006604 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6605 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006606 {
6607#ifdef HAVE_ACL
6608 mch_free_acl(acl);
6609#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006610 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006611 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006612
6613 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006614 fd_out = mch_open((char *)to,
6615 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 if (fd_out == -1)
6617 {
6618 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006619#ifdef HAVE_ACL
6620 mch_free_acl(acl);
6621#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006622 return -1;
6623 }
6624
6625 buffer = (char *)alloc(BUFSIZE);
6626 if (buffer == NULL)
6627 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006628 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006629 close(fd_in);
6630#ifdef HAVE_ACL
6631 mch_free_acl(acl);
6632#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006633 return -1;
6634 }
6635
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006636 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6637 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006638 {
6639 errmsg = _("E208: Error writing to \"%s\"");
6640 break;
6641 }
6642
6643 vim_free(buffer);
6644 close(fd_in);
6645 if (close(fd_out) < 0)
6646 errmsg = _("E209: Error closing \"%s\"");
6647 if (n < 0)
6648 {
6649 errmsg = _("E210: Error reading \"%s\"");
6650 to = from;
6651 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006652#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006653 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006654#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006655#ifdef HAVE_ACL
6656 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006657 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006658#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006659#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006660 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006661#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006662 if (errmsg != NULL)
6663 {
6664 EMSG2(errmsg, to);
6665 return -1;
6666 }
6667 mch_remove(from);
6668 return 0;
6669}
6670
6671static int already_warned = FALSE;
6672
6673/*
6674 * Check if any not hidden buffer has been changed.
6675 * Postpone the check if there are characters in the stuff buffer, a global
6676 * command is being executed, a mapping is being executed or an autocommand is
6677 * busy.
6678 * Returns TRUE if some message was written (screen should be redrawn and
6679 * cursor positioned).
6680 */
6681 int
6682check_timestamps(focus)
6683 int focus; /* called for GUI focus event */
6684{
6685 buf_T *buf;
6686 int didit = 0;
6687 int n;
6688
6689 /* Don't check timestamps while system() or another low-level function may
6690 * cause us to lose and gain focus. */
6691 if (no_check_timestamps > 0)
6692 return FALSE;
6693
6694 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6695 * event and we would keep on checking if the file is steadily growing.
6696 * Do check again after typing something. */
6697 if (focus && did_check_timestamps)
6698 {
6699 need_check_timestamps = TRUE;
6700 return FALSE;
6701 }
6702
6703 if (!stuff_empty() || global_busy || !typebuf_typed()
6704#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006705 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706#endif
6707 )
6708 need_check_timestamps = TRUE; /* check later */
6709 else
6710 {
6711 ++no_wait_return;
6712 did_check_timestamps = TRUE;
6713 already_warned = FALSE;
6714 for (buf = firstbuf; buf != NULL; )
6715 {
6716 /* Only check buffers in a window. */
6717 if (buf->b_nwindows > 0)
6718 {
6719 n = buf_check_timestamp(buf, focus);
6720 if (didit < n)
6721 didit = n;
6722 if (n > 0 && !buf_valid(buf))
6723 {
6724 /* Autocommands have removed the buffer, start at the
6725 * first one again. */
6726 buf = firstbuf;
6727 continue;
6728 }
6729 }
6730 buf = buf->b_next;
6731 }
6732 --no_wait_return;
6733 need_check_timestamps = FALSE;
6734 if (need_wait_return && didit == 2)
6735 {
6736 /* make sure msg isn't overwritten */
6737 msg_puts((char_u *)"\n");
6738 out_flush();
6739 }
6740 }
6741 return didit;
6742}
6743
6744/*
6745 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6746 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6747 * empty.
6748 */
6749 static int
6750move_lines(frombuf, tobuf)
6751 buf_T *frombuf;
6752 buf_T *tobuf;
6753{
6754 buf_T *tbuf = curbuf;
6755 int retval = OK;
6756 linenr_T lnum;
6757 char_u *p;
6758
6759 /* Copy the lines in "frombuf" to "tobuf". */
6760 curbuf = tobuf;
6761 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6762 {
6763 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6764 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6765 {
6766 vim_free(p);
6767 retval = FAIL;
6768 break;
6769 }
6770 vim_free(p);
6771 }
6772
6773 /* Delete all the lines in "frombuf". */
6774 if (retval != FAIL)
6775 {
6776 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006777 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6778 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006779 {
6780 /* Oops! We could try putting back the saved lines, but that
6781 * might fail again... */
6782 retval = FAIL;
6783 break;
6784 }
6785 }
6786
6787 curbuf = tbuf;
6788 return retval;
6789}
6790
6791/*
6792 * Check if buffer "buf" has been changed.
6793 * Also check if the file for a new buffer unexpectedly appeared.
6794 * return 1 if a changed buffer was found.
6795 * return 2 if a message has been displayed.
6796 * return 0 otherwise.
6797 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006798 int
6799buf_check_timestamp(buf, focus)
6800 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006801 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006802{
6803 struct stat st;
6804 int stat_res;
6805 int retval = 0;
6806 char_u *path;
6807 char_u *tbuf;
6808 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006809 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006810 int helpmesg = FALSE;
6811 int reload = FALSE;
6812#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6813 int can_reload = FALSE;
6814#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006815 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 int orig_mode = buf->b_orig_mode;
6817#ifdef FEAT_GUI
6818 int save_mouse_correct = need_mouse_correct;
6819#endif
6820#ifdef FEAT_AUTOCMD
6821 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006822 int n;
6823 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006824#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006825 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826
6827 /* If there is no file name, the buffer is not loaded, 'buftype' is
6828 * set, we are in the middle of a save or being called recursively: ignore
6829 * this buffer. */
6830 if (buf->b_ffname == NULL
6831 || buf->b_ml.ml_mfp == NULL
6832#if defined(FEAT_QUICKFIX)
6833 || *buf->b_p_bt != NUL
6834#endif
6835 || buf->b_saving
6836#ifdef FEAT_AUTOCMD
6837 || busy
6838#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006839#ifdef FEAT_NETBEANS_INTG
6840 || isNetbeansBuffer(buf)
6841#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 )
6843 return 0;
6844
6845 if ( !(buf->b_flags & BF_NOTEDITED)
6846 && buf->b_mtime != 0
6847 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6848 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006849 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006850#ifdef HAVE_ST_MODE
6851 || (int)st.st_mode != buf->b_orig_mode
6852#else
6853 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6854#endif
6855 ))
6856 {
6857 retval = 1;
6858
Bram Moolenaar316059c2006-01-14 21:18:42 +00006859 /* set b_mtime to stop further warnings (e.g., when executing
6860 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006861 if (stat_res < 0)
6862 {
6863 buf->b_mtime = 0;
6864 buf->b_orig_size = 0;
6865 buf->b_orig_mode = 0;
6866 }
6867 else
6868 buf_store_time(buf, &st, buf->b_ffname);
6869
6870 /* Don't do anything for a directory. Might contain the file
6871 * explorer. */
6872 if (mch_isdir(buf->b_fname))
6873 ;
6874
6875 /*
6876 * If 'autoread' is set, the buffer has no changes and the file still
6877 * exists, reload the buffer. Use the buffer-local option value if it
6878 * was set, the global option value otherwise.
6879 */
6880 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6881 && !bufIsChanged(buf) && stat_res >= 0)
6882 reload = TRUE;
6883 else
6884 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006885 if (stat_res < 0)
6886 reason = "deleted";
6887 else if (bufIsChanged(buf))
6888 reason = "conflict";
6889 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6890 reason = "changed";
6891 else if (orig_mode != buf->b_orig_mode)
6892 reason = "mode";
6893 else
6894 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006895
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006896#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006897 /*
6898 * Only give the warning if there are no FileChangedShell
6899 * autocommands.
6900 * Avoid being called recursively by setting "busy".
6901 */
6902 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006903# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006904 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6905 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006906# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006907 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006908 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6909 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006910 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006911 busy = FALSE;
6912 if (n)
6913 {
6914 if (!buf_valid(buf))
6915 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006916# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006917 s = get_vim_var_str(VV_FCS_CHOICE);
6918 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6919 reload = TRUE;
6920 else if (STRCMP(s, "ask") == 0)
6921 n = FALSE;
6922 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006923# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006924 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006926 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006927#endif
6928 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006929 if (*reason == 'd')
6930 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006931 else
6932 {
6933 helpmesg = TRUE;
6934#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6935 can_reload = TRUE;
6936#endif
6937 /*
6938 * Check if the file contents really changed to avoid
6939 * giving a warning when only the timestamp was set (e.g.,
6940 * checked out of CVS). Always warn when the buffer was
6941 * changed.
6942 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006943 if (reason[2] == 'n')
6944 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006945 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006946 mesg2 = _("See \":help W12\" for more info.");
6947 }
6948 else if (reason[1] == 'h')
6949 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006951 mesg2 = _("See \":help W11\" for more info.");
6952 }
6953 else if (*reason == 'm')
6954 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006955 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006956 mesg2 = _("See \":help W16\" for more info.");
6957 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006958 else
6959 /* Only timestamp changed, store it to avoid a warning
6960 * in check_mtime() later. */
6961 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 }
6963 }
6964 }
6965
6966 }
6967 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6968 && vim_fexists(buf->b_ffname))
6969 {
6970 retval = 1;
6971 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6972 buf->b_flags |= BF_NEW_W;
6973#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6974 can_reload = TRUE;
6975#endif
6976 }
6977
6978 if (mesg != NULL)
6979 {
6980 path = home_replace_save(buf, buf->b_fname);
6981 if (path != NULL)
6982 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006983 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006984 mesg2 = "";
6985 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
6986 + STRLEN(mesg2) + 2));
6987 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006988#ifdef FEAT_EVAL
6989 /* Set warningmsg here, before the unimportant and output-specific
6990 * mesg2 has been appended. */
6991 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
6992#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006993#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6994 if (can_reload)
6995 {
6996 if (*mesg2 != NUL)
6997 {
6998 STRCAT(tbuf, "\n");
6999 STRCAT(tbuf, mesg2);
7000 }
7001 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01007002 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007003 reload = TRUE;
7004 }
7005 else
7006#endif
7007 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7008 {
7009 if (*mesg2 != NUL)
7010 {
7011 STRCAT(tbuf, "; ");
7012 STRCAT(tbuf, mesg2);
7013 }
7014 EMSG(tbuf);
7015 retval = 2;
7016 }
7017 else
7018 {
Bram Moolenaared203462004-06-16 11:19:22 +00007019# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007020 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007021# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007022 {
7023 msg_start();
7024 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7025 if (*mesg2 != NUL)
7026 msg_puts_attr((char_u *)mesg2,
7027 hl_attr(HLF_W) + MSG_HIST);
7028 msg_clr_eos();
7029 (void)msg_end();
7030 if (emsg_silent == 0)
7031 {
7032 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007033# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007034 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007035# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007036 /* give the user some time to think about it */
7037 ui_delay(1000L, TRUE);
7038
7039 /* don't redraw and erase the message */
7040 redraw_cmdline = FALSE;
7041 }
7042 }
7043 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007044 }
7045
7046 vim_free(path);
7047 vim_free(tbuf);
7048 }
7049 }
7050
7051 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02007052 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007053 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007054 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02007055#ifdef FEAT_PERSISTENT_UNDO
7056 if (buf->b_p_udf && buf->b_ffname != NULL)
7057 {
7058 char_u hash[UNDO_HASH_SIZE];
7059 buf_T *save_curbuf = curbuf;
7060
7061 /* Any existing undo file is unusable, write it now. */
7062 curbuf = buf;
7063 u_compute_hash(hash);
7064 u_write_undo(NULL, FALSE, buf, hash);
7065 curbuf = save_curbuf;
7066 }
7067#endif
7068 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007069
Bram Moolenaar56718732006-03-15 22:53:57 +00007070#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007071 /* Trigger FileChangedShell when the file was changed in any way. */
7072 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007073 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7074 buf->b_fname, buf->b_fname, FALSE, buf);
7075#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007076#ifdef FEAT_GUI
7077 /* restore this in case an autocommand has set it; it would break
7078 * 'mousefocus' */
7079 need_mouse_correct = save_mouse_correct;
7080#endif
7081
7082 return retval;
7083}
7084
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007085/*
7086 * Reload a buffer that is already loaded.
7087 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007088 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7089 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007090 */
7091 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007092buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007093 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007094 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007095{
7096 exarg_T ea;
7097 pos_T old_cursor;
7098 linenr_T old_topline;
7099 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007100 buf_T *savebuf;
7101 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007102 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007103 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007104
7105 /* set curwin/curbuf for "buf" and save some things */
7106 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007107
7108 /* We only want to read the text from the file, not reset the syntax
7109 * highlighting, clear marks, diff status, etc. Force the fileformat
7110 * and encoding to be the same. */
7111 if (prep_exarg(&ea, buf) == OK)
7112 {
7113 old_cursor = curwin->w_cursor;
7114 old_topline = curwin->w_topline;
7115
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007116 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007117 {
7118 /* Save all the text, so that the reload can be undone.
7119 * Sync first so that this is a separate undo-able action. */
7120 u_sync(FALSE);
7121 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7122 flags |= READ_KEEP_UNDO;
7123 }
7124
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007125 /*
7126 * To behave like when a new file is edited (matters for
7127 * BufReadPost autocommands) we first need to delete the current
7128 * buffer contents. But if reading the file fails we should keep
7129 * the old contents. Can't use memory only, the file might be
7130 * too big. Use a hidden buffer to move the buffer contents to.
7131 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007132 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007133 savebuf = NULL;
7134 else
7135 {
7136 /* Allocate a buffer without putting it in the buffer list. */
7137 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007138 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007139 {
7140 /* Open the memline. */
7141 curbuf = savebuf;
7142 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007143 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007144 curbuf = buf;
7145 curwin->w_buffer = buf;
7146 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007147 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007148 || move_lines(buf, savebuf) == FAIL)
7149 {
7150 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7151 buf->b_fname);
7152 saved = FAIL;
7153 }
7154 }
7155
7156 if (saved == OK)
7157 {
7158 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7159#ifdef FEAT_AUTOCMD
7160 keep_filetype = TRUE; /* don't detect 'filetype' */
7161#endif
7162 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7163 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007164 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007165 {
7166#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7167 if (!aborting())
7168#endif
7169 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007170 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007171 {
7172 /* Put the text back from the save buffer. First
7173 * delete any lines that readfile() added. */
7174 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007175 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007176 break;
7177 (void)move_lines(savebuf, buf);
7178 }
7179 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007180 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007181 {
7182 /* Mark the buffer as unmodified and free undo info. */
7183 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007184 if ((flags & READ_KEEP_UNDO) == 0)
7185 {
7186 u_blockfree(buf);
7187 u_clearall(buf);
7188 }
7189 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007190 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007191 /* Mark all undo states as changed. */
7192 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007193 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007194 }
7195 }
7196 vim_free(ea.cmd);
7197
Bram Moolenaar8424a622006-04-19 21:23:36 +00007198 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007199 wipe_buffer(savebuf, FALSE);
7200
7201#ifdef FEAT_DIFF
7202 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007203 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007204#endif
7205
7206 /* Restore the topline and cursor position and check it (lines may
7207 * have been removed). */
7208 if (old_topline > curbuf->b_ml.ml_line_count)
7209 curwin->w_topline = curbuf->b_ml.ml_line_count;
7210 else
7211 curwin->w_topline = old_topline;
7212 curwin->w_cursor = old_cursor;
7213 check_cursor();
7214 update_topline();
7215#ifdef FEAT_AUTOCMD
7216 keep_filetype = FALSE;
7217#endif
7218#ifdef FEAT_FOLDING
7219 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007220 win_T *wp;
7221 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007222
7223 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007224 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007225 if (wp->w_buffer == curwin->w_buffer
7226 && !foldmethodIsManual(wp))
7227 foldUpdateAll(wp);
7228 }
7229#endif
7230 /* If the mode didn't change and 'readonly' was set, keep the old
7231 * value; the user probably used the ":view" command. But don't
7232 * reset it, might have had a read error. */
7233 if (orig_mode == curbuf->b_orig_mode)
7234 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007235
7236 /* Modelines must override settings done by autocommands. */
7237 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007238 }
7239
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007240 /* restore curwin/curbuf and a few other things */
7241 aucmd_restbuf(&aco);
7242 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007243}
7244
Bram Moolenaar071d4272004-06-13 20:20:40 +00007245 void
7246buf_store_time(buf, st, fname)
7247 buf_T *buf;
7248 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007249 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007250{
7251 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007252 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007253#ifdef HAVE_ST_MODE
7254 buf->b_orig_mode = (int)st->st_mode;
7255#else
7256 buf->b_orig_mode = mch_getperm(fname);
7257#endif
7258}
7259
7260/*
7261 * Adjust the line with missing eol, used for the next write.
7262 * Used for do_filter(), when the input lines for the filter are deleted.
7263 */
7264 void
7265write_lnum_adjust(offset)
7266 linenr_T offset;
7267{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007268 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7269 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007270}
7271
7272#if defined(TEMPDIRNAMES) || defined(PROTO)
7273static long temp_count = 0; /* Temp filename counter. */
7274
7275/*
7276 * Delete the temp directory and all files it contains.
7277 */
7278 void
7279vim_deltempdir()
7280{
7281 char_u **files;
7282 int file_count;
7283 int i;
7284
7285 if (vim_tempdir != NULL)
7286 {
7287 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7288 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7289 EW_DIR|EW_FILE|EW_SILENT) == OK)
7290 {
7291 for (i = 0; i < file_count; ++i)
7292 mch_remove(files[i]);
7293 FreeWild(file_count, files);
7294 }
7295 gettail(NameBuff)[-1] = NUL;
7296 (void)mch_rmdir(NameBuff);
7297
7298 vim_free(vim_tempdir);
7299 vim_tempdir = NULL;
7300 }
7301}
7302#endif
7303
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007304#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007305/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007306 * Directory "tempdir" was created. Expand this name to a full path and put
7307 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7308 * "tempdir" must be no longer than MAXPATHL.
7309 */
7310 static void
7311vim_settempdir(tempdir)
7312 char_u *tempdir;
7313{
7314 char_u *buf;
7315
7316 buf = alloc((unsigned)MAXPATHL + 2);
7317 if (buf != NULL)
7318 {
7319 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7320 STRCPY(buf, tempdir);
7321# ifdef __EMX__
7322 if (vim_strchr(buf, '/') != NULL)
7323 STRCAT(buf, "/");
7324 else
7325# endif
7326 add_pathsep(buf);
7327 vim_tempdir = vim_strsave(buf);
7328 vim_free(buf);
7329 }
7330}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007331#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007332
7333/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007334 * vim_tempname(): Return a unique name that can be used for a temp file.
7335 *
7336 * The temp file is NOT created.
7337 *
7338 * The returned pointer is to allocated memory.
7339 * The returned pointer is NULL if no valid name was found.
7340 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007341 char_u *
7342vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007343 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007344{
7345#ifdef USE_TMPNAM
7346 char_u itmp[L_tmpnam]; /* use tmpnam() */
7347#else
7348 char_u itmp[TEMPNAMELEN];
7349#endif
7350
7351#ifdef TEMPDIRNAMES
7352 static char *(tempdirs[]) = {TEMPDIRNAMES};
7353 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007354# ifndef EEXIST
7355 struct stat st;
7356# endif
7357
7358 /*
7359 * This will create a directory for private use by this instance of Vim.
7360 * This is done once, and the same directory is used for all temp files.
7361 * This method avoids security problems because of symlink attacks et al.
7362 * It's also a bit faster, because we only need to check for an existing
7363 * file when creating the directory and not for each temp file.
7364 */
7365 if (vim_tempdir == NULL)
7366 {
7367 /*
7368 * Try the entries in TEMPDIRNAMES to create the temp directory.
7369 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007370 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007371 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007372# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007373 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007374 long nr;
7375 long off;
7376# endif
7377
Bram Moolenaar071d4272004-06-13 20:20:40 +00007378 /* expand $TMP, leave room for "/v1100000/999999999" */
7379 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7380 if (mch_isdir(itmp)) /* directory exists */
7381 {
7382# ifdef __EMX__
7383 /* If $TMP contains a forward slash (perhaps using bash or
7384 * tcsh), don't add a backslash, use a forward slash!
7385 * Adding 2 backslashes didn't work. */
7386 if (vim_strchr(itmp, '/') != NULL)
7387 STRCAT(itmp, "/");
7388 else
7389# endif
7390 add_pathsep(itmp);
7391
Bram Moolenaareaf03392009-11-17 11:08:52 +00007392# ifdef HAVE_MKDTEMP
7393 /* Leave room for filename */
7394 STRCAT(itmp, "vXXXXXX");
7395 if (mkdtemp((char *)itmp) != NULL)
7396 vim_settempdir(itmp);
7397# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007398 /* Get an arbitrary number of up to 6 digits. When it's
7399 * unlikely that it already exists it will be faster,
7400 * otherwise it doesn't matter. The use of mkdir() avoids any
7401 * security problems because of the predictable number. */
7402 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007403 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007404
7405 /* Try up to 10000 different values until we find a name that
7406 * doesn't exist. */
7407 for (off = 0; off < 10000L; ++off)
7408 {
7409 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007410# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007412# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007413
Bram Moolenaareaf03392009-11-17 11:08:52 +00007414 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7415# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007416 /* If mkdir() does not set errno to EEXIST, check for
7417 * existing file here. There is a race condition then,
7418 * although it's fail-safe. */
7419 if (mch_stat((char *)itmp, &st) >= 0)
7420 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007421# endif
7422# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007423 /* Make sure the umask doesn't remove the executable bit.
7424 * "repl" has been reported to use "177". */
7425 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007426# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007428# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007430# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007431 if (r == 0)
7432 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007433 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007434 break;
7435 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007436# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007437 /* If the mkdir() didn't fail because the file/dir exists,
7438 * we probably can't create any dir here, try another
7439 * place. */
7440 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007441# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007442 break;
7443 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007444# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007445 if (vim_tempdir != NULL)
7446 break;
7447 }
7448 }
7449 }
7450
7451 if (vim_tempdir != NULL)
7452 {
7453 /* There is no need to check if the file exists, because we own the
7454 * directory and nobody else creates a file in it. */
7455 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7456 return vim_strsave(itmp);
7457 }
7458
7459 return NULL;
7460
7461#else /* TEMPDIRNAMES */
7462
7463# ifdef WIN3264
7464 char szTempFile[_MAX_PATH + 1];
7465 char buf4[4];
7466 char_u *retval;
7467 char_u *p;
7468
7469 STRCPY(itmp, "");
7470 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007471 {
7472 szTempFile[0] = '.'; /* GetTempPath() failed, use current dir */
7473 szTempFile[1] = NUL;
7474 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475 strcpy(buf4, "VIM");
7476 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7477 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7478 return NULL;
7479 /* GetTempFileName() will create the file, we don't want that */
7480 (void)DeleteFile(itmp);
7481
7482 /* Backslashes in a temp file name cause problems when filtering with
7483 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7484 * didn't set 'shellslash'. */
7485 retval = vim_strsave(itmp);
7486 if (*p_shcf == '-' || p_ssl)
7487 for (p = retval; *p; ++p)
7488 if (*p == '\\')
7489 *p = '/';
7490 return retval;
7491
7492# else /* WIN3264 */
7493
7494# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007495 char_u *p;
7496
Bram Moolenaar071d4272004-06-13 20:20:40 +00007497 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007498 p = tmpnam((char *)itmp);
7499 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 return NULL;
7501# else
7502 char_u *p;
7503
7504# ifdef VMS_TEMPNAM
7505 /* mktemp() is not working on VMS. It seems to be
7506 * a do-nothing function. Therefore we use tempnam().
7507 */
7508 sprintf((char *)itmp, "VIM%c", extra_char);
7509 p = (char_u *)tempnam("tmp:", (char *)itmp);
7510 if (p != NULL)
7511 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007512 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007513 * and VIM will then be unable to find the file later */
7514 STRCPY(itmp, p);
7515 STRCAT(itmp, ".txt");
7516 free(p);
7517 }
7518 else
7519 return NULL;
7520# else
7521 STRCPY(itmp, TEMPNAME);
7522 if ((p = vim_strchr(itmp, '?')) != NULL)
7523 *p = extra_char;
7524 if (mktemp((char *)itmp) == NULL)
7525 return NULL;
7526# endif
7527# endif
7528
7529 return vim_strsave(itmp);
7530# endif /* WIN3264 */
7531#endif /* TEMPDIRNAMES */
7532}
7533
7534#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7535/*
7536 * Convert all backslashes in fname to forward slashes in-place.
7537 */
7538 void
7539forward_slash(fname)
7540 char_u *fname;
7541{
7542 char_u *p;
7543
7544 for (p = fname; *p != NUL; ++p)
7545# ifdef FEAT_MBYTE
7546 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007547 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007548 ++p;
7549 else
7550# endif
7551 if (*p == '\\')
7552 *p = '/';
7553}
7554#endif
7555
7556
7557/*
7558 * Code for automatic commands.
7559 *
7560 * Only included when "FEAT_AUTOCMD" has been defined.
7561 */
7562
7563#if defined(FEAT_AUTOCMD) || defined(PROTO)
7564
7565/*
7566 * The autocommands are stored in a list for each event.
7567 * Autocommands for the same pattern, that are consecutive, are joined
7568 * together, to avoid having to match the pattern too often.
7569 * The result is an array of Autopat lists, which point to AutoCmd lists:
7570 *
7571 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7572 * Autopat.cmds Autopat.cmds
7573 * | |
7574 * V V
7575 * AutoCmd.next AutoCmd.next
7576 * | |
7577 * V V
7578 * AutoCmd.next NULL
7579 * |
7580 * V
7581 * NULL
7582 *
7583 * first_autopat[1] --> Autopat.next --> NULL
7584 * Autopat.cmds
7585 * |
7586 * V
7587 * AutoCmd.next
7588 * |
7589 * V
7590 * NULL
7591 * etc.
7592 *
7593 * The order of AutoCmds is important, this is the order in which they were
7594 * defined and will have to be executed.
7595 */
7596typedef struct AutoCmd
7597{
7598 char_u *cmd; /* The command to be executed (NULL
7599 when command has been removed) */
7600 char nested; /* If autocommands nest here */
7601 char last; /* last command in list */
7602#ifdef FEAT_EVAL
7603 scid_T scriptID; /* script ID where defined */
7604#endif
7605 struct AutoCmd *next; /* Next AutoCmd in list */
7606} AutoCmd;
7607
7608typedef struct AutoPat
7609{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007610 char_u *pat; /* pattern as typed (NULL when pattern
7611 has been removed) */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007612 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613 AutoCmd *cmds; /* list of commands to do */
7614 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007615 int group; /* group ID */
7616 int patlen; /* strlen() of pat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007617 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar6395af82013-06-12 19:52:15 +02007618 char allow_dirs; /* Pattern may match whole path */
7619 char last; /* last pattern for apply_autocmds() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007620} AutoPat;
7621
7622static struct event_name
7623{
7624 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007625 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007626} event_names[] =
7627{
7628 {"BufAdd", EVENT_BUFADD},
7629 {"BufCreate", EVENT_BUFADD},
7630 {"BufDelete", EVENT_BUFDELETE},
7631 {"BufEnter", EVENT_BUFENTER},
7632 {"BufFilePost", EVENT_BUFFILEPOST},
7633 {"BufFilePre", EVENT_BUFFILEPRE},
7634 {"BufHidden", EVENT_BUFHIDDEN},
7635 {"BufLeave", EVENT_BUFLEAVE},
7636 {"BufNew", EVENT_BUFNEW},
7637 {"BufNewFile", EVENT_BUFNEWFILE},
7638 {"BufRead", EVENT_BUFREADPOST},
7639 {"BufReadCmd", EVENT_BUFREADCMD},
7640 {"BufReadPost", EVENT_BUFREADPOST},
7641 {"BufReadPre", EVENT_BUFREADPRE},
7642 {"BufUnload", EVENT_BUFUNLOAD},
7643 {"BufWinEnter", EVENT_BUFWINENTER},
7644 {"BufWinLeave", EVENT_BUFWINLEAVE},
7645 {"BufWipeout", EVENT_BUFWIPEOUT},
7646 {"BufWrite", EVENT_BUFWRITEPRE},
7647 {"BufWritePost", EVENT_BUFWRITEPOST},
7648 {"BufWritePre", EVENT_BUFWRITEPRE},
7649 {"BufWriteCmd", EVENT_BUFWRITECMD},
7650 {"CmdwinEnter", EVENT_CMDWINENTER},
7651 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaard5005162014-08-22 23:05:54 +02007652 {"CmdUndefined", EVENT_CMDUNDEFINED},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007653 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaarcfa3cae2012-07-10 17:14:56 +02007654 {"CompleteDone", EVENT_COMPLETEDONE},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007655 {"CursorHold", EVENT_CURSORHOLD},
7656 {"CursorHoldI", EVENT_CURSORHOLDI},
7657 {"CursorMoved", EVENT_CURSORMOVED},
7658 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007659 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7660 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007661 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7662 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7663 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7664 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007665 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007666 {"FileChangedRO", EVENT_FILECHANGEDRO},
7667 {"FileReadPost", EVENT_FILEREADPOST},
7668 {"FileReadPre", EVENT_FILEREADPRE},
7669 {"FileReadCmd", EVENT_FILEREADCMD},
7670 {"FileType", EVENT_FILETYPE},
7671 {"FileWritePost", EVENT_FILEWRITEPOST},
7672 {"FileWritePre", EVENT_FILEWRITEPRE},
7673 {"FileWriteCmd", EVENT_FILEWRITECMD},
7674 {"FilterReadPost", EVENT_FILTERREADPOST},
7675 {"FilterReadPre", EVENT_FILTERREADPRE},
7676 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7677 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7678 {"FocusGained", EVENT_FOCUSGAINED},
7679 {"FocusLost", EVENT_FOCUSLOST},
7680 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7681 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007682 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007683 {"InsertChange", EVENT_INSERTCHANGE},
7684 {"InsertEnter", EVENT_INSERTENTER},
7685 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaare659c952011-05-19 17:25:41 +02007686 {"InsertCharPre", EVENT_INSERTCHARPRE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007687 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007688 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7689 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar3b53dfb2012-06-06 18:03:07 +02007690 {"QuitPre", EVENT_QUITPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007691 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007692 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007693 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7694 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007695 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007696 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007697 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007698 {"StdinReadPost", EVENT_STDINREADPOST},
7699 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007700 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007701 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007702 {"TabEnter", EVENT_TABENTER},
7703 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007704 {"TermChanged", EVENT_TERMCHANGED},
7705 {"TermResponse", EVENT_TERMRESPONSE},
Bram Moolenaar186628f2013-03-19 13:33:23 +01007706 {"TextChanged", EVENT_TEXTCHANGED},
7707 {"TextChangedI", EVENT_TEXTCHANGEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007708 {"User", EVENT_USER},
7709 {"VimEnter", EVENT_VIMENTER},
7710 {"VimLeave", EVENT_VIMLEAVE},
7711 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7712 {"WinEnter", EVENT_WINENTER},
7713 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007714 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007715 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007716};
7717
7718static AutoPat *first_autopat[NUM_EVENTS] =
7719{
7720 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7721 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7722 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7723 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007724 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7725 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007726};
7727
7728/*
7729 * struct used to keep status while executing autocommands for an event.
7730 */
7731typedef struct AutoPatCmd
7732{
7733 AutoPat *curpat; /* next AutoPat to examine */
7734 AutoCmd *nextcmd; /* next AutoCmd to execute */
7735 int group; /* group being used */
7736 char_u *fname; /* fname to match with */
7737 char_u *sfname; /* sfname to match with */
7738 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007739 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007740 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7741 buf is deleted */
7742 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007743} AutoPatCmd;
7744
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007745static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007746
Bram Moolenaar071d4272004-06-13 20:20:40 +00007747/*
7748 * augroups stores a list of autocmd group names.
7749 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007750static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007751#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7752
7753/*
7754 * The ID of the current group. Group 0 is the default one.
7755 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007756static int current_augroup = AUGROUP_DEFAULT;
7757
7758static int au_need_clean = FALSE; /* need to delete marked patterns */
7759
Bram Moolenaar754b5602006-02-09 23:53:20 +00007760static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007761static void au_remove_pat __ARGS((AutoPat *ap));
7762static void au_remove_cmds __ARGS((AutoPat *ap));
7763static void au_cleanup __ARGS((void));
7764static int au_new_group __ARGS((char_u *name));
7765static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007766static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7767static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007768static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007769static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007770static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007771static int do_autocmd_event __ARGS((event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007772static 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 +00007773static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7774
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007775
Bram Moolenaar754b5602006-02-09 23:53:20 +00007776static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007777static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007778static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007779
7780/*
7781 * Show the autocommands for one AutoPat.
7782 */
7783 static void
7784show_autocmd(ap, event)
7785 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007786 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007787{
7788 AutoCmd *ac;
7789
7790 /* Check for "got_int" (here and at various places below), which is set
7791 * when "q" has been hit for the "--more--" prompt */
7792 if (got_int)
7793 return;
7794 if (ap->pat == NULL) /* pattern has been removed */
7795 return;
7796
7797 msg_putchar('\n');
7798 if (got_int)
7799 return;
7800 if (event != last_event || ap->group != last_group)
7801 {
7802 if (ap->group != AUGROUP_DEFAULT)
7803 {
7804 if (AUGROUP_NAME(ap->group) == NULL)
7805 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7806 else
7807 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7808 msg_puts((char_u *)" ");
7809 }
7810 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7811 last_event = event;
7812 last_group = ap->group;
7813 msg_putchar('\n');
7814 if (got_int)
7815 return;
7816 }
7817 msg_col = 4;
7818 msg_outtrans(ap->pat);
7819
7820 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7821 {
7822 if (ac->cmd != NULL) /* skip removed commands */
7823 {
7824 if (msg_col >= 14)
7825 msg_putchar('\n');
7826 msg_col = 14;
7827 if (got_int)
7828 return;
7829 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007830#ifdef FEAT_EVAL
7831 if (p_verbose > 0)
7832 last_set_msg(ac->scriptID);
7833#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007834 if (got_int)
7835 return;
7836 if (ac->next != NULL)
7837 {
7838 msg_putchar('\n');
7839 if (got_int)
7840 return;
7841 }
7842 }
7843 }
7844}
7845
7846/*
7847 * Mark an autocommand pattern for deletion.
7848 */
7849 static void
7850au_remove_pat(ap)
7851 AutoPat *ap;
7852{
7853 vim_free(ap->pat);
7854 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007855 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007856 au_need_clean = TRUE;
7857}
7858
7859/*
7860 * Mark all commands for a pattern for deletion.
7861 */
7862 static void
7863au_remove_cmds(ap)
7864 AutoPat *ap;
7865{
7866 AutoCmd *ac;
7867
7868 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7869 {
7870 vim_free(ac->cmd);
7871 ac->cmd = NULL;
7872 }
7873 au_need_clean = TRUE;
7874}
7875
7876/*
7877 * Cleanup autocommands and patterns that have been deleted.
7878 * This is only done when not executing autocommands.
7879 */
7880 static void
7881au_cleanup()
7882{
7883 AutoPat *ap, **prev_ap;
7884 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007885 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007886
7887 if (autocmd_busy || !au_need_clean)
7888 return;
7889
7890 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007891 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7892 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007893 {
7894 /* loop over all autocommand patterns */
7895 prev_ap = &(first_autopat[(int)event]);
7896 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7897 {
7898 /* loop over all commands for this pattern */
7899 prev_ac = &(ap->cmds);
7900 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7901 {
7902 /* remove the command if the pattern is to be deleted or when
7903 * the command has been marked for deletion */
7904 if (ap->pat == NULL || ac->cmd == NULL)
7905 {
7906 *prev_ac = ac->next;
7907 vim_free(ac->cmd);
7908 vim_free(ac);
7909 }
7910 else
7911 prev_ac = &(ac->next);
7912 }
7913
7914 /* remove the pattern if it has been marked for deletion */
7915 if (ap->pat == NULL)
7916 {
7917 *prev_ap = ap->next;
Bram Moolenaar473de612013-06-08 18:19:48 +02007918 vim_regfree(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007919 vim_free(ap);
7920 }
7921 else
7922 prev_ap = &(ap->next);
7923 }
7924 }
7925
7926 au_need_clean = FALSE;
7927}
7928
7929/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007930 * Called when buffer is freed, to remove/invalidate related buffer-local
7931 * autocmds.
7932 */
7933 void
7934aubuflocal_remove(buf)
7935 buf_T *buf;
7936{
7937 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007938 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007939 AutoPatCmd *apc;
7940
7941 /* invalidate currently executing autocommands */
7942 for (apc = active_apc_list; apc; apc = apc->next)
7943 if (buf->b_fnum == apc->arg_bufnr)
7944 apc->arg_bufnr = 0;
7945
7946 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007947 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7948 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007949 /* loop over all autocommand patterns */
7950 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7951 if (ap->buflocal_nr == buf->b_fnum)
7952 {
7953 au_remove_pat(ap);
7954 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007955 {
7956 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007957 smsg((char_u *)
7958 _("auto-removing autocommand: %s <buffer=%d>"),
7959 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007960 verbose_leave();
7961 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007962 }
7963 au_cleanup();
7964}
7965
7966/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007967 * Add an autocmd group name.
7968 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7969 */
7970 static int
7971au_new_group(name)
7972 char_u *name;
7973{
7974 int i;
7975
7976 i = au_find_group(name);
7977 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7978 {
7979 /* First try using a free entry. */
7980 for (i = 0; i < augroups.ga_len; ++i)
7981 if (AUGROUP_NAME(i) == NULL)
7982 break;
7983 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7984 return AUGROUP_ERROR;
7985
7986 AUGROUP_NAME(i) = vim_strsave(name);
7987 if (AUGROUP_NAME(i) == NULL)
7988 return AUGROUP_ERROR;
7989 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007990 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007991 }
7992
7993 return i;
7994}
7995
7996 static void
7997au_del_group(name)
7998 char_u *name;
7999{
8000 int i;
8001
8002 i = au_find_group(name);
8003 if (i == AUGROUP_ERROR) /* the group doesn't exist */
8004 EMSG2(_("E367: No such group: \"%s\""), name);
8005 else
8006 {
8007 vim_free(AUGROUP_NAME(i));
8008 AUGROUP_NAME(i) = NULL;
8009 }
8010}
8011
8012/*
8013 * Find the ID of an autocmd group name.
8014 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8015 */
8016 static int
8017au_find_group(name)
8018 char_u *name;
8019{
8020 int i;
8021
8022 for (i = 0; i < augroups.ga_len; ++i)
8023 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8024 return i;
8025 return AUGROUP_ERROR;
8026}
8027
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008028/*
8029 * Return TRUE if augroup "name" exists.
8030 */
8031 int
8032au_has_group(name)
8033 char_u *name;
8034{
8035 return au_find_group(name) != AUGROUP_ERROR;
8036}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008037
Bram Moolenaar071d4272004-06-13 20:20:40 +00008038/*
8039 * ":augroup {name}".
8040 */
8041 void
8042do_augroup(arg, del_group)
8043 char_u *arg;
8044 int del_group;
8045{
8046 int i;
8047
8048 if (del_group)
8049 {
8050 if (*arg == NUL)
8051 EMSG(_(e_argreq));
8052 else
8053 au_del_group(arg);
8054 }
8055 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8056 current_augroup = AUGROUP_DEFAULT;
8057 else if (*arg) /* ":aug xxx": switch to group xxx */
8058 {
8059 i = au_new_group(arg);
8060 if (i != AUGROUP_ERROR)
8061 current_augroup = i;
8062 }
8063 else /* ":aug": list the group names */
8064 {
8065 msg_start();
8066 for (i = 0; i < augroups.ga_len; ++i)
8067 {
8068 if (AUGROUP_NAME(i) != NULL)
8069 {
8070 msg_puts(AUGROUP_NAME(i));
8071 msg_puts((char_u *)" ");
8072 }
8073 }
8074 msg_clr_eos();
8075 msg_end();
8076 }
8077}
8078
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008079#if defined(EXITFREE) || defined(PROTO)
8080 void
8081free_all_autocmds()
8082{
8083 for (current_augroup = -1; current_augroup < augroups.ga_len;
8084 ++current_augroup)
8085 do_autocmd((char_u *)"", TRUE);
8086 ga_clear_strings(&augroups);
8087}
8088#endif
8089
Bram Moolenaar071d4272004-06-13 20:20:40 +00008090/*
8091 * Return the event number for event name "start".
8092 * Return NUM_EVENTS if the event name was not found.
8093 * Return a pointer to the next event name in "end".
8094 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008095 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008096event_name2nr(start, end)
8097 char_u *start;
8098 char_u **end;
8099{
8100 char_u *p;
8101 int i;
8102 int len;
8103
8104 /* the event name ends with end of line, a blank or a comma */
8105 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8106 ;
8107 for (i = 0; event_names[i].name != NULL; ++i)
8108 {
8109 len = (int)STRLEN(event_names[i].name);
8110 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8111 break;
8112 }
8113 if (*p == ',')
8114 ++p;
8115 *end = p;
8116 if (event_names[i].name == NULL)
8117 return NUM_EVENTS;
8118 return event_names[i].event;
8119}
8120
8121/*
8122 * Return the name for event "event".
8123 */
8124 static char_u *
8125event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008126 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008127{
8128 int i;
8129
8130 for (i = 0; event_names[i].name != NULL; ++i)
8131 if (event_names[i].event == event)
8132 return (char_u *)event_names[i].name;
8133 return (char_u *)"Unknown";
8134}
8135
8136/*
8137 * Scan over the events. "*" stands for all events.
8138 */
8139 static char_u *
8140find_end_event(arg, have_group)
8141 char_u *arg;
8142 int have_group; /* TRUE when group name was found */
8143{
8144 char_u *pat;
8145 char_u *p;
8146
8147 if (*arg == '*')
8148 {
8149 if (arg[1] && !vim_iswhite(arg[1]))
8150 {
8151 EMSG2(_("E215: Illegal character after *: %s"), arg);
8152 return NULL;
8153 }
8154 pat = arg + 1;
8155 }
8156 else
8157 {
8158 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8159 {
8160 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8161 {
8162 if (have_group)
8163 EMSG2(_("E216: No such event: %s"), pat);
8164 else
8165 EMSG2(_("E216: No such group or event: %s"), pat);
8166 return NULL;
8167 }
8168 }
8169 }
8170 return pat;
8171}
8172
8173/*
8174 * Return TRUE if "event" is included in 'eventignore'.
8175 */
8176 static int
8177event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008178 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008179{
8180 char_u *p = p_ei;
8181
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008182 while (*p != NUL)
8183 {
8184 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8185 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008186 if (event_name2nr(p, &p) == event)
8187 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008188 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008189
8190 return FALSE;
8191}
8192
8193/*
8194 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8195 */
8196 int
8197check_ei()
8198{
8199 char_u *p = p_ei;
8200
Bram Moolenaar071d4272004-06-13 20:20:40 +00008201 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008202 {
8203 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8204 {
8205 p += 3;
8206 if (*p == ',')
8207 ++p;
8208 }
8209 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008210 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008211 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008212
8213 return OK;
8214}
8215
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008216# if defined(FEAT_SYN_HL) || defined(PROTO)
8217
8218/*
8219 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8220 * buffer loaded into the window. "what" must start with a comma.
8221 * Returns the old value of 'eventignore' in allocated memory.
8222 */
8223 char_u *
8224au_event_disable(what)
8225 char *what;
8226{
8227 char_u *new_ei;
8228 char_u *save_ei;
8229
8230 save_ei = vim_strsave(p_ei);
8231 if (save_ei != NULL)
8232 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008233 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008234 if (new_ei != NULL)
8235 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008236 if (*what == ',' && *p_ei == NUL)
8237 STRCPY(new_ei, what + 1);
8238 else
8239 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008240 set_string_option_direct((char_u *)"ei", -1, new_ei,
8241 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008242 vim_free(new_ei);
8243 }
8244 }
8245 return save_ei;
8246}
8247
8248 void
8249au_event_restore(old_ei)
8250 char_u *old_ei;
8251{
8252 if (old_ei != NULL)
8253 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008254 set_string_option_direct((char_u *)"ei", -1, old_ei,
8255 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008256 vim_free(old_ei);
8257 }
8258}
8259# endif /* FEAT_SYN_HL */
8260
Bram Moolenaar071d4272004-06-13 20:20:40 +00008261/*
8262 * do_autocmd() -- implements the :autocmd command. Can be used in the
8263 * following ways:
8264 *
8265 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8266 * will be automatically executed for <event>
8267 * when editing a file matching <pat>, in
8268 * the current group.
8269 * :autocmd <event> <pat> Show the auto-commands associated with
8270 * <event> and <pat>.
8271 * :autocmd <event> Show the auto-commands associated with
8272 * <event>.
8273 * :autocmd Show all auto-commands.
8274 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8275 * <event> and <pat>, and add the command
8276 * <cmd>, for the current group.
8277 * :autocmd! <event> <pat> Remove all auto-commands associated with
8278 * <event> and <pat> for the current group.
8279 * :autocmd! <event> Remove all auto-commands associated with
8280 * <event> for the current group.
8281 * :autocmd! Remove ALL auto-commands for the current
8282 * group.
8283 *
8284 * Multiple events and patterns may be given separated by commas. Here are
8285 * some examples:
8286 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8287 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8288 *
8289 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008290 *
8291 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008292 */
8293 void
8294do_autocmd(arg, forceit)
8295 char_u *arg;
8296 int forceit;
8297{
8298 char_u *pat;
8299 char_u *envpat = NULL;
8300 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008301 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008302 int need_free = FALSE;
8303 int nested = FALSE;
8304 int group;
8305
8306 /*
8307 * Check for a legal group name. If not, use AUGROUP_ALL.
8308 */
8309 group = au_get_grouparg(&arg);
8310 if (arg == NULL) /* out of memory */
8311 return;
8312
8313 /*
8314 * Scan over the events.
8315 * If we find an illegal name, return here, don't do anything.
8316 */
8317 pat = find_end_event(arg, group != AUGROUP_ALL);
8318 if (pat == NULL)
8319 return;
8320
8321 /*
8322 * Scan over the pattern. Put a NUL at the end.
8323 */
8324 pat = skipwhite(pat);
8325 cmd = pat;
8326 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8327 cmd++;
8328 if (*cmd)
8329 *cmd++ = NUL;
8330
8331 /* Expand environment variables in the pattern. Set 'shellslash', we want
8332 * forward slashes here. */
8333 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8334 {
8335#ifdef BACKSLASH_IN_FILENAME
8336 int p_ssl_save = p_ssl;
8337
8338 p_ssl = TRUE;
8339#endif
8340 envpat = expand_env_save(pat);
8341#ifdef BACKSLASH_IN_FILENAME
8342 p_ssl = p_ssl_save;
8343#endif
8344 if (envpat != NULL)
8345 pat = envpat;
8346 }
8347
8348 /*
8349 * Check for "nested" flag.
8350 */
8351 cmd = skipwhite(cmd);
8352 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8353 {
8354 nested = TRUE;
8355 cmd = skipwhite(cmd + 6);
8356 }
8357
8358 /*
8359 * Find the start of the commands.
8360 * Expand <sfile> in it.
8361 */
8362 if (*cmd != NUL)
8363 {
8364 cmd = expand_sfile(cmd);
8365 if (cmd == NULL) /* some error */
8366 return;
8367 need_free = TRUE;
8368 }
8369
8370 /*
8371 * Print header when showing autocommands.
8372 */
8373 if (!forceit && *cmd == NUL)
8374 {
8375 /* Highlight title */
8376 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8377 }
8378
8379 /*
8380 * Loop over the events.
8381 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008382 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008383 last_group = AUGROUP_ERROR; /* for listing the group name */
8384 if (*arg == '*' || *arg == NUL)
8385 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008386 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8387 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008388 if (do_autocmd_event(event, pat,
8389 nested, cmd, forceit, group) == FAIL)
8390 break;
8391 }
8392 else
8393 {
8394 while (*arg && !vim_iswhite(*arg))
8395 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8396 nested, cmd, forceit, group) == FAIL)
8397 break;
8398 }
8399
8400 if (need_free)
8401 vim_free(cmd);
8402 vim_free(envpat);
8403}
8404
8405/*
8406 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8407 * The "argp" argument is advanced to the following argument.
8408 *
8409 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8410 */
8411 static int
8412au_get_grouparg(argp)
8413 char_u **argp;
8414{
8415 char_u *group_name;
8416 char_u *p;
8417 char_u *arg = *argp;
8418 int group = AUGROUP_ALL;
8419
8420 p = skiptowhite(arg);
8421 if (p > arg)
8422 {
8423 group_name = vim_strnsave(arg, (int)(p - arg));
8424 if (group_name == NULL) /* out of memory */
8425 return AUGROUP_ERROR;
8426 group = au_find_group(group_name);
8427 if (group == AUGROUP_ERROR)
8428 group = AUGROUP_ALL; /* no match, use all groups */
8429 else
8430 *argp = skipwhite(p); /* match, skip over group name */
8431 vim_free(group_name);
8432 }
8433 return group;
8434}
8435
8436/*
8437 * do_autocmd() for one event.
8438 * If *pat == NUL do for all patterns.
8439 * If *cmd == NUL show entries.
8440 * If forceit == TRUE delete entries.
8441 * If group is not AUGROUP_ALL, only use this group.
8442 */
8443 static int
8444do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008445 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008446 char_u *pat;
8447 int nested;
8448 char_u *cmd;
8449 int forceit;
8450 int group;
8451{
8452 AutoPat *ap;
8453 AutoPat **prev_ap;
8454 AutoCmd *ac;
8455 AutoCmd **prev_ac;
8456 int brace_level;
8457 char_u *endpat;
8458 int findgroup;
8459 int allgroups;
8460 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008461 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008462 int buflocal_nr;
8463 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008464
8465 if (group == AUGROUP_ALL)
8466 findgroup = current_augroup;
8467 else
8468 findgroup = group;
8469 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8470
8471 /*
8472 * Show or delete all patterns for an event.
8473 */
8474 if (*pat == NUL)
8475 {
8476 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8477 {
8478 if (forceit) /* delete the AutoPat, if it's in the current group */
8479 {
8480 if (ap->group == findgroup)
8481 au_remove_pat(ap);
8482 }
8483 else if (group == AUGROUP_ALL || ap->group == group)
8484 show_autocmd(ap, event);
8485 }
8486 }
8487
8488 /*
8489 * Loop through all the specified patterns.
8490 */
8491 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8492 {
8493 /*
8494 * Find end of the pattern.
8495 * Watch out for a comma in braces, like "*.\{obj,o\}".
8496 */
8497 brace_level = 0;
8498 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8499 || endpat[-1] == '\\'); ++endpat)
8500 {
8501 if (*endpat == '{')
8502 brace_level++;
8503 else if (*endpat == '}')
8504 brace_level--;
8505 }
8506 if (pat == endpat) /* ignore single comma */
8507 continue;
8508 patlen = (int)(endpat - pat);
8509
8510 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008511 * detect special <buflocal[=X]> buffer-local patterns
8512 */
8513 is_buflocal = FALSE;
8514 buflocal_nr = 0;
8515
8516 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8517 && pat[patlen - 1] == '>')
8518 {
8519 /* Error will be printed only for addition. printing and removing
8520 * will proceed silently. */
8521 is_buflocal = TRUE;
8522 if (patlen == 8)
8523 buflocal_nr = curbuf->b_fnum;
8524 else if (patlen > 9 && pat[7] == '=')
8525 {
8526 /* <buffer=abuf> */
8527 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8528 buflocal_nr = autocmd_bufnr;
8529 /* <buffer=123> */
8530 else if (skipdigits(pat + 8) == pat + patlen - 1)
8531 buflocal_nr = atoi((char *)pat + 8);
8532 }
8533 }
8534
8535 if (is_buflocal)
8536 {
8537 /* normalize pat into standard "<buffer>#N" form */
8538 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8539 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008540 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008541 }
8542
8543 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008544 * Find AutoPat entries with this pattern.
8545 */
8546 prev_ap = &first_autopat[(int)event];
8547 while ((ap = *prev_ap) != NULL)
8548 {
8549 if (ap->pat != NULL)
8550 {
8551 /* Accept a pattern when:
8552 * - a group was specified and it's that group, or a group was
8553 * not specified and it's the current group, or a group was
8554 * not specified and we are listing
8555 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008556 * - the pattern matches.
8557 * For <buffer[=X]>, this condition works because we normalize
8558 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008559 */
8560 if ((allgroups || ap->group == findgroup)
8561 && ap->patlen == patlen
8562 && STRNCMP(pat, ap->pat, patlen) == 0)
8563 {
8564 /*
8565 * Remove existing autocommands.
8566 * If adding any new autocmd's for this AutoPat, don't
8567 * delete the pattern from the autopat list, append to
8568 * this list.
8569 */
8570 if (forceit)
8571 {
8572 if (*cmd != NUL && ap->next == NULL)
8573 {
8574 au_remove_cmds(ap);
8575 break;
8576 }
8577 au_remove_pat(ap);
8578 }
8579
8580 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008581 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008582 */
8583 else if (*cmd == NUL)
8584 show_autocmd(ap, event);
8585
8586 /*
8587 * Add autocmd to this autopat, if it's the last one.
8588 */
8589 else if (ap->next == NULL)
8590 break;
8591 }
8592 }
8593 prev_ap = &ap->next;
8594 }
8595
8596 /*
8597 * Add a new command.
8598 */
8599 if (*cmd != NUL)
8600 {
8601 /*
8602 * If the pattern we want to add a command to does appear at the
8603 * end of the list (or not is not in the list at all), add the
8604 * pattern at the end of the list.
8605 */
8606 if (ap == NULL)
8607 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008608 /* refuse to add buffer-local ap if buffer number is invalid */
8609 if (is_buflocal && (buflocal_nr == 0
8610 || buflist_findnr(buflocal_nr) == NULL))
8611 {
8612 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8613 buflocal_nr);
8614 return FAIL;
8615 }
8616
Bram Moolenaar071d4272004-06-13 20:20:40 +00008617 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8618 if (ap == NULL)
8619 return FAIL;
8620 ap->pat = vim_strnsave(pat, patlen);
8621 ap->patlen = patlen;
8622 if (ap->pat == NULL)
8623 {
8624 vim_free(ap);
8625 return FAIL;
8626 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008627
8628 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008629 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008630 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008631 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008632 }
8633 else
8634 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008635 char_u *reg_pat;
8636
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008637 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008638 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008639 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008640 if (reg_pat != NULL)
8641 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008642 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008643 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008644 {
8645 vim_free(ap->pat);
8646 vim_free(ap);
8647 return FAIL;
8648 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008649 }
8650 ap->cmds = NULL;
8651 *prev_ap = ap;
8652 ap->next = NULL;
8653 if (group == AUGROUP_ALL)
8654 ap->group = current_augroup;
8655 else
8656 ap->group = group;
8657 }
8658
8659 /*
8660 * Add the autocmd at the end of the AutoCmd list.
8661 */
8662 prev_ac = &(ap->cmds);
8663 while ((ac = *prev_ac) != NULL)
8664 prev_ac = &ac->next;
8665 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8666 if (ac == NULL)
8667 return FAIL;
8668 ac->cmd = vim_strsave(cmd);
8669#ifdef FEAT_EVAL
8670 ac->scriptID = current_SID;
8671#endif
8672 if (ac->cmd == NULL)
8673 {
8674 vim_free(ac);
8675 return FAIL;
8676 }
8677 ac->next = NULL;
8678 *prev_ac = ac;
8679 ac->nested = nested;
8680 }
8681 }
8682
8683 au_cleanup(); /* may really delete removed patterns/commands now */
8684 return OK;
8685}
8686
8687/*
8688 * Implementation of ":doautocmd [group] event [fname]".
8689 * Return OK for success, FAIL for failure;
8690 */
8691 int
8692do_doautocmd(arg, do_msg)
8693 char_u *arg;
8694 int do_msg; /* give message for no matching autocmds? */
8695{
8696 char_u *fname;
8697 int nothing_done = TRUE;
8698 int group;
8699
8700 /*
8701 * Check for a legal group name. If not, use AUGROUP_ALL.
8702 */
8703 group = au_get_grouparg(&arg);
8704 if (arg == NULL) /* out of memory */
8705 return FAIL;
8706
8707 if (*arg == '*')
8708 {
8709 EMSG(_("E217: Can't execute autocommands for ALL events"));
8710 return FAIL;
8711 }
8712
8713 /*
8714 * Scan over the events.
8715 * If we find an illegal name, return here, don't do anything.
8716 */
8717 fname = find_end_event(arg, group != AUGROUP_ALL);
8718 if (fname == NULL)
8719 return FAIL;
8720
8721 fname = skipwhite(fname);
8722
8723 /*
8724 * Loop over the events.
8725 */
8726 while (*arg && !vim_iswhite(*arg))
8727 if (apply_autocmds_group(event_name2nr(arg, &arg),
8728 fname, NULL, TRUE, group, curbuf, NULL))
8729 nothing_done = FALSE;
8730
8731 if (nothing_done && do_msg)
8732 MSG(_("No matching autocommands"));
8733
8734#ifdef FEAT_EVAL
8735 return aborting() ? FAIL : OK;
8736#else
8737 return OK;
8738#endif
8739}
8740
8741/*
8742 * ":doautoall": execute autocommands for each loaded buffer.
8743 */
8744 void
8745ex_doautoall(eap)
8746 exarg_T *eap;
8747{
8748 int retval;
8749 aco_save_T aco;
8750 buf_T *buf;
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008751 char_u *arg = eap->arg;
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008752 int call_do_modelines = check_nomodeline(&arg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008753
8754 /*
8755 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8756 * equal to curbuf, but for some buffers there may not be a window.
8757 * So we change the buffer for the current window for a moment. This
8758 * gives problems when the autocommands make changes to the list of
8759 * buffers or windows...
8760 */
8761 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8762 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008763 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008764 {
8765 /* find a window for this buffer and save some values */
8766 aucmd_prepbuf(&aco, buf);
8767
8768 /* execute the autocommands for this buffer */
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008769 retval = do_doautocmd(arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008770
Bram Moolenaara61d5fb2012-02-12 00:18:58 +01008771 if (call_do_modelines)
8772 {
8773 /* Execute the modeline settings, but don't set window-local
8774 * options if we are using the current window for another
8775 * buffer. */
8776 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
8777 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008778
8779 /* restore the current window */
8780 aucmd_restbuf(&aco);
8781
8782 /* stop if there is some error or buffer was deleted */
8783 if (retval == FAIL || !buf_valid(buf))
8784 break;
8785 }
8786 }
8787
8788 check_cursor(); /* just in case lines got deleted */
8789}
8790
8791/*
Bram Moolenaar60542ac2012-02-12 20:14:01 +01008792 * Check *argp for <nomodeline>. When it is present return FALSE, otherwise
8793 * return TRUE and advance *argp to after it.
8794 * Thus return TRUE when do_modelines() should be called.
8795 */
8796 int
8797check_nomodeline(argp)
8798 char_u **argp;
8799{
8800 if (STRNCMP(*argp, "<nomodeline>", 12) == 0)
8801 {
8802 *argp = skipwhite(*argp + 12);
8803 return FALSE;
8804 }
8805 return TRUE;
8806}
8807
8808/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008809 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008810 * Search for a visible window containing the current buffer. If there isn't
8811 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008812 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008813 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008814 */
8815 void
8816aucmd_prepbuf(aco, buf)
8817 aco_save_T *aco; /* structure to save values in */
8818 buf_T *buf; /* new curbuf */
8819{
8820 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008821#ifdef FEAT_WINDOWS
8822 int save_ea;
8823#endif
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008824#ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008825 int save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008826#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008827
8828 /* Find a window that is for the new buffer */
8829 if (buf == curbuf) /* be quick when buf is curbuf */
8830 win = curwin;
8831 else
8832#ifdef FEAT_WINDOWS
8833 for (win = firstwin; win != NULL; win = win->w_next)
8834 if (win->w_buffer == buf)
8835 break;
8836#else
8837 win = NULL;
8838#endif
8839
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008840 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8841 * back to using the current window. */
8842 if (win == NULL && aucmd_win == NULL)
8843 {
8844 win_alloc_aucmd_win();
8845 if (aucmd_win == NULL)
8846 win = curwin;
8847 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008848 if (win == NULL && aucmd_win_used)
8849 /* Strange recursive autocommand, fall back to using the current
8850 * window. Expect a few side effects... */
8851 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008852
8853 aco->save_curwin = curwin;
8854 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008855 if (win != NULL)
8856 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008857 /* There is a window for "buf" in the current tab page, make it the
8858 * curwin. This is preferred, it has the least side effects (esp. if
8859 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008860 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008861 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008862 }
8863 else
8864 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008865 /* There is no window for "buf", use "aucmd_win". To minimize the side
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02008866 * effects, insert it in the current tab page.
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008867 * Anything related to a window (e.g., setting folds) may have
8868 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008869 aco->use_aucmd_win = TRUE;
8870 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008871 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008872 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008873 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008874 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008875
8876 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8877 * win_enter_ext(). */
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008878 vim_free(aucmd_win->w_localdir);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008879 aucmd_win->w_localdir = NULL;
8880 aco->globaldir = globaldir;
8881 globaldir = NULL;
8882
Bram Moolenaar071d4272004-06-13 20:20:40 +00008883
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008884#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008885 /* Split the current window, put the aucmd_win in the upper half.
8886 * We don't want the BufEnter or WinEnter autocommands. */
8887 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008888 make_snapshot(SNAP_AUCMD_IDX);
8889 save_ea = p_ea;
8890 p_ea = FALSE;
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008891
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008892# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008893 /* Prevent chdir() call in win_enter_ext(), through do_autochdir(). */
8894 save_acd = p_acd;
8895 p_acd = FALSE;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008896# endif
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008897
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008898 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8899 (void)win_comp_pos(); /* recompute window positions */
8900 p_ea = save_ea;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008901# ifdef FEAT_AUTOCHDIR
Bram Moolenaar4008f4f2013-08-02 17:08:13 +02008902 p_acd = save_acd;
Bram Moolenaar01c458e2013-08-05 22:02:20 +02008903# endif
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008904 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008905#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008906 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008907 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008908 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008909 aco->new_curwin = curwin;
8910 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008911}
8912
8913/*
8914 * Cleanup after executing autocommands for a (hidden) buffer.
8915 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008916 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008917 */
8918 void
8919aucmd_restbuf(aco)
8920 aco_save_T *aco; /* structure holding saved values */
8921{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008922#ifdef FEAT_WINDOWS
8923 int dummy;
8924#endif
8925
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008926 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008927 {
8928 --curbuf->b_nwindows;
8929#ifdef FEAT_WINDOWS
8930 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008931 * page. Do not trigger autocommands here. */
8932 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008933 if (curwin != aucmd_win)
8934 {
8935 tabpage_T *tp;
8936 win_T *wp;
8937
8938 FOR_ALL_TAB_WINDOWS(tp, wp)
8939 {
8940 if (wp == aucmd_win)
8941 {
8942 if (tp != curtab)
Bram Moolenaar49e649f2013-05-06 04:50:35 +02008943 goto_tabpage_tp(tp, TRUE, TRUE);
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008944 win_goto(aucmd_win);
Bram Moolenaar28f29082012-02-11 23:45:37 +01008945 goto win_found;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008946 }
8947 }
8948 }
Bram Moolenaar28f29082012-02-11 23:45:37 +01008949win_found:
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008950
8951 /* Remove the window and frame from the tree of frames. */
8952 (void)winframe_remove(curwin, &dummy, NULL);
8953 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008954 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008955 last_status(FALSE); /* may need to remove last status line */
8956 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8957 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008958 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008959
8960 if (win_valid(aco->save_curwin))
8961 curwin = aco->save_curwin;
8962 else
8963 /* Hmm, original window disappeared. Just use the first one. */
8964 curwin = firstwin;
8965# ifdef FEAT_EVAL
Bram Moolenaar429fa852013-04-15 12:27:36 +02008966 vars_clear(&aucmd_win->w_vars->dv_hashtab); /* free all w: variables */
8967 hash_init(&aucmd_win->w_vars->dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008968# endif
8969#else
8970 curwin = aco->save_curwin;
8971#endif
8972 curbuf = curwin->w_buffer;
8973
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008974 vim_free(globaldir);
8975 globaldir = aco->globaldir;
8976
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008977 /* the buffer contents may have changed */
8978 check_cursor();
8979 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8980 {
8981 curwin->w_topline = curbuf->b_ml.ml_line_count;
8982#ifdef FEAT_DIFF
8983 curwin->w_topfill = 0;
8984#endif
8985 }
8986#if defined(FEAT_GUI)
8987 /* Hide the scrollbars from the aucmd_win and update. */
8988 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8989 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8990 gui_may_update_scrollbars();
8991#endif
8992 }
8993 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008994 {
8995 /* restore curwin */
8996#ifdef FEAT_WINDOWS
8997 if (win_valid(aco->save_curwin))
8998#endif
8999 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009000 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00009001 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009002 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009003 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009004 && curbuf != aco->new_curbuf
9005 && buf_valid(aco->new_curbuf)
9006 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009007 {
Bram Moolenaar7da9c372012-04-30 17:04:52 +02009008# if defined(FEAT_SYN_HL) || defined(FEAT_SPELL)
9009 if (curwin->w_s == &curbuf->b_s)
9010 curwin->w_s = &aco->new_curbuf->b_s;
9011# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009012 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009013 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009014 curwin->w_buffer = curbuf;
9015 ++curbuf->b_nwindows;
9016 }
9017
9018 curwin = aco->save_curwin;
9019 curbuf = curwin->w_buffer;
Bram Moolenaar371932a2014-09-09 16:59:38 +02009020 /* In case the autocommand move the cursor to a position that that
9021 * not exist in curbuf. */
9022 check_cursor();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009023 }
9024 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009025}
9026
9027static int autocmd_nested = FALSE;
9028
9029/*
9030 * Execute autocommands for "event" and file name "fname".
9031 * Return TRUE if some commands were executed.
9032 */
9033 int
9034apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009035 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009036 char_u *fname; /* NULL or empty means use actual file name */
9037 char_u *fname_io; /* fname to use for <afile> on cmdline */
9038 int force; /* when TRUE, ignore autocmd_busy */
9039 buf_T *buf; /* buffer for <abuf> */
9040{
9041 return apply_autocmds_group(event, fname, fname_io, force,
9042 AUGROUP_ALL, buf, NULL);
9043}
9044
9045/*
9046 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
9047 * setting v:filearg.
9048 */
9049 static int
9050apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009051 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009052 char_u *fname;
9053 char_u *fname_io;
9054 int force;
9055 buf_T *buf;
9056 exarg_T *eap;
9057{
9058 return apply_autocmds_group(event, fname, fname_io, force,
9059 AUGROUP_ALL, buf, eap);
9060}
9061
9062/*
9063 * Like apply_autocmds(), but handles the caller's retval. If the script
9064 * processing is being aborted or if retval is FAIL when inside a try
9065 * conditional, no autocommands are executed. If otherwise the autocommands
9066 * cause the script to be aborted, retval is set to FAIL.
9067 */
9068 int
9069apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009070 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009071 char_u *fname; /* NULL or empty means use actual file name */
9072 char_u *fname_io; /* fname to use for <afile> on cmdline */
9073 int force; /* when TRUE, ignore autocmd_busy */
9074 buf_T *buf; /* buffer for <abuf> */
9075 int *retval; /* pointer to caller's retval */
9076{
9077 int did_cmd;
9078
Bram Moolenaar1e015462005-09-25 22:16:38 +00009079#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009080 if (should_abort(*retval))
9081 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009082#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009083
9084 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9085 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009086 if (did_cmd
9087#ifdef FEAT_EVAL
9088 && aborting()
9089#endif
9090 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009091 *retval = FAIL;
9092 return did_cmd;
9093}
9094
Bram Moolenaard35f9712005-12-18 22:02:33 +00009095/*
9096 * Return TRUE when there is a CursorHold autocommand defined.
9097 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009098 int
9099has_cursorhold()
9100{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009101 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9102 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009103}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009104
9105/*
9106 * Return TRUE if the CursorHold event can be triggered.
9107 */
9108 int
9109trigger_cursorhold()
9110{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009111 int state;
9112
Bram Moolenaar05334432011-07-20 18:29:39 +02009113 if (!did_cursorhold
9114 && has_cursorhold()
9115 && !Recording
9116 && typebuf.tb_len == 0
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009117#ifdef FEAT_INS_EXPAND
9118 && !ins_compl_active()
9119#endif
9120 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009121 {
9122 state = get_real_state();
9123 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9124 return TRUE;
9125 }
9126 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009127}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009128
9129/*
9130 * Return TRUE when there is a CursorMoved autocommand defined.
9131 */
9132 int
9133has_cursormoved()
9134{
9135 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9136}
9137
9138/*
9139 * Return TRUE when there is a CursorMovedI autocommand defined.
9140 */
9141 int
9142has_cursormovedI()
9143{
9144 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9145}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009146
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009147/*
Bram Moolenaar186628f2013-03-19 13:33:23 +01009148 * Return TRUE when there is a TextChanged autocommand defined.
9149 */
9150 int
9151has_textchanged()
9152{
9153 return (first_autopat[(int)EVENT_TEXTCHANGED] != NULL);
9154}
9155
9156/*
9157 * Return TRUE when there is a TextChangedI autocommand defined.
9158 */
9159 int
9160has_textchangedI()
9161{
9162 return (first_autopat[(int)EVENT_TEXTCHANGEDI] != NULL);
9163}
9164
9165/*
Bram Moolenaarf5876f12012-02-29 18:22:08 +01009166 * Return TRUE when there is an InsertCharPre autocommand defined.
9167 */
9168 int
9169has_insertcharpre()
9170{
9171 return (first_autopat[(int)EVENT_INSERTCHARPRE] != NULL);
9172}
9173
Bram Moolenaard5005162014-08-22 23:05:54 +02009174/*
9175 * Return TRUE when there is an CmdUndefined autocommand defined.
9176 */
9177 int
9178has_cmdundefined()
9179{
9180 return (first_autopat[(int)EVENT_CMDUNDEFINED] != NULL);
9181}
9182
9183/*
9184 * Return TRUE when there is an FuncUndefined autocommand defined.
9185 */
9186 int
9187has_funcundefined()
9188{
9189 return (first_autopat[(int)EVENT_FUNCUNDEFINED] != NULL);
9190}
9191
Bram Moolenaar071d4272004-06-13 20:20:40 +00009192 static int
9193apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009194 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009195 char_u *fname; /* NULL or empty means use actual file name */
9196 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9197 use fname */
9198 int force; /* when TRUE, ignore autocmd_busy */
9199 int group; /* group ID, or AUGROUP_ALL */
9200 buf_T *buf; /* buffer for <abuf> */
9201 exarg_T *eap; /* command arguments */
9202{
9203 char_u *sfname = NULL; /* short file name */
9204 char_u *tail;
9205 int save_changed;
9206 buf_T *old_curbuf;
9207 int retval = FALSE;
9208 char_u *save_sourcing_name;
9209 linenr_T save_sourcing_lnum;
9210 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009211 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009212 int save_autocmd_bufnr;
9213 char_u *save_autocmd_match;
9214 int save_autocmd_busy;
9215 int save_autocmd_nested;
9216 static int nesting = 0;
9217 AutoPatCmd patcmd;
9218 AutoPat *ap;
9219#ifdef FEAT_EVAL
9220 scid_T save_current_SID;
9221 void *save_funccalp;
9222 char_u *save_cmdarg;
9223 long save_cmdbang;
9224#endif
9225 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009226#ifdef FEAT_PROFILE
9227 proftime_T wait_time;
9228#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009229
9230 /*
9231 * Quickly return if there are no autocommands for this event or
9232 * autocommands are blocked.
9233 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009234 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009235 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009236
9237 /*
9238 * When autocommands are busy, new autocommands are only executed when
9239 * explicitly enabled with the "nested" flag.
9240 */
9241 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009242 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009243
9244#ifdef FEAT_EVAL
9245 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009246 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009247 * occurred or an exception was thrown but not caught.
9248 */
9249 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009250 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009251#endif
9252
9253 /*
9254 * FileChangedShell never nests, because it can create an endless loop.
9255 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009256 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9257 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009258 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009259
9260 /*
9261 * Ignore events in 'eventignore'.
9262 */
9263 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009264 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009265
9266 /*
9267 * Allow nesting of autocommands, but restrict the depth, because it's
9268 * possible to create an endless loop.
9269 */
9270 if (nesting == 10)
9271 {
9272 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009273 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009274 }
9275
9276 /*
9277 * Check if these autocommands are disabled. Used when doing ":all" or
9278 * ":ball".
9279 */
9280 if ( (autocmd_no_enter
9281 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9282 || (autocmd_no_leave
9283 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009284 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009285
9286 /*
9287 * Save the autocmd_* variables and info about the current buffer.
9288 */
9289 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009290 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009291 save_autocmd_bufnr = autocmd_bufnr;
9292 save_autocmd_match = autocmd_match;
9293 save_autocmd_busy = autocmd_busy;
9294 save_autocmd_nested = autocmd_nested;
9295 save_changed = curbuf->b_changed;
9296 old_curbuf = curbuf;
9297
9298 /*
9299 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009300 * Make a copy to avoid that changing a buffer name or directory makes it
9301 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009302 */
9303 if (fname_io == NULL)
9304 {
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009305 if (event == EVENT_COLORSCHEME)
9306 autocmd_fname = NULL;
9307 else if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009308 autocmd_fname = fname;
9309 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009310 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009311 else
9312 autocmd_fname = NULL;
9313 }
9314 else
9315 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009316 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009317 autocmd_fname = vim_strsave(autocmd_fname);
9318 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009319
9320 /*
9321 * Set the buffer number to be used for <abuf>.
9322 */
9323 if (buf == NULL)
9324 autocmd_bufnr = 0;
9325 else
9326 autocmd_bufnr = buf->b_fnum;
9327
9328 /*
9329 * When the file name is NULL or empty, use the file name of buffer "buf".
9330 * Always use the full path of the file name to match with, in case
9331 * "allow_dirs" is set.
9332 */
9333 if (fname == NULL || *fname == NUL)
9334 {
9335 if (buf == NULL)
9336 fname = NULL;
9337 else
9338 {
9339#ifdef FEAT_SYN_HL
9340 if (event == EVENT_SYNTAX)
9341 fname = buf->b_p_syn;
9342 else
9343#endif
9344 if (event == EVENT_FILETYPE)
9345 fname = buf->b_p_ft;
9346 else
9347 {
9348 if (buf->b_sfname != NULL)
9349 sfname = vim_strsave(buf->b_sfname);
9350 fname = buf->b_ffname;
9351 }
9352 }
9353 if (fname == NULL)
9354 fname = (char_u *)"";
9355 fname = vim_strsave(fname); /* make a copy, so we can change it */
9356 }
9357 else
9358 {
9359 sfname = vim_strsave(fname);
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009360 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID,
9361 * ColorScheme or QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009362 if (event == EVENT_FILETYPE
9363 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009364 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009365 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009366 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009367 || event == EVENT_QUICKFIXCMDPRE
Bram Moolenaarb95186f2013-11-28 18:53:52 +01009368 || event == EVENT_COLORSCHEME
Bram Moolenaar7c626922005-02-07 22:01:03 +00009369 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009370 fname = vim_strsave(fname);
9371 else
9372 fname = FullName_save(fname, FALSE);
9373 }
9374 if (fname == NULL) /* out of memory */
9375 {
9376 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009377 retval = FALSE;
9378 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009379 }
9380
9381#ifdef BACKSLASH_IN_FILENAME
9382 /*
9383 * Replace all backslashes with forward slashes. This makes the
9384 * autocommand patterns portable between Unix and MS-DOS.
9385 */
9386 if (sfname != NULL)
9387 forward_slash(sfname);
9388 forward_slash(fname);
9389#endif
9390
9391#ifdef VMS
9392 /* remove version for correct match */
9393 if (sfname != NULL)
9394 vms_remove_version(sfname);
9395 vms_remove_version(fname);
9396#endif
9397
9398 /*
9399 * Set the name to be used for <amatch>.
9400 */
9401 autocmd_match = fname;
9402
9403
9404 /* Don't redraw while doing auto commands. */
9405 ++RedrawingDisabled;
9406 save_sourcing_name = sourcing_name;
9407 sourcing_name = NULL; /* don't free this one */
9408 save_sourcing_lnum = sourcing_lnum;
9409 sourcing_lnum = 0; /* no line number here */
9410
9411#ifdef FEAT_EVAL
9412 save_current_SID = current_SID;
9413
Bram Moolenaar05159a02005-02-26 23:04:13 +00009414# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009415 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009416 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9417# endif
9418
Bram Moolenaar071d4272004-06-13 20:20:40 +00009419 /* Don't use local function variables, if called from a function */
9420 save_funccalp = save_funccal();
9421#endif
9422
9423 /*
9424 * When starting to execute autocommands, save the search patterns.
9425 */
9426 if (!autocmd_busy)
9427 {
9428 save_search_patterns();
9429 saveRedobuff();
9430 did_filetype = keep_filetype;
9431 }
9432
9433 /*
9434 * Note that we are applying autocmds. Some commands need to know.
9435 */
9436 autocmd_busy = TRUE;
9437 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9438 ++nesting; /* see matching decrement below */
9439
9440 /* Remember that FileType was triggered. Used for did_filetype(). */
9441 if (event == EVENT_FILETYPE)
9442 did_filetype = TRUE;
9443
9444 tail = gettail(fname);
9445
9446 /* Find first autocommand that matches */
9447 patcmd.curpat = first_autopat[(int)event];
9448 patcmd.nextcmd = NULL;
9449 patcmd.group = group;
9450 patcmd.fname = fname;
9451 patcmd.sfname = sfname;
9452 patcmd.tail = tail;
9453 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009454 patcmd.arg_bufnr = autocmd_bufnr;
9455 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009456 auto_next_pat(&patcmd, FALSE);
9457
9458 /* found one, start executing the autocommands */
9459 if (patcmd.curpat != NULL)
9460 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009461 /* add to active_apc_list */
9462 patcmd.next = active_apc_list;
9463 active_apc_list = &patcmd;
9464
Bram Moolenaar071d4272004-06-13 20:20:40 +00009465#ifdef FEAT_EVAL
9466 /* set v:cmdarg (only when there is a matching pattern) */
9467 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9468 if (eap != NULL)
9469 {
9470 save_cmdarg = set_cmdarg(eap, NULL);
9471 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9472 }
9473 else
9474 save_cmdarg = NULL; /* avoid gcc warning */
9475#endif
9476 retval = TRUE;
9477 /* mark the last pattern, to avoid an endless loop when more patterns
9478 * are added when executing autocommands */
9479 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9480 ap->last = FALSE;
9481 ap->last = TRUE;
9482 check_lnums(TRUE); /* make sure cursor and topline are valid */
9483 do_cmdline(NULL, getnextac, (void *)&patcmd,
9484 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9485#ifdef FEAT_EVAL
9486 if (eap != NULL)
9487 {
9488 (void)set_cmdarg(NULL, save_cmdarg);
9489 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9490 }
9491#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009492 /* delete from active_apc_list */
9493 if (active_apc_list == &patcmd) /* just in case */
9494 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009495 }
9496
9497 --RedrawingDisabled;
9498 autocmd_busy = save_autocmd_busy;
9499 filechangeshell_busy = FALSE;
9500 autocmd_nested = save_autocmd_nested;
9501 vim_free(sourcing_name);
9502 sourcing_name = save_sourcing_name;
9503 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009504 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009505 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009506 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009507 autocmd_bufnr = save_autocmd_bufnr;
9508 autocmd_match = save_autocmd_match;
9509#ifdef FEAT_EVAL
9510 current_SID = save_current_SID;
9511 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009512# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009513 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009514 prof_child_exit(&wait_time);
9515# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009516#endif
9517 vim_free(fname);
9518 vim_free(sfname);
9519 --nesting; /* see matching increment above */
9520
9521 /*
9522 * When stopping to execute autocommands, restore the search patterns and
Bram Moolenaar3be85852014-06-12 14:01:31 +02009523 * the redo buffer. Free any buffers in the au_pending_free_buf list and
9524 * free any windows in the au_pending_free_win list.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009525 */
9526 if (!autocmd_busy)
9527 {
9528 restore_search_patterns();
9529 restoreRedobuff();
9530 did_filetype = FALSE;
Bram Moolenaar4c7ab1b2014-04-06 20:45:43 +02009531 while (au_pending_free_buf != NULL)
9532 {
9533 buf_T *b = au_pending_free_buf->b_next;
9534 vim_free(au_pending_free_buf);
9535 au_pending_free_buf = b;
9536 }
Bram Moolenaar3be85852014-06-12 14:01:31 +02009537 while (au_pending_free_win != NULL)
9538 {
9539 win_T *w = au_pending_free_win->w_next;
9540 vim_free(au_pending_free_win);
9541 au_pending_free_win = w;
9542 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009543 }
9544
9545 /*
9546 * Some events don't set or reset the Changed flag.
9547 * Check if still in the same buffer!
9548 */
9549 if (curbuf == old_curbuf
9550 && (event == EVENT_BUFREADPOST
9551 || event == EVENT_BUFWRITEPOST
9552 || event == EVENT_FILEAPPENDPOST
9553 || event == EVENT_VIMLEAVE
9554 || event == EVENT_VIMLEAVEPRE))
9555 {
9556#ifdef FEAT_TITLE
9557 if (curbuf->b_changed != save_changed)
9558 need_maketitle = TRUE;
9559#endif
9560 curbuf->b_changed = save_changed;
9561 }
9562
9563 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009564
9565BYPASS_AU:
9566 /* When wiping out a buffer make sure all its buffer-local autocommands
9567 * are deleted. */
9568 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9569 aubuflocal_remove(buf);
9570
Bram Moolenaar071d4272004-06-13 20:20:40 +00009571 return retval;
9572}
9573
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009574# ifdef FEAT_EVAL
9575static char_u *old_termresponse = NULL;
9576# endif
9577
9578/*
9579 * Block triggering autocommands until unblock_autocmd() is called.
9580 * Can be used recursively, so long as it's symmetric.
9581 */
9582 void
9583block_autocmds()
9584{
9585# ifdef FEAT_EVAL
9586 /* Remember the value of v:termresponse. */
9587 if (autocmd_blocked == 0)
9588 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9589# endif
9590 ++autocmd_blocked;
9591}
9592
9593 void
9594unblock_autocmds()
9595{
9596 --autocmd_blocked;
9597
9598# ifdef FEAT_EVAL
9599 /* When v:termresponse was set while autocommands were blocked, trigger
9600 * the autocommands now. Esp. useful when executing a shell command
9601 * during startup (vimdiff). */
9602 if (autocmd_blocked == 0
9603 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9604 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9605# endif
9606}
9607
Bram Moolenaarabab85a2013-06-26 19:18:05 +02009608 int
9609is_autocmd_blocked()
9610{
9611 return autocmd_blocked != 0;
9612}
9613
Bram Moolenaar071d4272004-06-13 20:20:40 +00009614/*
9615 * Find next autocommand pattern that matches.
9616 */
9617 static void
9618auto_next_pat(apc, stop_at_last)
9619 AutoPatCmd *apc;
9620 int stop_at_last; /* stop when 'last' flag is set */
9621{
9622 AutoPat *ap;
9623 AutoCmd *cp;
9624 char_u *name;
9625 char *s;
9626
9627 vim_free(sourcing_name);
9628 sourcing_name = NULL;
9629
9630 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9631 {
9632 apc->curpat = NULL;
9633
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009634 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009635 * the group matches. For buffer-local autocommands only check the
9636 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009637 if (ap->pat != NULL && ap->cmds != NULL
9638 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9639 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009640 /* execution-condition */
9641 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009642 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9643 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009644 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009645 {
9646 name = event_nr2name(apc->event);
9647 s = _("%s Auto commands for \"%s\"");
9648 sourcing_name = alloc((unsigned)(STRLEN(s)
9649 + STRLEN(name) + ap->patlen + 1));
9650 if (sourcing_name != NULL)
9651 {
9652 sprintf((char *)sourcing_name, s,
9653 (char *)name, (char *)ap->pat);
9654 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009655 {
9656 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009657 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009658 verbose_leave();
9659 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009660 }
9661
9662 apc->curpat = ap;
9663 apc->nextcmd = ap->cmds;
9664 /* mark last command */
9665 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9666 cp->last = FALSE;
9667 cp->last = TRUE;
9668 }
9669 line_breakcheck();
9670 if (apc->curpat != NULL) /* found a match */
9671 break;
9672 }
9673 if (stop_at_last && ap->last)
9674 break;
9675 }
9676}
9677
9678/*
9679 * Get next autocommand command.
9680 * Called by do_cmdline() to get the next line for ":if".
9681 * Returns allocated string, or NULL for end of autocommands.
9682 */
Bram Moolenaar21691f82012-12-05 19:13:18 +01009683 char_u *
Bram Moolenaar071d4272004-06-13 20:20:40 +00009684getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009685 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009686 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009687 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009688{
9689 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9690 char_u *retval;
9691 AutoCmd *ac;
9692
9693 /* Can be called again after returning the last line. */
9694 if (acp->curpat == NULL)
9695 return NULL;
9696
9697 /* repeat until we find an autocommand to execute */
9698 for (;;)
9699 {
9700 /* skip removed commands */
9701 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9702 if (acp->nextcmd->last)
9703 acp->nextcmd = NULL;
9704 else
9705 acp->nextcmd = acp->nextcmd->next;
9706
9707 if (acp->nextcmd != NULL)
9708 break;
9709
9710 /* at end of commands, find next pattern that matches */
9711 if (acp->curpat->last)
9712 acp->curpat = NULL;
9713 else
9714 acp->curpat = acp->curpat->next;
9715 if (acp->curpat != NULL)
9716 auto_next_pat(acp, TRUE);
9717 if (acp->curpat == NULL)
9718 return NULL;
9719 }
9720
9721 ac = acp->nextcmd;
9722
9723 if (p_verbose >= 9)
9724 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009725 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009726 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009727 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009728 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009729 }
9730 retval = vim_strsave(ac->cmd);
9731 autocmd_nested = ac->nested;
9732#ifdef FEAT_EVAL
9733 current_SID = ac->scriptID;
9734#endif
9735 if (ac->last)
9736 acp->nextcmd = NULL;
9737 else
9738 acp->nextcmd = ac->next;
9739 return retval;
9740}
9741
9742/*
9743 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009744 * To account for buffer-local autocommands, function needs to know
9745 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009746 */
9747 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009748has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009749 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009750 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009751 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009752{
9753 AutoPat *ap;
9754 char_u *fname;
9755 char_u *tail = gettail(sfname);
9756 int retval = FALSE;
9757
9758 fname = FullName_save(sfname, FALSE);
9759 if (fname == NULL)
9760 return FALSE;
9761
9762#ifdef BACKSLASH_IN_FILENAME
9763 /*
9764 * Replace all backslashes with forward slashes. This makes the
9765 * autocommand patterns portable between Unix and MS-DOS.
9766 */
9767 sfname = vim_strsave(sfname);
9768 if (sfname != NULL)
9769 forward_slash(sfname);
9770 forward_slash(fname);
9771#endif
9772
9773 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9774 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009775 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009776 ? match_file_pat(NULL, ap->reg_prog,
9777 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009778 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009779 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009780 {
9781 retval = TRUE;
9782 break;
9783 }
9784
9785 vim_free(fname);
9786#ifdef BACKSLASH_IN_FILENAME
9787 vim_free(sfname);
9788#endif
9789
9790 return retval;
9791}
9792
9793#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9794/*
9795 * Function given to ExpandGeneric() to obtain the list of autocommand group
9796 * names.
9797 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009798 char_u *
9799get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009800 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009801 int idx;
9802{
9803 if (idx == augroups.ga_len) /* add "END" add the end */
9804 return (char_u *)"END";
9805 if (idx >= augroups.ga_len) /* end of list */
9806 return NULL;
9807 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9808 return (char_u *)"";
9809 return AUGROUP_NAME(idx); /* return a name */
9810}
9811
9812static int include_groups = FALSE;
9813
9814 char_u *
9815set_context_in_autocmd(xp, arg, doautocmd)
9816 expand_T *xp;
9817 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009818 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009819{
9820 char_u *p;
9821 int group;
9822
9823 /* check for a group name, skip it if present */
9824 include_groups = FALSE;
9825 p = arg;
9826 group = au_get_grouparg(&arg);
9827 if (group == AUGROUP_ERROR)
9828 return NULL;
9829 /* If there only is a group name that's what we expand. */
9830 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9831 {
9832 arg = p;
9833 group = AUGROUP_ALL;
9834 }
9835
9836 /* skip over event name */
9837 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9838 if (*p == ',')
9839 arg = p + 1;
9840 if (*p == NUL)
9841 {
9842 if (group == AUGROUP_ALL)
9843 include_groups = TRUE;
9844 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9845 xp->xp_pattern = arg;
9846 return NULL;
9847 }
9848
9849 /* skip over pattern */
9850 arg = skipwhite(p);
9851 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9852 arg++;
9853 if (*arg)
9854 return arg; /* expand (next) command */
9855
9856 if (doautocmd)
9857 xp->xp_context = EXPAND_FILES; /* expand file names */
9858 else
9859 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9860 return NULL;
9861}
9862
9863/*
9864 * Function given to ExpandGeneric() to obtain the list of event names.
9865 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009866 char_u *
9867get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009868 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009869 int idx;
9870{
9871 if (idx < augroups.ga_len) /* First list group names, if wanted */
9872 {
9873 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9874 return (char_u *)""; /* skip deleted entries */
9875 return AUGROUP_NAME(idx); /* return a name */
9876 }
9877 return (char_u *)event_names[idx - augroups.ga_len].name;
9878}
9879
9880#endif /* FEAT_CMDL_COMPL */
9881
9882/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009883 * Return TRUE if autocmd is supported.
9884 */
9885 int
9886autocmd_supported(name)
9887 char_u *name;
9888{
9889 char_u *p;
9890
9891 return (event_name2nr(name, &p) != NUM_EVENTS);
9892}
9893
9894/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009895 * Return TRUE if an autocommand is defined for a group, event and
9896 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9897 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9898 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9899 * Used for:
9900 * exists("#Group") or
9901 * exists("#Group#Event") or
9902 * exists("#Group#Event#pat") or
9903 * exists("#Event") or
9904 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009905 */
9906 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009907au_exists(arg)
9908 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009909{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009910 char_u *arg_save;
9911 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009912 char_u *event_name;
9913 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009914 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009915 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009916 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009917 int group;
9918 int retval = FALSE;
9919
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009920 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009921 arg_save = vim_strsave(arg);
9922 if (arg_save == NULL)
9923 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009924 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009925 if (p != NULL)
9926 *p++ = NUL;
9927
9928 /* First, look for an autocmd group name */
9929 group = au_find_group(arg_save);
9930 if (group == AUGROUP_ERROR)
9931 {
9932 /* Didn't match a group name, assume the first argument is an event. */
9933 group = AUGROUP_ALL;
9934 event_name = arg_save;
9935 }
9936 else
9937 {
9938 if (p == NULL)
9939 {
9940 /* "Group": group name is present and it's recognized */
9941 retval = TRUE;
9942 goto theend;
9943 }
9944
9945 /* Must be "Group#Event" or "Group#Event#pat". */
9946 event_name = p;
9947 p = vim_strchr(event_name, '#');
9948 if (p != NULL)
9949 *p++ = NUL; /* "Group#Event#pat" */
9950 }
9951
9952 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009953
9954 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009955 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009956
9957 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009958 if (event == NUM_EVENTS)
9959 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009960
9961 /* Find the first autocommand for this event.
9962 * If there isn't any, return FALSE;
9963 * If there is one and no pattern given, return TRUE; */
9964 ap = first_autopat[(int)event];
9965 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009966 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009967
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009968 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9969 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009970 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009971 buflocal_buf = curbuf;
9972
Bram Moolenaar071d4272004-06-13 20:20:40 +00009973 /* Check if there is an autocommand with the given pattern. */
9974 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009975 /* only use a pattern when it has not been removed and has commands. */
9976 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009977 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009978 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009979 && (pattern == NULL
9980 || (buflocal_buf == NULL
9981 ? fnamecmp(ap->pat, pattern) == 0
9982 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009983 {
9984 retval = TRUE;
9985 break;
9986 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009987
Bram Moolenaar195d6352005-12-19 22:08:24 +00009988theend:
9989 vim_free(arg_save);
9990 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009991}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009992
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009993#else /* FEAT_AUTOCMD */
9994
9995/*
9996 * Prepare for executing commands for (hidden) buffer "buf".
9997 * This is the non-autocommand version, it simply saves "curbuf" and sets
9998 * "curbuf" and "curwin" to match "buf".
9999 */
10000 void
10001aucmd_prepbuf(aco, buf)
10002 aco_save_T *aco; /* structure to save values in */
10003 buf_T *buf; /* new curbuf */
10004{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010005 aco->save_curbuf = curbuf;
10006 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010007 curbuf = buf;
10008 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010009 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010010}
10011
10012/*
10013 * Restore after executing commands for a (hidden) buffer.
10014 * This is the non-autocommand version.
10015 */
10016 void
10017aucmd_restbuf(aco)
10018 aco_save_T *aco; /* structure holding saved values */
10019{
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010020 --curbuf->b_nwindows;
10021 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010022 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +000010023 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010024}
10025
Bram Moolenaar071d4272004-06-13 20:20:40 +000010026#endif /* FEAT_AUTOCMD */
10027
Bram Moolenaarf30e74c2006-08-16 17:35:00 +000010028
Bram Moolenaar071d4272004-06-13 20:20:40 +000010029#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
10030/*
Bram Moolenaar748bf032005-02-02 23:04:36 +000010031 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
10032 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
10033 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +000010034 * Used for autocommands and 'wildignore'.
10035 * Returns TRUE if there is a match, FALSE otherwise.
10036 */
10037 int
Bram Moolenaar748bf032005-02-02 23:04:36 +000010038match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010039 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +000010040 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010041 char_u *fname; /* full path of file name */
10042 char_u *sfname; /* short file name or NULL */
10043 char_u *tail; /* tail of path */
10044 int allow_dirs; /* allow matching with dir */
10045{
10046 regmatch_T regmatch;
10047 int result = FALSE;
10048#ifdef FEAT_OSFILETYPE
10049 int no_pattern = FALSE; /* TRUE if check is filetype only */
10050 char_u *type_start;
10051 char_u c;
10052 int match = FALSE;
10053#endif
10054
Bram Moolenaar71afbfe2013-03-19 16:49:16 +010010055 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010056#ifdef FEAT_OSFILETYPE
10057 if (*pattern == '<')
10058 {
10059 /* There is a filetype condition specified with this pattern.
10060 * Check the filetype matches first. If not, don't bother with the
10061 * pattern (set regprog to NULL).
10062 * Always use magic for the regexp.
10063 */
10064
10065 for (type_start = pattern + 1; (c = *pattern); pattern++)
10066 {
10067 if ((c == ';' || c == '>') && match == FALSE)
10068 {
10069 *pattern = NUL; /* Terminate the string */
Bram Moolenaar05334432011-07-20 18:29:39 +020010070 /* TODO: match with 'filetype' of buffer that "fname" comes
10071 * from. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010072 match = mch_check_filetype(fname, type_start);
10073 *pattern = c; /* Restore the terminator */
10074 type_start = pattern + 1;
10075 }
10076 if (c == '>')
10077 break;
10078 }
10079
10080 /* (c should never be NUL, but check anyway) */
10081 if (match == FALSE || c == NUL)
10082 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
10083 else if (*pattern == NUL)
10084 {
10085 regmatch.regprog = NULL; /* Vim will try to free regprog later */
10086 no_pattern = TRUE; /* Always matches - don't check pat. */
10087 }
10088 else
10089 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
10090 }
10091 else
10092#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +000010093 {
10094 if (prog != NULL)
10095 regmatch.regprog = prog;
10096 else
10097 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
10098 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010099
10100 /*
10101 * Try for a match with the pattern with:
10102 * 1. the full file name, when the pattern has a '/'.
10103 * 2. the short file name, when the pattern has a '/'.
10104 * 3. the tail of the file name, when the pattern has no '/'.
10105 */
10106 if (
10107#ifdef FEAT_OSFILETYPE
10108 /* If the check is for a filetype only and we don't care
10109 * about the path then skip all the regexp stuff.
10110 */
10111 no_pattern ||
10112#endif
10113 (regmatch.regprog != NULL
10114 && ((allow_dirs
10115 && (vim_regexec(&regmatch, fname, (colnr_T)0)
10116 || (sfname != NULL
10117 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
10118 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
10119 result = TRUE;
10120
Bram Moolenaar748bf032005-02-02 23:04:36 +000010121 if (prog == NULL)
Bram Moolenaar473de612013-06-08 18:19:48 +020010122 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010123 return result;
10124}
10125#endif
10126
10127#if defined(FEAT_WILDIGN) || defined(PROTO)
10128/*
10129 * Return TRUE if a file matches with a pattern in "list".
10130 * "list" is a comma-separated list of patterns, like 'wildignore'.
10131 * "sfname" is the short file name or NULL, "ffname" the long file name.
10132 */
10133 int
10134match_file_list(list, sfname, ffname)
10135 char_u *list;
10136 char_u *sfname;
10137 char_u *ffname;
10138{
10139 char_u buf[100];
10140 char_u *tail;
10141 char_u *regpat;
10142 char allow_dirs;
10143 int match;
10144 char_u *p;
10145
10146 tail = gettail(sfname);
10147
10148 /* try all patterns in 'wildignore' */
10149 p = list;
10150 while (*p)
10151 {
10152 copy_option_part(&p, buf, 100, ",");
10153 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10154 if (regpat == NULL)
10155 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010156 match = match_file_pat(regpat, NULL, ffname, sfname,
10157 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010158 vim_free(regpat);
10159 if (match)
10160 return TRUE;
10161 }
10162 return FALSE;
10163}
10164#endif
10165
10166/*
10167 * Convert the given pattern "pat" which has shell style wildcards in it, into
10168 * a regular expression, and return the result in allocated memory. If there
10169 * is a directory path separator to be matched, then TRUE is put in
10170 * allow_dirs, otherwise FALSE is put there -- webb.
10171 * Handle backslashes before special characters, like "\*" and "\ ".
10172 *
10173 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10174 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10175 *
10176 * Returns NULL when out of memory.
10177 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010178 char_u *
10179file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10180 char_u *pat;
10181 char_u *pat_end; /* first char after pattern or NULL */
10182 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010183 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010184{
10185 int size;
10186 char_u *endp;
10187 char_u *reg_pat;
10188 char_u *p;
10189 int i;
10190 int nested = 0;
10191 int add_dollar = TRUE;
10192#ifdef FEAT_OSFILETYPE
10193 int check_length = 0;
10194#endif
10195
10196 if (allow_dirs != NULL)
10197 *allow_dirs = FALSE;
10198 if (pat_end == NULL)
10199 pat_end = pat + STRLEN(pat);
10200
10201#ifdef FEAT_OSFILETYPE
10202 /* Find out how much of the string is the filetype check */
10203 if (*pat == '<')
10204 {
10205 /* Count chars until the next '>' */
10206 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10207 ;
10208 if (p < pat_end)
10209 {
10210 /* Pattern is of the form <.*>.* */
10211 check_length = p - pat + 1;
10212 if (p + 1 >= pat_end)
10213 {
10214 /* The 'pattern' is a filetype check ONLY */
10215 reg_pat = (char_u *)alloc(check_length + 1);
10216 if (reg_pat != NULL)
10217 {
10218 mch_memmove(reg_pat, pat, (size_t)check_length);
10219 reg_pat[check_length] = NUL;
10220 }
10221 return reg_pat;
10222 }
10223 }
10224 /* else: there was no closing '>' - assume it was a normal pattern */
10225
10226 }
10227 pat += check_length;
10228 size = 2 + check_length;
10229#else
10230 size = 2; /* '^' at start, '$' at end */
10231#endif
10232
10233 for (p = pat; p < pat_end; p++)
10234 {
10235 switch (*p)
10236 {
10237 case '*':
10238 case '.':
10239 case ',':
10240 case '{':
10241 case '}':
10242 case '~':
10243 size += 2; /* extra backslash */
10244 break;
10245#ifdef BACKSLASH_IN_FILENAME
10246 case '\\':
10247 case '/':
10248 size += 4; /* could become "[\/]" */
10249 break;
10250#endif
10251 default:
10252 size++;
10253# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010254 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010255 {
10256 ++p;
10257 ++size;
10258 }
10259# endif
10260 break;
10261 }
10262 }
10263 reg_pat = alloc(size + 1);
10264 if (reg_pat == NULL)
10265 return NULL;
10266
10267#ifdef FEAT_OSFILETYPE
10268 /* Copy the type check in to the start. */
10269 if (check_length)
10270 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10271 i = check_length;
10272#else
10273 i = 0;
10274#endif
10275
10276 if (pat[0] == '*')
10277 while (pat[0] == '*' && pat < pat_end - 1)
10278 pat++;
10279 else
10280 reg_pat[i++] = '^';
10281 endp = pat_end - 1;
10282 if (*endp == '*')
10283 {
10284 while (endp - pat > 0 && *endp == '*')
10285 endp--;
10286 add_dollar = FALSE;
10287 }
10288 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10289 {
10290 switch (*p)
10291 {
10292 case '*':
10293 reg_pat[i++] = '.';
10294 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010295 while (p[1] == '*') /* "**" matches like "*" */
10296 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010297 break;
10298 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010299 case '~':
10300 reg_pat[i++] = '\\';
10301 reg_pat[i++] = *p;
10302 break;
10303 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +000010304 reg_pat[i++] = '.';
10305 break;
10306 case '\\':
10307 if (p[1] == NUL)
10308 break;
10309#ifdef BACKSLASH_IN_FILENAME
10310 if (!no_bslash)
10311 {
10312 /* translate:
10313 * "\x" to "\\x" e.g., "dir\file"
10314 * "\*" to "\\.*" e.g., "dir\*.c"
10315 * "\?" to "\\." e.g., "dir\??.c"
10316 * "\+" to "\+" e.g., "fileX\+.c"
10317 */
10318 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10319 && p[1] != '+')
10320 {
10321 reg_pat[i++] = '[';
10322 reg_pat[i++] = '\\';
10323 reg_pat[i++] = '/';
10324 reg_pat[i++] = ']';
10325 if (allow_dirs != NULL)
10326 *allow_dirs = TRUE;
10327 break;
10328 }
10329 }
10330#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010331 /* Undo escaping from ExpandEscape():
10332 * foo\?bar -> foo?bar
10333 * foo\%bar -> foo%bar
10334 * foo\,bar -> foo,bar
10335 * foo\ bar -> foo bar
10336 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010337 * regexp.
10338 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +020010339 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010340 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010341 if (*++p == '?'
10342#ifdef BACKSLASH_IN_FILENAME
10343 && no_bslash
10344#endif
10345 )
10346 reg_pat[i++] = '?';
10347 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +020010348 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaara946afe2013-08-02 15:22:39 +020010349 || *p == ' ' || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010350 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +020010351 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
10352 {
10353 reg_pat[i++] = '\\';
10354 reg_pat[i++] = '{';
10355 p += 2;
10356 }
Bram Moolenaar071d4272004-06-13 20:20:40 +000010357 else
10358 {
10359 if (allow_dirs != NULL && vim_ispathsep(*p)
10360#ifdef BACKSLASH_IN_FILENAME
10361 && (!no_bslash || *p != '\\')
10362#endif
10363 )
10364 *allow_dirs = TRUE;
10365 reg_pat[i++] = '\\';
10366 reg_pat[i++] = *p;
10367 }
10368 break;
10369#ifdef BACKSLASH_IN_FILENAME
10370 case '/':
10371 reg_pat[i++] = '[';
10372 reg_pat[i++] = '\\';
10373 reg_pat[i++] = '/';
10374 reg_pat[i++] = ']';
10375 if (allow_dirs != NULL)
10376 *allow_dirs = TRUE;
10377 break;
10378#endif
10379 case '{':
10380 reg_pat[i++] = '\\';
10381 reg_pat[i++] = '(';
10382 nested++;
10383 break;
10384 case '}':
10385 reg_pat[i++] = '\\';
10386 reg_pat[i++] = ')';
10387 --nested;
10388 break;
10389 case ',':
10390 if (nested)
10391 {
10392 reg_pat[i++] = '\\';
10393 reg_pat[i++] = '|';
10394 }
10395 else
10396 reg_pat[i++] = ',';
10397 break;
10398 default:
10399# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010400 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010401 reg_pat[i++] = *p++;
10402 else
10403# endif
10404 if (allow_dirs != NULL && vim_ispathsep(*p))
10405 *allow_dirs = TRUE;
10406 reg_pat[i++] = *p;
10407 break;
10408 }
10409 }
10410 if (add_dollar)
10411 reg_pat[i++] = '$';
10412 reg_pat[i] = NUL;
10413 if (nested != 0)
10414 {
10415 if (nested < 0)
10416 EMSG(_("E219: Missing {."));
10417 else
10418 EMSG(_("E220: Missing }."));
10419 vim_free(reg_pat);
10420 reg_pat = NULL;
10421 }
10422 return reg_pat;
10423}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010424
10425#if defined(EINTR) || defined(PROTO)
10426/*
10427 * Version of read() that retries when interrupted by EINTR (possibly
10428 * by a SIGWINCH).
10429 */
10430 long
10431read_eintr(fd, buf, bufsize)
10432 int fd;
10433 void *buf;
10434 size_t bufsize;
10435{
10436 long ret;
10437
10438 for (;;)
10439 {
10440 ret = vim_read(fd, buf, bufsize);
10441 if (ret >= 0 || errno != EINTR)
10442 break;
10443 }
10444 return ret;
10445}
10446
10447/*
10448 * Version of write() that retries when interrupted by EINTR (possibly
10449 * by a SIGWINCH).
10450 */
10451 long
10452write_eintr(fd, buf, bufsize)
10453 int fd;
10454 void *buf;
10455 size_t bufsize;
10456{
10457 long ret = 0;
10458 long wlen;
10459
10460 /* Repeat the write() so long it didn't fail, other than being interrupted
10461 * by a signal. */
10462 while (ret < (long)bufsize)
10463 {
Bram Moolenaar9c263032010-12-17 18:06:06 +010010464 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010465 if (wlen < 0)
10466 {
10467 if (errno != EINTR)
10468 break;
10469 }
10470 else
10471 ret += wlen;
10472 }
10473 return ret;
10474}
10475#endif