blob: 2828aa72af4a24dddc61a0456e7bdbb6e231c1cb [file] [log] [blame]
Bram Moolenaar071d4272004-06-13 20:20:40 +00001/* vi:set ts=8 sts=4 sw=4:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
14#if defined(MSDOS) || defined(WIN16) || defined(WIN32) || defined(_WIN64)
Bram Moolenaar362e1a32006-03-06 23:29:24 +000015# include "vimio.h" /* for lseek(), must be before vim.h */
Bram Moolenaar071d4272004-06-13 20:20:40 +000016#endif
17
18#if defined __EMX__
Bram Moolenaar362e1a32006-03-06 23:29:24 +000019# include "vimio.h" /* for mktemp(), CJW 1997-12-03 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000020#endif
21
22#include "vim.h"
23
Bram Moolenaarf4888d02009-12-02 12:31:27 +000024#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000025# include <limits.h> /* for SSIZE_MAX */
26#endif
27
28#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
29# include <utime.h> /* for struct utimbuf */
30#endif
31
32#define BUFSIZE 8192 /* size of normal write buffer */
33#define SMBUFSIZE 256 /* size of emergency write buffer */
34
35#ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +020036/* crypt_magic[0] is pkzip crypt, crypt_magic[1] is sha2+blowfish */
Bram Moolenaarf50a2532010-05-21 15:36:08 +020037static char *crypt_magic[] = {"VimCrypt~01!", "VimCrypt~02!"};
38static char crypt_magic_head[] = "VimCrypt~";
39# define CRYPT_MAGIC_LEN 12 /* must be multiple of 4! */
Bram Moolenaar80794b12010-06-13 05:20:42 +020040
41/* For blowfish, after the magic header, we store 8 bytes of salt and then 8
42 * bytes of seed (initialisation vector). */
43static int crypt_salt_len[] = {0, 8};
Bram Moolenaarf50a2532010-05-21 15:36:08 +020044static int crypt_seed_len[] = {0, 8};
Bram Moolenaar80794b12010-06-13 05:20:42 +020045#define CRYPT_SALT_LEN_MAX 8
Bram Moolenaar40e6a712010-05-16 22:32:54 +020046#define CRYPT_SEED_LEN_MAX 8
Bram Moolenaar071d4272004-06-13 20:20:40 +000047#endif
48
49/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000050#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000051
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +000052#if defined(sun) && defined(S_ISCHR)
53# define OPEN_CHR_FILES
54static int is_dev_fd_file(char_u *fname);
55#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000056#ifdef FEAT_MBYTE
57static char_u *next_fenc __ARGS((char_u **pp));
58# ifdef FEAT_EVAL
59static char_u *readfile_charconvert __ARGS((char_u *fname, char_u *fenc, int *fdp));
60# endif
61#endif
62#ifdef FEAT_VIMINFO
63static void check_marks_read __ARGS((void));
64#endif
65#ifdef FEAT_CRYPT
Bram Moolenaar49771f42010-07-20 17:32:38 +020066static int crypt_method_from_magic __ARGS((char *ptr, int len));
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +020067static 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 +000068#endif
69#ifdef UNIX
70static void set_file_time __ARGS((char_u *fname, time_t atime, time_t mtime));
71#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +000072static int set_rw_fname __ARGS((char_u *fname, char_u *sfname));
Bram Moolenaar071d4272004-06-13 20:20:40 +000073static int msg_add_fileformat __ARGS((int eol_type));
Bram Moolenaar071d4272004-06-13 20:20:40 +000074static void msg_add_eol __ARGS((void));
75static int check_mtime __ARGS((buf_T *buf, struct stat *s));
76static int time_differs __ARGS((long t1, long t2));
77#ifdef FEAT_AUTOCMD
Bram Moolenaar754b5602006-02-09 23:53:20 +000078static 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 +000079static int au_find_group __ARGS((char_u *name));
80
81# define AUGROUP_DEFAULT -1 /* default autocmd group */
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000082# define AUGROUP_ERROR -2 /* erroneous autocmd group */
Bram Moolenaar70836c82006-02-20 21:28:49 +000083# define AUGROUP_ALL -3 /* all autocmd groups */
Bram Moolenaar071d4272004-06-13 20:20:40 +000084#endif
85
86#if defined(FEAT_CRYPT) || defined(FEAT_MBYTE)
87# define HAS_BW_FLAGS
88# define FIO_LATIN1 0x01 /* convert Latin1 */
89# define FIO_UTF8 0x02 /* convert UTF-8 */
90# define FIO_UCS2 0x04 /* convert UCS-2 */
91# define FIO_UCS4 0x08 /* convert UCS-4 */
92# define FIO_UTF16 0x10 /* convert UTF-16 */
93# ifdef WIN3264
94# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
95# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
96# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
97# endif
98# ifdef MACOS_X
99# define FIO_MACROMAN 0x20 /* convert MacRoman */
100# endif
101# define FIO_ENDIAN_L 0x80 /* little endian */
102# define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
103# define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
104# define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
105# define FIO_ALL -1 /* allow all formats */
106#endif
107
108/* When converting, a read() or write() may leave some bytes to be converted
109 * for the next call. The value is guessed... */
110#define CONV_RESTLEN 30
111
112/* We have to guess how much a sequence of bytes may expand when converting
113 * with iconv() to be able to allocate a buffer. */
114#define ICONV_MULT 8
115
116/*
117 * Structure to pass arguments from buf_write() to buf_write_bytes().
118 */
119struct bw_info
120{
121 int bw_fd; /* file descriptor */
122 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +0000123 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000124#ifdef HAS_BW_FLAGS
125 int bw_flags; /* FIO_ flags */
126#endif
127#ifdef FEAT_MBYTE
128 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
129 int bw_restlen; /* nr of bytes in bw_rest[] */
130 int bw_first; /* first write call */
131 char_u *bw_conv_buf; /* buffer for writing converted chars */
132 int bw_conv_buflen; /* size of bw_conv_buf */
133 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +0000134 linenr_T bw_conv_error_lnum; /* first line with error or zero */
135 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000136# ifdef USE_ICONV
137 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
138# endif
139#endif
140};
141
142static int buf_write_bytes __ARGS((struct bw_info *ip));
143
144#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000145static linenr_T readfile_linenr __ARGS((linenr_T linecnt, char_u *p, char_u *endp));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000146static int ucs2bytes __ARGS((unsigned c, char_u **pp, int flags));
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000147static int need_conversion __ARGS((char_u *fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000148static int get_fio_flags __ARGS((char_u *ptr));
149static char_u *check_for_bom __ARGS((char_u *p, long size, int *lenp, int flags));
150static int make_bom __ARGS((char_u *buf, char_u *name));
151# ifdef WIN3264
152static int get_win_fio_flags __ARGS((char_u *ptr));
153# endif
154# ifdef MACOS_X
155static int get_mac_fio_flags __ARGS((char_u *ptr));
156# endif
157#endif
158static int move_lines __ARGS((buf_T *frombuf, buf_T *tobuf));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000159#ifdef TEMPDIRNAMES
Bram Moolenaareaf03392009-11-17 11:08:52 +0000160static void vim_settempdir __ARGS((char_u *tempdir));
Bram Moolenaar4592dee2009-11-18 19:11:58 +0000161#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000162#ifdef FEAT_AUTOCMD
163static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
164#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000165
Bram Moolenaar071d4272004-06-13 20:20:40 +0000166 void
167filemess(buf, name, s, attr)
168 buf_T *buf;
169 char_u *name;
170 char_u *s;
171 int attr;
172{
173 int msg_scroll_save;
174
175 if (msg_silent != 0)
176 return;
177 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
178 /* If it's extremely long, truncate it. */
179 if (STRLEN(IObuff) > IOSIZE - 80)
180 IObuff[IOSIZE - 80] = NUL;
181 STRCAT(IObuff, s);
182 /*
183 * For the first message may have to start a new line.
184 * For further ones overwrite the previous one, reset msg_scroll before
185 * calling filemess().
186 */
187 msg_scroll_save = msg_scroll;
188 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
189 msg_scroll = FALSE;
190 if (!msg_scroll) /* wait a bit when overwriting an error msg */
191 check_for_delay(FALSE);
192 msg_start();
193 msg_scroll = msg_scroll_save;
194 msg_scrolled_ign = TRUE;
195 /* may truncate the message to avoid a hit-return prompt */
196 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
197 msg_clr_eos();
198 out_flush();
199 msg_scrolled_ign = FALSE;
200}
201
202/*
203 * Read lines from file "fname" into the buffer after line "from".
204 *
205 * 1. We allocate blocks with lalloc, as big as possible.
206 * 2. Each block is filled with characters from the file with a single read().
207 * 3. The lines are inserted in the buffer with ml_append().
208 *
209 * (caller must check that fname != NULL, unless READ_STDIN is used)
210 *
211 * "lines_to_skip" is the number of lines that must be skipped
212 * "lines_to_read" is the number of lines that are appended
213 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
214 *
215 * flags:
216 * READ_NEW starting to edit a new buffer
217 * READ_FILTER reading filter output
218 * READ_STDIN read from stdin instead of a file
219 * READ_BUFFER read from curbuf instead of a file (converting after reading
220 * stdin)
221 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200222 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000223 *
224 * return FAIL for failure, OK otherwise
225 */
226 int
227readfile(fname, sfname, from, lines_to_skip, lines_to_read, eap, flags)
228 char_u *fname;
229 char_u *sfname;
230 linenr_T from;
231 linenr_T lines_to_skip;
232 linenr_T lines_to_read;
233 exarg_T *eap; /* can be NULL! */
234 int flags;
235{
236 int fd = 0;
237 int newfile = (flags & READ_NEW);
238 int check_readonly;
239 int filtering = (flags & READ_FILTER);
240 int read_stdin = (flags & READ_STDIN);
241 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000242 int set_options = newfile || read_buffer
243 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000244 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
245 colnr_T read_buf_col = 0; /* next char to read from this line */
246 char_u c;
247 linenr_T lnum = from;
248 char_u *ptr = NULL; /* pointer into read buffer */
249 char_u *buffer = NULL; /* read buffer */
250 char_u *new_buffer = NULL; /* init to shut up gcc */
251 char_u *line_start = NULL; /* init to shut up gcc */
252 int wasempty; /* buffer was empty before reading */
253 colnr_T len;
254 long size = 0;
255 char_u *p;
Bram Moolenaar914703b2010-05-31 21:59:46 +0200256 off_t filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000257 int skip_read = FALSE;
258#ifdef FEAT_CRYPT
259 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200260 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000261#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200262#ifdef FEAT_PERSISTENT_UNDO
263 context_sha256_T sha_ctx;
264 int read_undo_file = FALSE;
265#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000266 int split = 0; /* number of split lines */
267#define UNKNOWN 0x0fffffff /* file size is unknown */
268 linenr_T linecnt;
269 int error = FALSE; /* errors encountered */
270 int ff_error = EOL_UNKNOWN; /* file format with errors */
271 long linerest = 0; /* remaining chars in line */
272#ifdef UNIX
273 int perm = 0;
274 int swap_mode = -1; /* protection bits for swap file */
275#else
276 int perm;
277#endif
278 int fileformat = 0; /* end-of-line format */
279 int keep_fileformat = FALSE;
280 struct stat st;
281 int file_readonly;
282 linenr_T skip_count = 0;
283 linenr_T read_count = 0;
284 int msg_save = msg_scroll;
285 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
286 * last read was missing the eol */
287 int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
288 int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
289 int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
290 int file_rewind = FALSE;
291#ifdef FEAT_MBYTE
292 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000293 linenr_T conv_error = 0; /* line nr with conversion error */
294 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000295 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
296 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000297 int bad_char_behavior = BAD_REPLACE;
298 /* BAD_KEEP, BAD_DROP or character to
299 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000300 char_u *tmpname = NULL; /* name of 'charconvert' output file */
301 int fio_flags = 0;
302 char_u *fenc; /* fileencoding to use */
303 int fenc_alloced; /* fenc_next is in allocated memory */
304 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
305 int advance_fenc = FALSE;
306 long real_size = 0;
307# ifdef USE_ICONV
308 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
309# ifdef FEAT_EVAL
310 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
311 'charconvert' next */
312# endif
313# endif
314 int converted = FALSE; /* TRUE if conversion done */
315 int notconverted = FALSE; /* TRUE if conversion wanted but it
316 wasn't possible */
317 char_u conv_rest[CONV_RESTLEN];
318 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
319#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000320#ifdef FEAT_AUTOCMD
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200321 buf_T *old_curbuf;
322 char_u *old_b_ffname;
323 char_u *old_b_fname;
324 int using_b_ffname;
325 int using_b_fname;
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000326#endif
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200327
Bram Moolenaar071d4272004-06-13 20:20:40 +0000328 write_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000329
330 /*
331 * If there is no file name yet, use the one for the read file.
332 * BF_NOTEDITED is set to reflect this.
333 * Don't do this for a read from a filter.
334 * Only do this when 'cpoptions' contains the 'f' flag.
335 */
336 if (curbuf->b_ffname == NULL
337 && !filtering
338 && fname != NULL
339 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
340 && !(flags & READ_DUMMY))
341 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000342 if (set_rw_fname(fname, sfname) == FAIL)
343 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000344 }
345
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200346#ifdef FEAT_AUTOCMD
347 /* Remember the initial values of curbuf, curbuf->b_ffname and
348 * curbuf->b_fname to detect whether they are altered as a result of
349 * executing nasty autocommands. Also check if "fname" and "sfname"
350 * point to one of these values. */
351 old_curbuf = curbuf;
352 old_b_ffname = curbuf->b_ffname;
353 old_b_fname = curbuf->b_fname;
354 using_b_ffname = (fname == curbuf->b_ffname)
355 || (sfname == curbuf->b_ffname);
356 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
357#endif
358
Bram Moolenaardf177f62005-02-22 08:39:57 +0000359 /* After reading a file the cursor line changes but we don't want to
360 * display the line. */
361 ex_no_reprint = TRUE;
362
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000363 /* don't display the file info for another buffer now */
364 need_fileinfo = FALSE;
365
Bram Moolenaar071d4272004-06-13 20:20:40 +0000366 /*
367 * For Unix: Use the short file name whenever possible.
368 * Avoids problems with networks and when directory names are changed.
369 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
370 * another directory, which we don't detect.
371 */
372 if (sfname == NULL)
373 sfname = fname;
374#if defined(UNIX) || defined(__EMX__)
375 fname = sfname;
376#endif
377
378#ifdef FEAT_AUTOCMD
379 /*
380 * The BufReadCmd and FileReadCmd events intercept the reading process by
381 * executing the associated commands instead.
382 */
383 if (!filtering && !read_stdin && !read_buffer)
384 {
385 pos_T pos;
386
387 pos = curbuf->b_op_start;
388
389 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
390 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
391 curbuf->b_op_start.col = 0;
392
393 if (newfile)
394 {
395 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
396 FALSE, curbuf, eap))
397#ifdef FEAT_EVAL
398 return aborting() ? FAIL : OK;
399#else
400 return OK;
401#endif
402 }
403 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
404 FALSE, NULL, eap))
405#ifdef FEAT_EVAL
406 return aborting() ? FAIL : OK;
407#else
408 return OK;
409#endif
410
411 curbuf->b_op_start = pos;
412 }
413#endif
414
415 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
416 msg_scroll = FALSE; /* overwrite previous file message */
417 else
418 msg_scroll = TRUE; /* don't overwrite previous file message */
419
420 /*
421 * If the name ends in a path separator, we can't open it. Check here,
422 * because reading the file may actually work, but then creating the swap
423 * file may destroy it! Reported on MS-DOS and Win 95.
424 * If the name is too long we might crash further on, quit here.
425 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000426 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000427 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000428 p = fname + STRLEN(fname);
429 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000430 {
431 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
432 msg_end();
433 msg_scroll = msg_save;
434 return FAIL;
435 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000436 }
437
438#ifdef UNIX
439 /*
440 * On Unix it is possible to read a directory, so we have to
441 * check for it before the mch_open().
442 */
443 if (!read_stdin && !read_buffer)
444 {
445 perm = mch_getperm(fname);
446 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
447# ifdef S_ISFIFO
448 && !S_ISFIFO(perm) /* ... or fifo */
449# endif
450# ifdef S_ISSOCK
451 && !S_ISSOCK(perm) /* ... or socket */
452# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000453# ifdef OPEN_CHR_FILES
454 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
455 /* ... or a character special file named /dev/fd/<n> */
456# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000457 )
458 {
459 if (S_ISDIR(perm))
460 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
461 else
462 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
463 msg_end();
464 msg_scroll = msg_save;
465 return FAIL;
466 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000467
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000468# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
469 /*
470 * MS-Windows allows opening a device, but we will probably get stuck
471 * trying to read it.
472 */
473 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
474 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000475 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000476 msg_end();
477 msg_scroll = msg_save;
478 return FAIL;
479 }
480# endif
Bram Moolenaar043545e2006-10-10 16:44:07 +0000481 }
482#endif
483
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 /* set default 'fileformat' */
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000485 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000486 {
487 if (eap != NULL && eap->force_ff != 0)
488 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
489 else if (*p_ffs != NUL)
490 set_fileformat(default_fileformat(), OPT_LOCAL);
491 }
492
493 /* set or reset 'binary' */
494 if (eap != NULL && eap->force_bin != 0)
495 {
496 int oldval = curbuf->b_p_bin;
497
498 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
499 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
500 }
501
502 /*
503 * When opening a new file we take the readonly flag from the file.
504 * Default is r/w, can be set to r/o below.
505 * Don't reset it when in readonly mode
506 * Only set/reset b_p_ro when BF_CHECK_RO is set.
507 */
508 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000509 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000510 curbuf->b_p_ro = FALSE;
511
512 if (newfile && !read_stdin && !read_buffer)
513 {
514 /* Remember time of file.
515 * For RISCOS, also remember the filetype.
516 */
517 if (mch_stat((char *)fname, &st) >= 0)
518 {
519 buf_store_time(curbuf, &st, fname);
520 curbuf->b_mtime_read = curbuf->b_mtime;
521
522#if defined(RISCOS) && defined(FEAT_OSFILETYPE)
523 /* Read the filetype into the buffer local filetype option. */
524 mch_read_filetype(fname);
525#endif
526#ifdef UNIX
527 /*
528 * Use the protection bits of the original file for the swap file.
529 * This makes it possible for others to read the name of the
530 * edited file from the swapfile, but only if they can read the
531 * edited file.
532 * Remove the "write" and "execute" bits for group and others
533 * (they must not write the swapfile).
534 * Add the "read" and "write" bits for the user, otherwise we may
535 * not be able to write to the file ourselves.
536 * Setting the bits is done below, after creating the swap file.
537 */
538 swap_mode = (st.st_mode & 0644) | 0600;
539#endif
540#ifdef FEAT_CW_EDITOR
541 /* Get the FSSpec on MacOS
542 * TODO: Update it properly when the buffer name changes
543 */
544 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
545#endif
546#ifdef VMS
547 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000548 curbuf->b_fab_rat = st.st_fab_rat;
549 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000550#endif
551 }
552 else
553 {
554 curbuf->b_mtime = 0;
555 curbuf->b_mtime_read = 0;
556 curbuf->b_orig_size = 0;
557 curbuf->b_orig_mode = 0;
558 }
559
560 /* Reset the "new file" flag. It will be set again below when the
561 * file doesn't exist. */
562 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
563 }
564
565/*
566 * for UNIX: check readonly with perm and mch_access()
567 * for RISCOS: same as Unix, otherwise file gets re-datestamped!
568 * for MSDOS and Amiga: check readonly by trying to open the file for writing
569 */
570 file_readonly = FALSE;
571 if (read_stdin)
572 {
573#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
574 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
575 setmode(0, O_BINARY);
576#endif
577 }
578 else if (!read_buffer)
579 {
580#ifdef USE_MCH_ACCESS
581 if (
582# ifdef UNIX
583 !(perm & 0222) ||
584# endif
585 mch_access((char *)fname, W_OK))
586 file_readonly = TRUE;
587 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
588#else
589 if (!newfile
590 || readonlymode
591 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
592 {
593 file_readonly = TRUE;
594 /* try to open ro */
595 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
596 }
597#endif
598 }
599
600 if (fd < 0) /* cannot open at all */
601 {
602#ifndef UNIX
603 int isdir_f;
604#endif
605 msg_scroll = msg_save;
606#ifndef UNIX
607 /*
608 * On MSDOS and Amiga we can't open a directory, check here.
609 */
610 isdir_f = (mch_isdir(fname));
611 perm = mch_getperm(fname); /* check if the file exists */
612 if (isdir_f)
613 {
614 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
615 curbuf->b_p_ro = TRUE; /* must use "w!" now */
616 }
617 else
618#endif
619 if (newfile)
620 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200621 if (perm < 0
622#ifdef ENOENT
623 && errno == ENOENT
624#endif
625 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000626 {
627 /*
628 * Set the 'new-file' flag, so that when the file has
629 * been created by someone else, a ":w" will complain.
630 */
631 curbuf->b_flags |= BF_NEW;
632
633 /* Create a swap file now, so that other Vims are warned
634 * that we are editing this file. Don't do this for a
635 * "nofile" or "nowrite" buffer type. */
636#ifdef FEAT_QUICKFIX
637 if (!bt_dontwrite(curbuf))
638#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000639 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000640 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000641#ifdef FEAT_AUTOCMD
642 /* SwapExists autocommand may mess things up */
643 if (curbuf != old_curbuf
644 || (using_b_ffname
645 && (old_b_ffname != curbuf->b_ffname))
646 || (using_b_fname
647 && (old_b_fname != curbuf->b_fname)))
648 {
649 EMSG(_(e_auchangedbuf));
650 return FAIL;
651 }
652#endif
653 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000654 if (dir_of_file_exists(fname))
655 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
656 else
657 filemess(curbuf, sfname,
658 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000659#ifdef FEAT_VIMINFO
660 /* Even though this is a new file, it might have been
661 * edited before and deleted. Get the old marks. */
662 check_marks_read();
663#endif
664#ifdef FEAT_MBYTE
665 if (eap != NULL && eap->force_enc != 0)
666 {
667 /* set forced 'fileencoding' */
668 fenc = enc_canonize(eap->cmd + eap->force_enc);
669 if (fenc != NULL)
670 set_string_option_direct((char_u *)"fenc", -1,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +0000671 fenc, OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672 vim_free(fenc);
673 }
674#endif
675#ifdef FEAT_AUTOCMD
676 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
677 FALSE, curbuf, eap);
678#endif
679 /* remember the current fileformat */
680 save_file_ff(curbuf);
681
682#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
683 if (aborting()) /* autocmds may abort script processing */
684 return FAIL;
685#endif
686 return OK; /* a new file is not an error */
687 }
688 else
689 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000690 filemess(curbuf, sfname, (char_u *)(
691# ifdef EFBIG
692 (errno == EFBIG) ? _("[File too big]") :
693# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200694# ifdef EOVERFLOW
695 (errno == EOVERFLOW) ? _("[File too big]") :
696# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000697 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000698 curbuf->b_p_ro = TRUE; /* must use "w!" now */
699 }
700 }
701
702 return FAIL;
703 }
704
705 /*
706 * Only set the 'ro' flag for readonly files the first time they are
707 * loaded. Help files always get readonly mode
708 */
709 if ((check_readonly && file_readonly) || curbuf->b_help)
710 curbuf->b_p_ro = TRUE;
711
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000712 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000714 /* Don't change 'eol' if reading from buffer as it will already be
715 * correctly set when reading stdin. */
716 if (!read_buffer)
717 {
718 curbuf->b_p_eol = TRUE;
719 curbuf->b_start_eol = TRUE;
720 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000721#ifdef FEAT_MBYTE
722 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000723 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000724#endif
725 }
726
727 /* Create a swap file now, so that other Vims are warned that we are
728 * editing this file.
729 * Don't do this for a "nofile" or "nowrite" buffer type. */
730#ifdef FEAT_QUICKFIX
731 if (!bt_dontwrite(curbuf))
732#endif
733 {
734 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000735#ifdef FEAT_AUTOCMD
736 if (!read_stdin && (curbuf != old_curbuf
737 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
738 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
739 {
740 EMSG(_(e_auchangedbuf));
741 if (!read_buffer)
742 close(fd);
743 return FAIL;
744 }
745#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000746#ifdef UNIX
747 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000748 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
749 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 (void)mch_setperm(curbuf->b_ml.ml_mfp->mf_fname, (long)swap_mode);
751#endif
752 }
753
Bram Moolenaarb815dac2005-12-07 20:59:24 +0000754#if defined(HAS_SWAP_EXISTS_ACTION)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000755 /* If "Quit" selected at ATTENTION dialog, don't load the file */
756 if (swap_exists_action == SEA_QUIT)
757 {
758 if (!read_buffer && !read_stdin)
759 close(fd);
760 return FAIL;
761 }
762#endif
763
764 ++no_wait_return; /* don't wait for return yet */
765
766 /*
767 * Set '[ mark to the line above where the lines go (line 1 if zero).
768 */
769 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
770 curbuf->b_op_start.col = 0;
771
772#ifdef FEAT_AUTOCMD
773 if (!read_buffer)
774 {
775 int m = msg_scroll;
776 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000777
778 /*
779 * The file must be closed again, the autocommands may want to change
780 * the file before reading it.
781 */
782 if (!read_stdin)
783 close(fd); /* ignore errors */
784
785 /*
786 * The output from the autocommands should not overwrite anything and
787 * should not be overwritten: Set msg_scroll, restore its value if no
788 * output was done.
789 */
790 msg_scroll = TRUE;
791 if (filtering)
792 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
793 FALSE, curbuf, eap);
794 else if (read_stdin)
795 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
796 FALSE, curbuf, eap);
797 else if (newfile)
798 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
799 FALSE, curbuf, eap);
800 else
801 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
802 FALSE, NULL, eap);
803 if (msg_scrolled == n)
804 msg_scroll = m;
805
806#ifdef FEAT_EVAL
807 if (aborting()) /* autocmds may abort script processing */
808 {
809 --no_wait_return;
810 msg_scroll = msg_save;
811 curbuf->b_p_ro = TRUE; /* must use "w!" now */
812 return FAIL;
813 }
814#endif
815 /*
816 * Don't allow the autocommands to change the current buffer.
817 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000818 *
819 * Don't allow the autocommands to change the buffer name either
820 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000821 */
822 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000823 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
824 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000825 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
826 {
827 --no_wait_return;
828 msg_scroll = msg_save;
829 if (fd < 0)
830 EMSG(_("E200: *ReadPre autocommands made the file unreadable"));
831 else
832 EMSG(_("E201: *ReadPre autocommands must not change current buffer"));
833 curbuf->b_p_ro = TRUE; /* must use "w!" now */
834 return FAIL;
835 }
836 }
837#endif /* FEAT_AUTOCMD */
838
839 /* Autocommands may add lines to the file, need to check if it is empty */
840 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
841
842 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
843 {
844 /*
845 * Show the user that we are busy reading the input. Sometimes this
846 * may take a while. When reading from stdin another program may
847 * still be running, don't move the cursor to the last line, unless
848 * always using the GUI.
849 */
850 if (read_stdin)
851 {
852#ifndef ALWAYS_USE_GUI
853 mch_msg(_("Vim: Reading from stdin...\n"));
854#endif
855#ifdef FEAT_GUI
856 /* Also write a message in the GUI window, if there is one. */
857 if (gui.in_use && !gui.dying && !gui.starting)
858 {
859 p = (char_u *)_("Reading from stdin...");
860 gui_write(p, (int)STRLEN(p));
861 }
862#endif
863 }
864 else if (!read_buffer)
865 filemess(curbuf, sfname, (char_u *)"", 0);
866 }
867
868 msg_scroll = FALSE; /* overwrite the file message */
869
870 /*
871 * Set linecnt now, before the "retry" caused by a wrong guess for
872 * fileformat, and after the autocommands, which may change them.
873 */
874 linecnt = curbuf->b_ml.ml_line_count;
875
876#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000877 /* "++bad=" argument. */
878 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000879 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000880 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000881 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000882 curbuf->b_bad_char = eap->bad_char;
883 }
884 else
885 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000886
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000888 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000889 */
890 if (eap != NULL && eap->force_enc != 0)
891 {
892 fenc = enc_canonize(eap->cmd + eap->force_enc);
893 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000894 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000895 }
896 else if (curbuf->b_p_bin)
897 {
898 fenc = (char_u *)""; /* binary: don't convert */
899 fenc_alloced = FALSE;
900 }
901 else if (curbuf->b_help)
902 {
903 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000904 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905
906 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
907 * fails it must be latin1.
908 * Always do this when 'encoding' is "utf-8". Otherwise only do
909 * this when needed to avoid [converted] remarks all the time.
910 * It is needed when the first line contains non-ASCII characters.
911 * That is only in *.??x files. */
912 fenc = (char_u *)"latin1";
913 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000914 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000915 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000916 fc = fname[STRLEN(fname) - 1];
917 if (TOLOWER_ASC(fc) == 'x')
918 {
919 /* Read the first line (and a bit more). Immediately rewind to
920 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100921 len = read_eintr(fd, firstline, 80);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000922 lseek(fd, (off_t)0L, SEEK_SET);
923 for (p = firstline; p < firstline + len; ++p)
924 if (*p >= 0x80)
925 {
926 c = TRUE;
927 break;
928 }
929 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000930 }
931
932 if (c)
933 {
934 fenc_next = fenc;
935 fenc = (char_u *)"utf-8";
936
937 /* When the file is utf-8 but a character doesn't fit in
938 * 'encoding' don't retry. In help text editing utf-8 bytes
939 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000940 if (!enc_utf8)
941 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000942 }
943 fenc_alloced = FALSE;
944 }
945 else if (*p_fencs == NUL)
946 {
947 fenc = curbuf->b_p_fenc; /* use format from buffer */
948 fenc_alloced = FALSE;
949 }
950 else
951 {
952 fenc_next = p_fencs; /* try items in 'fileencodings' */
953 fenc = next_fenc(&fenc_next);
954 fenc_alloced = TRUE;
955 }
956#endif
957
958 /*
959 * Jump back here to retry reading the file in different ways.
960 * Reasons to retry:
961 * - encoding conversion failed: try another one from "fenc_next"
962 * - BOM detected and fenc was set, need to setup conversion
963 * - "fileformat" check failed: try another
964 *
965 * Variables set for special retry actions:
966 * "file_rewind" Rewind the file to start reading it again.
967 * "advance_fenc" Advance "fenc" using "fenc_next".
968 * "skip_read" Re-use already read bytes (BOM detected).
969 * "did_iconv" iconv() conversion failed, try 'charconvert'.
970 * "keep_fileformat" Don't reset "fileformat".
971 *
972 * Other status indicators:
973 * "tmpname" When != NULL did conversion with 'charconvert'.
974 * Output file has to be deleted afterwards.
975 * "iconv_fd" When != -1 did conversion with iconv().
976 */
977retry:
978
979 if (file_rewind)
980 {
981 if (read_buffer)
982 {
983 read_buf_lnum = 1;
984 read_buf_col = 0;
985 }
986 else if (read_stdin || lseek(fd, (off_t)0L, SEEK_SET) != 0)
987 {
988 /* Can't rewind the file, give up. */
989 error = TRUE;
990 goto failed;
991 }
992 /* Delete the previously read lines. */
993 while (lnum > from)
994 ml_delete(lnum--, FALSE);
995 file_rewind = FALSE;
996#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000997 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000998 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000999 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001000 curbuf->b_start_bomb = FALSE;
1001 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001002 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003#endif
1004 }
1005
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001006#ifdef FEAT_CRYPT
1007 if (cryptkey != NULL)
1008 /* Need to reset the state, but keep the key, don't want to ask for it
1009 * again. */
1010 crypt_pop_state();
1011#endif
1012
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 /*
1014 * When retrying with another "fenc" and the first time "fileformat"
1015 * will be reset.
1016 */
1017 if (keep_fileformat)
1018 keep_fileformat = FALSE;
1019 else
1020 {
1021 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +00001022 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +00001024 try_unix = try_dos = try_mac = FALSE;
1025 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001026 else if (curbuf->b_p_bin)
1027 fileformat = EOL_UNIX; /* binary: use Unix format */
1028 else if (*p_ffs == NUL)
1029 fileformat = get_fileformat(curbuf);/* use format from buffer */
1030 else
1031 fileformat = EOL_UNKNOWN; /* detect from file */
1032 }
1033
1034#ifdef FEAT_MBYTE
1035# ifdef USE_ICONV
1036 if (iconv_fd != (iconv_t)-1)
1037 {
1038 /* aborted conversion with iconv(), close the descriptor */
1039 iconv_close(iconv_fd);
1040 iconv_fd = (iconv_t)-1;
1041 }
1042# endif
1043
1044 if (advance_fenc)
1045 {
1046 /*
1047 * Try the next entry in 'fileencodings'.
1048 */
1049 advance_fenc = FALSE;
1050
1051 if (eap != NULL && eap->force_enc != 0)
1052 {
1053 /* Conversion given with "++cc=" wasn't possible, read
1054 * without conversion. */
1055 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001056 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001057 if (fenc_alloced)
1058 vim_free(fenc);
1059 fenc = (char_u *)"";
1060 fenc_alloced = FALSE;
1061 }
1062 else
1063 {
1064 if (fenc_alloced)
1065 vim_free(fenc);
1066 if (fenc_next != NULL)
1067 {
1068 fenc = next_fenc(&fenc_next);
1069 fenc_alloced = (fenc_next != NULL);
1070 }
1071 else
1072 {
1073 fenc = (char_u *)"";
1074 fenc_alloced = FALSE;
1075 }
1076 }
1077 if (tmpname != NULL)
1078 {
1079 mch_remove(tmpname); /* delete converted file */
1080 vim_free(tmpname);
1081 tmpname = NULL;
1082 }
1083 }
1084
1085 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001086 * Conversion may be required when the encoding of the file is different
1087 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001088 */
1089 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001090 converted = need_conversion(fenc);
1091 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 {
1093
1094 /* "ucs-bom" means we need to check the first bytes of the file
1095 * for a BOM. */
1096 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1097 fio_flags = FIO_UCSBOM;
1098
1099 /*
1100 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1101 * done. This is handled below after read(). Prepare the
1102 * fio_flags to avoid having to parse the string each time.
1103 * Also check for Unicode to Latin1 conversion, because iconv()
1104 * appears not to handle this correctly. This works just like
1105 * conversion to UTF-8 except how the resulting character is put in
1106 * the buffer.
1107 */
1108 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1109 fio_flags = get_fio_flags(fenc);
1110
1111# ifdef WIN3264
1112 /*
1113 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1114 * is handled with MultiByteToWideChar().
1115 */
1116 if (fio_flags == 0)
1117 fio_flags = get_win_fio_flags(fenc);
1118# endif
1119
1120# ifdef MACOS_X
1121 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1122 if (fio_flags == 0)
1123 fio_flags = get_mac_fio_flags(fenc);
1124# endif
1125
1126# ifdef USE_ICONV
1127 /*
1128 * Try using iconv() if we can't convert internally.
1129 */
1130 if (fio_flags == 0
1131# ifdef FEAT_EVAL
1132 && !did_iconv
1133# endif
1134 )
1135 iconv_fd = (iconv_t)my_iconv_open(
1136 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
1137# endif
1138
1139# ifdef FEAT_EVAL
1140 /*
1141 * Use the 'charconvert' expression when conversion is required
1142 * and we can't do it internally or with iconv().
1143 */
1144 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
1145# ifdef USE_ICONV
1146 && iconv_fd == (iconv_t)-1
1147# endif
1148 )
1149 {
1150# ifdef USE_ICONV
1151 did_iconv = FALSE;
1152# endif
1153 /* Skip conversion when it's already done (retry for wrong
1154 * "fileformat"). */
1155 if (tmpname == NULL)
1156 {
1157 tmpname = readfile_charconvert(fname, fenc, &fd);
1158 if (tmpname == NULL)
1159 {
1160 /* Conversion failed. Try another one. */
1161 advance_fenc = TRUE;
1162 if (fd < 0)
1163 {
1164 /* Re-opening the original file failed! */
1165 EMSG(_("E202: Conversion made file unreadable!"));
1166 error = TRUE;
1167 goto failed;
1168 }
1169 goto retry;
1170 }
1171 }
1172 }
1173 else
1174# endif
1175 {
1176 if (fio_flags == 0
1177# ifdef USE_ICONV
1178 && iconv_fd == (iconv_t)-1
1179# endif
1180 )
1181 {
1182 /* Conversion wanted but we can't.
1183 * Try the next conversion in 'fileencodings' */
1184 advance_fenc = TRUE;
1185 goto retry;
1186 }
1187 }
1188 }
1189
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001190 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001192 * stdin or fixed at a specific encoding. */
1193 can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194#endif
1195
1196 if (!skip_read)
1197 {
1198 linerest = 0;
1199 filesize = 0;
1200 skip_count = lines_to_skip;
1201 read_count = lines_to_read;
1202#ifdef FEAT_MBYTE
1203 conv_restlen = 0;
1204#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001205#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001206 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1207 && curbuf->b_ffname != NULL
1208 && curbuf->b_p_udf
1209 && !filtering
1210 && !read_stdin
1211 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001212 if (read_undo_file)
1213 sha256_start(&sha_ctx);
1214#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001215 }
1216
1217 while (!error && !got_int)
1218 {
1219 /*
1220 * We allocate as much space for the file as we can get, plus
1221 * space for the old line plus room for one terminating NUL.
1222 * The amount is limited by the fact that read() only can read
1223 * upto max_unsigned characters (and other things).
1224 */
1225#if SIZEOF_INT <= 2
1226 if (linerest >= 0x7ff0)
1227 {
1228 ++split;
1229 *ptr = NL; /* split line by inserting a NL */
1230 size = 1;
1231 }
1232 else
1233#endif
1234 {
1235 if (!skip_read)
1236 {
1237#if SIZEOF_INT > 2
Bram Moolenaar311d9822007-02-27 15:48:28 +00001238# if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001239 size = SSIZE_MAX; /* use max I/O size, 52K */
1240# else
1241 size = 0x10000L; /* use buffer >= 64K */
1242# endif
1243#else
1244 size = 0x7ff0L - linerest; /* limit buffer to 32K */
1245#endif
1246
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001247 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001248 {
1249 if ((new_buffer = lalloc((long_u)(size + linerest + 1),
1250 FALSE)) != NULL)
1251 break;
1252 }
1253 if (new_buffer == NULL)
1254 {
1255 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1256 error = TRUE;
1257 break;
1258 }
1259 if (linerest) /* copy characters from the previous buffer */
1260 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1261 vim_free(buffer);
1262 buffer = new_buffer;
1263 ptr = buffer + linerest;
1264 line_start = buffer;
1265
1266#ifdef FEAT_MBYTE
1267 /* May need room to translate into.
1268 * For iconv() we don't really know the required space, use a
1269 * factor ICONV_MULT.
1270 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1271 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1272 * become up to 4 bytes, size must be multiple of 2
1273 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1274 * multiple of 2
1275 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1276 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001277 real_size = (int)size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001278# ifdef USE_ICONV
1279 if (iconv_fd != (iconv_t)-1)
1280 size = size / ICONV_MULT;
1281 else
1282# endif
1283 if (fio_flags & FIO_LATIN1)
1284 size = size / 2;
1285 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1286 size = (size * 2 / 3) & ~1;
1287 else if (fio_flags & FIO_UCS4)
1288 size = (size * 2 / 3) & ~3;
1289 else if (fio_flags == FIO_UCSBOM)
1290 size = size / ICONV_MULT; /* worst case */
1291# ifdef WIN3264
1292 else if (fio_flags & FIO_CODEPAGE)
1293 size = size / ICONV_MULT; /* also worst case */
1294# endif
1295# ifdef MACOS_X
1296 else if (fio_flags & FIO_MACROMAN)
1297 size = size / ICONV_MULT; /* also worst case */
1298# endif
1299#endif
1300
1301#ifdef FEAT_MBYTE
1302 if (conv_restlen > 0)
1303 {
1304 /* Insert unconverted bytes from previous line. */
1305 mch_memmove(ptr, conv_rest, conv_restlen);
1306 ptr += conv_restlen;
1307 size -= conv_restlen;
1308 }
1309#endif
1310
1311 if (read_buffer)
1312 {
1313 /*
1314 * Read bytes from curbuf. Used for converting text read
1315 * from stdin.
1316 */
1317 if (read_buf_lnum > from)
1318 size = 0;
1319 else
1320 {
1321 int n, ni;
1322 long tlen;
1323
1324 tlen = 0;
1325 for (;;)
1326 {
1327 p = ml_get(read_buf_lnum) + read_buf_col;
1328 n = (int)STRLEN(p);
1329 if ((int)tlen + n + 1 > size)
1330 {
1331 /* Filled up to "size", append partial line.
1332 * Change NL to NUL to reverse the effect done
1333 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001334 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001335 for (ni = 0; ni < n; ++ni)
1336 {
1337 if (p[ni] == NL)
1338 ptr[tlen++] = NUL;
1339 else
1340 ptr[tlen++] = p[ni];
1341 }
1342 read_buf_col += n;
1343 break;
1344 }
1345 else
1346 {
1347 /* Append whole line and new-line. Change NL
1348 * to NUL to reverse the effect done below. */
1349 for (ni = 0; ni < n; ++ni)
1350 {
1351 if (p[ni] == NL)
1352 ptr[tlen++] = NUL;
1353 else
1354 ptr[tlen++] = p[ni];
1355 }
1356 ptr[tlen++] = NL;
1357 read_buf_col = 0;
1358 if (++read_buf_lnum > from)
1359 {
1360 /* When the last line didn't have an
1361 * end-of-line don't add it now either. */
1362 if (!curbuf->b_p_eol)
1363 --tlen;
1364 size = tlen;
1365 break;
1366 }
1367 }
1368 }
1369 }
1370 }
1371 else
1372 {
1373 /*
1374 * Read bytes from the file.
1375 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001376 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001377 }
1378
1379 if (size <= 0)
1380 {
1381 if (size < 0) /* read error */
1382 error = TRUE;
1383#ifdef FEAT_MBYTE
1384 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001385 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001386 /*
1387 * Reached end-of-file but some trailing bytes could
1388 * not be converted. Truncated file?
1389 */
1390
1391 /* When we did a conversion report an error. */
1392 if (fio_flags != 0
1393# ifdef USE_ICONV
1394 || iconv_fd != (iconv_t)-1
1395# endif
1396 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001397 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001398 if (conv_error == 0)
1399 conv_error = curbuf->b_ml.ml_line_count
1400 - linecnt + 1;
1401 }
1402 /* Remember the first linenr with an illegal byte */
1403 else if (illegal_byte == 0)
1404 illegal_byte = curbuf->b_ml.ml_line_count
1405 - linecnt + 1;
1406 if (bad_char_behavior == BAD_DROP)
1407 {
1408 *(ptr - conv_restlen) = NUL;
1409 conv_restlen = 0;
1410 }
1411 else
1412 {
1413 /* Replace the trailing bytes with the replacement
1414 * character if we were converting; if we weren't,
1415 * leave the UTF8 checking code to do it, as it
1416 * works slightly differently. */
1417 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
1418# ifdef USE_ICONV
1419 || iconv_fd != (iconv_t)-1
1420# endif
1421 ))
1422 {
1423 while (conv_restlen > 0)
1424 {
1425 *(--ptr) = bad_char_behavior;
1426 --conv_restlen;
1427 }
1428 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001429 fio_flags = 0; /* don't convert this */
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001430# ifdef USE_ICONV
1431 if (iconv_fd != (iconv_t)-1)
1432 {
1433 iconv_close(iconv_fd);
1434 iconv_fd = (iconv_t)-1;
1435 }
1436# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001437 }
1438 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001439#endif
1440 }
1441
1442#ifdef FEAT_CRYPT
1443 /*
1444 * At start of file: Check for magic number of encryption.
1445 */
1446 if (filesize == 0)
1447 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02001448 &filesize, newfile, sfname,
1449 &did_ask_for_key);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001450 /*
1451 * Decrypt the read bytes.
1452 */
1453 if (cryptkey != NULL && size > 0)
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02001454 crypt_decode(ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455#endif
1456 }
1457 skip_read = FALSE;
1458
1459#ifdef FEAT_MBYTE
1460 /*
1461 * At start of file (or after crypt magic number): Check for BOM.
1462 * Also check for a BOM for other Unicode encodings, but not after
1463 * converting with 'charconvert' or when a BOM has already been
1464 * found.
1465 */
1466 if ((filesize == 0
1467# ifdef FEAT_CRYPT
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001468 || (filesize == (CRYPT_MAGIC_LEN
Bram Moolenaar80794b12010-06-13 05:20:42 +02001469 + crypt_salt_len[use_crypt_method]
Bram Moolenaar40e6a712010-05-16 22:32:54 +02001470 + crypt_seed_len[use_crypt_method])
1471 && cryptkey != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001472# endif
1473 )
1474 && (fio_flags == FIO_UCSBOM
1475 || (!curbuf->b_p_bomb
1476 && tmpname == NULL
1477 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1478 {
1479 char_u *ccname;
1480 int blen;
1481
1482 /* no BOM detection in a short file or in binary mode */
1483 if (size < 2 || curbuf->b_p_bin)
1484 ccname = NULL;
1485 else
1486 ccname = check_for_bom(ptr, size, &blen,
1487 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1488 if (ccname != NULL)
1489 {
1490 /* Remove BOM from the text */
1491 filesize += blen;
1492 size -= blen;
1493 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001494 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001495 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001497 curbuf->b_start_bomb = TRUE;
1498 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001499 }
1500
1501 if (fio_flags == FIO_UCSBOM)
1502 {
1503 if (ccname == NULL)
1504 {
1505 /* No BOM detected: retry with next encoding. */
1506 advance_fenc = TRUE;
1507 }
1508 else
1509 {
1510 /* BOM detected: set "fenc" and jump back */
1511 if (fenc_alloced)
1512 vim_free(fenc);
1513 fenc = ccname;
1514 fenc_alloced = FALSE;
1515 }
1516 /* retry reading without getting new bytes or rewinding */
1517 skip_read = TRUE;
1518 goto retry;
1519 }
1520 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001521
1522 /* Include not converted bytes. */
1523 ptr -= conv_restlen;
1524 size += conv_restlen;
1525 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001526#endif
1527 /*
1528 * Break here for a read error or end-of-file.
1529 */
1530 if (size <= 0)
1531 break;
1532
1533#ifdef FEAT_MBYTE
1534
Bram Moolenaar071d4272004-06-13 20:20:40 +00001535# ifdef USE_ICONV
1536 if (iconv_fd != (iconv_t)-1)
1537 {
1538 /*
1539 * Attempt conversion of the read bytes to 'encoding' using
1540 * iconv().
1541 */
1542 const char *fromp;
1543 char *top;
1544 size_t from_size;
1545 size_t to_size;
1546
1547 fromp = (char *)ptr;
1548 from_size = size;
1549 ptr += size;
1550 top = (char *)ptr;
1551 to_size = real_size - size;
1552
1553 /*
1554 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001555 * another conversion. Except for when there is no
1556 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001557 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001558 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1559 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001560 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1561 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001562 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001563 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001564 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001565 if (conv_error == 0)
1566 conv_error = readfile_linenr(linecnt,
1567 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001568
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001569 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001570 ++fromp;
1571 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001572 if (bad_char_behavior == BAD_KEEP)
1573 {
1574 *top++ = *(fromp - 1);
1575 --to_size;
1576 }
1577 else if (bad_char_behavior != BAD_DROP)
1578 {
1579 *top++ = bad_char_behavior;
1580 --to_size;
1581 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001582 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001583
1584 if (from_size > 0)
1585 {
1586 /* Some remaining characters, keep them for the next
1587 * round. */
1588 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1589 conv_restlen = (int)from_size;
1590 }
1591
1592 /* move the linerest to before the converted characters */
1593 line_start = ptr - linerest;
1594 mch_memmove(line_start, buffer, (size_t)linerest);
1595 size = (long)((char_u *)top - ptr);
1596 }
1597# endif
1598
1599# ifdef WIN3264
1600 if (fio_flags & FIO_CODEPAGE)
1601 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001602 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001603 WCHAR ucs2buf[3];
1604 int ucs2len;
1605 int codepage = FIO_GET_CP(fio_flags);
1606 int bytelen;
1607 int found_bad;
1608 char replstr[2];
1609
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610 /*
1611 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001612 * a codepage, using standard MS-Windows functions. This
1613 * requires two steps:
1614 * 1. convert from 'fileencoding' to ucs-2
1615 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001617 * Because there may be illegal bytes AND an incomplete byte
1618 * sequence at the end, we may have to do the conversion one
1619 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001621
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001622 /* Replacement string for WideCharToMultiByte(). */
1623 if (bad_char_behavior > 0)
1624 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001625 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001626 replstr[0] = '?';
1627 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001628
1629 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001630 * Move the bytes to the end of the buffer, so that we have
1631 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001632 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001633 src = ptr + real_size - size;
1634 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001635
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001636 /*
1637 * Do the conversion.
1638 */
1639 dst = ptr;
1640 size = size;
1641 while (size > 0)
1642 {
1643 found_bad = FALSE;
1644
1645# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1646 if (codepage == CP_UTF8)
1647 {
1648 /* Handle CP_UTF8 input ourselves to be able to handle
1649 * trailing bytes properly.
1650 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001651 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001652 if (bytelen > size)
1653 {
1654 /* Only got some bytes of a character. Normally
1655 * it's put in "conv_rest", but if it's too long
1656 * deal with it as if they were illegal bytes. */
1657 if (bytelen <= CONV_RESTLEN)
1658 break;
1659
1660 /* weird overlong byte sequence */
1661 bytelen = size;
1662 found_bad = TRUE;
1663 }
1664 else
1665 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001666 int u8c = utf_ptr2char(src);
1667
Bram Moolenaar86e01082005-12-29 22:45:34 +00001668 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001669 found_bad = TRUE;
1670 ucs2buf[0] = u8c;
1671 ucs2len = 1;
1672 }
1673 }
1674 else
1675# endif
1676 {
1677 /* We don't know how long the byte sequence is, try
1678 * from one to three bytes. */
1679 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1680 ++bytelen)
1681 {
1682 ucs2len = MultiByteToWideChar(codepage,
1683 MB_ERR_INVALID_CHARS,
1684 (LPCSTR)src, bytelen,
1685 ucs2buf, 3);
1686 if (ucs2len > 0)
1687 break;
1688 }
1689 if (ucs2len == 0)
1690 {
1691 /* If we have only one byte then it's probably an
1692 * incomplete byte sequence. Otherwise discard
1693 * one byte as a bad character. */
1694 if (size == 1)
1695 break;
1696 found_bad = TRUE;
1697 bytelen = 1;
1698 }
1699 }
1700
1701 if (!found_bad)
1702 {
1703 int i;
1704
1705 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1706 if (enc_utf8)
1707 {
1708 /* From UCS-2 to UTF-8. Cannot fail. */
1709 for (i = 0; i < ucs2len; ++i)
1710 dst += utf_char2bytes(ucs2buf[i], dst);
1711 }
1712 else
1713 {
1714 BOOL bad = FALSE;
1715 int dstlen;
1716
1717 /* From UCS-2 to "enc_codepage". If the
1718 * conversion uses the default character "?",
1719 * the data doesn't fit in this encoding. */
1720 dstlen = WideCharToMultiByte(enc_codepage, 0,
1721 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001722 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001723 replstr, &bad);
1724 if (bad)
1725 found_bad = TRUE;
1726 else
1727 dst += dstlen;
1728 }
1729 }
1730
1731 if (found_bad)
1732 {
1733 /* Deal with bytes we can't convert. */
1734 if (can_retry)
1735 goto rewind_retry;
1736 if (conv_error == 0)
1737 conv_error = readfile_linenr(linecnt, ptr, dst);
1738 if (bad_char_behavior != BAD_DROP)
1739 {
1740 if (bad_char_behavior == BAD_KEEP)
1741 {
1742 mch_memmove(dst, src, bytelen);
1743 dst += bytelen;
1744 }
1745 else
1746 *dst++ = bad_char_behavior;
1747 }
1748 }
1749
1750 src += bytelen;
1751 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001752 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001753
1754 if (size > 0)
1755 {
1756 /* An incomplete byte sequence remaining. */
1757 mch_memmove(conv_rest, src, size);
1758 conv_restlen = size;
1759 }
1760
1761 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001762 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001763 }
1764 else
1765# endif
Bram Moolenaar56718732006-03-15 22:53:57 +00001766# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 if (fio_flags & FIO_MACROMAN)
1768 {
1769 /*
1770 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001771 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001772 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001773 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001774 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001775 }
1776 else
1777# endif
1778 if (fio_flags != 0)
1779 {
1780 int u8c;
1781 char_u *dest;
1782 char_u *tail = NULL;
1783
1784 /*
1785 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1786 * "enc_utf8" not set: Convert Unicode to Latin1.
1787 * Go from end to start through the buffer, because the number
1788 * of bytes may increase.
1789 * "dest" points to after where the UTF-8 bytes go, "p" points
1790 * to after the next character to convert.
1791 */
1792 dest = ptr + real_size;
1793 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1794 {
1795 p = ptr + size;
1796 if (fio_flags == FIO_UTF8)
1797 {
1798 /* Check for a trailing incomplete UTF-8 sequence */
1799 tail = ptr + size - 1;
1800 while (tail > ptr && (*tail & 0xc0) == 0x80)
1801 --tail;
1802 if (tail + utf_byte2len(*tail) <= ptr + size)
1803 tail = NULL;
1804 else
1805 p = tail;
1806 }
1807 }
1808 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1809 {
1810 /* Check for a trailing byte */
1811 p = ptr + (size & ~1);
1812 if (size & 1)
1813 tail = p;
1814 if ((fio_flags & FIO_UTF16) && p > ptr)
1815 {
1816 /* Check for a trailing leading word */
1817 if (fio_flags & FIO_ENDIAN_L)
1818 {
1819 u8c = (*--p << 8);
1820 u8c += *--p;
1821 }
1822 else
1823 {
1824 u8c = *--p;
1825 u8c += (*--p << 8);
1826 }
1827 if (u8c >= 0xd800 && u8c <= 0xdbff)
1828 tail = p;
1829 else
1830 p += 2;
1831 }
1832 }
1833 else /* FIO_UCS4 */
1834 {
1835 /* Check for trailing 1, 2 or 3 bytes */
1836 p = ptr + (size & ~3);
1837 if (size & 3)
1838 tail = p;
1839 }
1840
1841 /* If there is a trailing incomplete sequence move it to
1842 * conv_rest[]. */
1843 if (tail != NULL)
1844 {
1845 conv_restlen = (int)((ptr + size) - tail);
1846 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1847 size -= conv_restlen;
1848 }
1849
1850
1851 while (p > ptr)
1852 {
1853 if (fio_flags & FIO_LATIN1)
1854 u8c = *--p;
1855 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1856 {
1857 if (fio_flags & FIO_ENDIAN_L)
1858 {
1859 u8c = (*--p << 8);
1860 u8c += *--p;
1861 }
1862 else
1863 {
1864 u8c = *--p;
1865 u8c += (*--p << 8);
1866 }
1867 if ((fio_flags & FIO_UTF16)
1868 && u8c >= 0xdc00 && u8c <= 0xdfff)
1869 {
1870 int u16c;
1871
1872 if (p == ptr)
1873 {
1874 /* Missing leading word. */
1875 if (can_retry)
1876 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001877 if (conv_error == 0)
1878 conv_error = readfile_linenr(linecnt,
1879 ptr, p);
1880 if (bad_char_behavior == BAD_DROP)
1881 continue;
1882 if (bad_char_behavior != BAD_KEEP)
1883 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884 }
1885
1886 /* found second word of double-word, get the first
1887 * word and compute the resulting character */
1888 if (fio_flags & FIO_ENDIAN_L)
1889 {
1890 u16c = (*--p << 8);
1891 u16c += *--p;
1892 }
1893 else
1894 {
1895 u16c = *--p;
1896 u16c += (*--p << 8);
1897 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001898 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1899 + (u8c & 0x3ff);
1900
Bram Moolenaar071d4272004-06-13 20:20:40 +00001901 /* Check if the word is indeed a leading word. */
1902 if (u16c < 0xd800 || u16c > 0xdbff)
1903 {
1904 if (can_retry)
1905 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001906 if (conv_error == 0)
1907 conv_error = readfile_linenr(linecnt,
1908 ptr, p);
1909 if (bad_char_behavior == BAD_DROP)
1910 continue;
1911 if (bad_char_behavior != BAD_KEEP)
1912 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001914 }
1915 }
1916 else if (fio_flags & FIO_UCS4)
1917 {
1918 if (fio_flags & FIO_ENDIAN_L)
1919 {
1920 u8c = (*--p << 24);
1921 u8c += (*--p << 16);
1922 u8c += (*--p << 8);
1923 u8c += *--p;
1924 }
1925 else /* big endian */
1926 {
1927 u8c = *--p;
1928 u8c += (*--p << 8);
1929 u8c += (*--p << 16);
1930 u8c += (*--p << 24);
1931 }
1932 }
1933 else /* UTF-8 */
1934 {
1935 if (*--p < 0x80)
1936 u8c = *p;
1937 else
1938 {
1939 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001940 p -= len;
1941 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 if (len == 0)
1943 {
1944 /* Not a valid UTF-8 character, retry with
1945 * another fenc when possible, otherwise just
1946 * report the error. */
1947 if (can_retry)
1948 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001949 if (conv_error == 0)
1950 conv_error = readfile_linenr(linecnt,
1951 ptr, p);
1952 if (bad_char_behavior == BAD_DROP)
1953 continue;
1954 if (bad_char_behavior != BAD_KEEP)
1955 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001956 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001957 }
1958 }
1959 if (enc_utf8) /* produce UTF-8 */
1960 {
1961 dest -= utf_char2len(u8c);
1962 (void)utf_char2bytes(u8c, dest);
1963 }
1964 else /* produce Latin1 */
1965 {
1966 --dest;
1967 if (u8c >= 0x100)
1968 {
1969 /* character doesn't fit in latin1, retry with
1970 * another fenc when possible, otherwise just
1971 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001972 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001974 if (conv_error == 0)
1975 conv_error = readfile_linenr(linecnt, ptr, p);
1976 if (bad_char_behavior == BAD_DROP)
1977 ++dest;
1978 else if (bad_char_behavior == BAD_KEEP)
1979 *dest = u8c;
1980 else if (eap != NULL && eap->bad_char != 0)
1981 *dest = bad_char_behavior;
1982 else
1983 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 }
1985 else
1986 *dest = u8c;
1987 }
1988 }
1989
1990 /* move the linerest to before the converted characters */
1991 line_start = dest - linerest;
1992 mch_memmove(line_start, buffer, (size_t)linerest);
1993 size = (long)((ptr + real_size) - dest);
1994 ptr = dest;
1995 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001996 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001998 int incomplete_tail = FALSE;
1999
2000 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
2001 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002002 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00002003 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002004 int l;
2005
2006 if (todo <= 0)
2007 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002008 if (*p >= 0x80)
2009 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 /* A length of 1 means it's an illegal byte. Accept
2011 * an incomplete character at the end though, the next
2012 * read() will get the next bytes, we'll check it
2013 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002014 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002015 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002016 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002017 /* Avoid retrying with a different encoding when
2018 * a truncated file is more likely, or attempting
2019 * to read the rest of an incomplete sequence when
2020 * we have already done so. */
2021 if (p > ptr || filesize > 0)
2022 incomplete_tail = TRUE;
2023 /* Incomplete byte sequence, move it to conv_rest[]
2024 * and try to read the rest of it, unless we've
2025 * already done so. */
2026 if (p > ptr)
2027 {
2028 conv_restlen = todo;
2029 mch_memmove(conv_rest, p, conv_restlen);
2030 size -= conv_restlen;
2031 break;
2032 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002033 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002034 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002035 {
2036 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002037 * do that, unless at EOF where a truncated
2038 * file is more likely than a conversion error. */
2039 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002040 break;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002041# ifdef USE_ICONV
2042 /* When we did a conversion report an error. */
2043 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2044 conv_error = readfile_linenr(linecnt, ptr, p);
2045# endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002046 /* Remember the first linenr with an illegal byte */
2047 if (conv_error == 0 && illegal_byte == 0)
2048 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002049
2050 /* Drop, keep or replace the bad byte. */
2051 if (bad_char_behavior == BAD_DROP)
2052 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002053 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002054 --p;
2055 --size;
2056 }
2057 else if (bad_char_behavior != BAD_KEEP)
2058 *p = bad_char_behavior;
2059 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002060 else
2061 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 }
2063 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002064 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 {
2066 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002067rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002068 /* Retry reading with another conversion. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002069# if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002070 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2071 /* iconv() failed, try 'charconvert' */
2072 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 else
2074# endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002075 /* use next item from 'fileencodings' */
2076 advance_fenc = TRUE;
2077 file_rewind = TRUE;
2078 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079 }
2080 }
2081#endif
2082
2083 /* count the number of characters (after conversion!) */
2084 filesize += size;
2085
2086 /*
2087 * when reading the first part of a file: guess EOL type
2088 */
2089 if (fileformat == EOL_UNKNOWN)
2090 {
2091 /* First try finding a NL, for Dos and Unix */
2092 if (try_dos || try_unix)
2093 {
2094 for (p = ptr; p < ptr + size; ++p)
2095 {
2096 if (*p == NL)
2097 {
2098 if (!try_unix
2099 || (try_dos && p > ptr && p[-1] == CAR))
2100 fileformat = EOL_DOS;
2101 else
2102 fileformat = EOL_UNIX;
2103 break;
2104 }
2105 }
2106
2107 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2108 if (fileformat == EOL_UNIX && try_mac)
2109 {
2110 /* Need to reset the counters when retrying fenc. */
2111 try_mac = 1;
2112 try_unix = 1;
2113 for (; p >= ptr && *p != CAR; p--)
2114 ;
2115 if (p >= ptr)
2116 {
2117 for (p = ptr; p < ptr + size; ++p)
2118 {
2119 if (*p == NL)
2120 try_unix++;
2121 else if (*p == CAR)
2122 try_mac++;
2123 }
2124 if (try_mac > try_unix)
2125 fileformat = EOL_MAC;
2126 }
2127 }
2128 }
2129
2130 /* No NL found: may use Mac format */
2131 if (fileformat == EOL_UNKNOWN && try_mac)
2132 fileformat = EOL_MAC;
2133
2134 /* Still nothing found? Use first format in 'ffs' */
2135 if (fileformat == EOL_UNKNOWN)
2136 fileformat = default_fileformat();
2137
2138 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002139 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002140 set_fileformat(fileformat, OPT_LOCAL);
2141 }
2142 }
2143
2144 /*
2145 * This loop is executed once for every character read.
2146 * Keep it fast!
2147 */
2148 if (fileformat == EOL_MAC)
2149 {
2150 --ptr;
2151 while (++ptr, --size >= 0)
2152 {
2153 /* catch most common case first */
2154 if ((c = *ptr) != NUL && c != CAR && c != NL)
2155 continue;
2156 if (c == NUL)
2157 *ptr = NL; /* NULs are replaced by newlines! */
2158 else if (c == NL)
2159 *ptr = CAR; /* NLs are replaced by CRs! */
2160 else
2161 {
2162 if (skip_count == 0)
2163 {
2164 *ptr = NUL; /* end of line */
2165 len = (colnr_T) (ptr - line_start + 1);
2166 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2167 {
2168 error = TRUE;
2169 break;
2170 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002171#ifdef FEAT_PERSISTENT_UNDO
2172 if (read_undo_file)
2173 sha256_update(&sha_ctx, line_start, len);
2174#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002175 ++lnum;
2176 if (--read_count == 0)
2177 {
2178 error = TRUE; /* break loop */
2179 line_start = ptr; /* nothing left to write */
2180 break;
2181 }
2182 }
2183 else
2184 --skip_count;
2185 line_start = ptr + 1;
2186 }
2187 }
2188 }
2189 else
2190 {
2191 --ptr;
2192 while (++ptr, --size >= 0)
2193 {
2194 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2195 continue;
2196 if (c == NUL)
2197 *ptr = NL; /* NULs are replaced by newlines! */
2198 else
2199 {
2200 if (skip_count == 0)
2201 {
2202 *ptr = NUL; /* end of line */
2203 len = (colnr_T)(ptr - line_start + 1);
2204 if (fileformat == EOL_DOS)
2205 {
2206 if (ptr[-1] == CAR) /* remove CR */
2207 {
2208 ptr[-1] = NUL;
2209 --len;
2210 }
2211 /*
2212 * Reading in Dos format, but no CR-LF found!
2213 * When 'fileformats' includes "unix", delete all
2214 * the lines read so far and start all over again.
2215 * Otherwise give an error message later.
2216 */
2217 else if (ff_error != EOL_DOS)
2218 {
2219 if ( try_unix
2220 && !read_stdin
2221 && (read_buffer
2222 || lseek(fd, (off_t)0L, SEEK_SET) == 0))
2223 {
2224 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002225 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002226 set_fileformat(EOL_UNIX, OPT_LOCAL);
2227 file_rewind = TRUE;
2228 keep_fileformat = TRUE;
2229 goto retry;
2230 }
2231 ff_error = EOL_DOS;
2232 }
2233 }
2234 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2235 {
2236 error = TRUE;
2237 break;
2238 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002239#ifdef FEAT_PERSISTENT_UNDO
2240 if (read_undo_file)
2241 sha256_update(&sha_ctx, line_start, len);
2242#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 ++lnum;
2244 if (--read_count == 0)
2245 {
2246 error = TRUE; /* break loop */
2247 line_start = ptr; /* nothing left to write */
2248 break;
2249 }
2250 }
2251 else
2252 --skip_count;
2253 line_start = ptr + 1;
2254 }
2255 }
2256 }
2257 linerest = (long)(ptr - line_start);
2258 ui_breakcheck();
2259 }
2260
2261failed:
2262 /* not an error, max. number of lines reached */
2263 if (error && read_count == 0)
2264 error = FALSE;
2265
2266 /*
2267 * If we get EOF in the middle of a line, note the fact and
2268 * complete the line ourselves.
2269 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2270 */
2271 if (!error
2272 && !got_int
2273 && linerest != 0
2274 && !(!curbuf->b_p_bin
2275 && fileformat == EOL_DOS
2276 && *line_start == Ctrl_Z
2277 && ptr == line_start + 1))
2278 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002279 /* remember for when writing */
2280 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002281 curbuf->b_p_eol = FALSE;
2282 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002283 len = (colnr_T)(ptr - line_start + 1);
2284 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 error = TRUE;
2286 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002287 {
2288#ifdef FEAT_PERSISTENT_UNDO
2289 if (read_undo_file)
2290 sha256_update(&sha_ctx, line_start, len);
2291#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002292 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002293 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002294 }
2295
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002296 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297 save_file_ff(curbuf); /* remember the current file format */
2298
2299#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002300 if (cryptkey != NULL)
2301 {
2302 crypt_pop_state();
2303 if (cryptkey != curbuf->b_p_key)
2304 free_crypt_key(cryptkey);
2305 /* don't set cryptkey to NULL, it's used below as a flag that
2306 * encryption was used */
2307 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002308#endif
2309
2310#ifdef FEAT_MBYTE
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002311 /* If editing a new file: set 'fenc' for the current buffer.
2312 * Also for ":read ++edit file". */
2313 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002315 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002316 if (fenc_alloced)
2317 vim_free(fenc);
2318# ifdef USE_ICONV
2319 if (iconv_fd != (iconv_t)-1)
2320 {
2321 iconv_close(iconv_fd);
2322 iconv_fd = (iconv_t)-1;
2323 }
2324# endif
2325#endif
2326
2327 if (!read_buffer && !read_stdin)
2328 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002329#ifdef HAVE_FD_CLOEXEC
2330 else
2331 {
2332 int fdflags = fcntl(fd, F_GETFD);
2333 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
2334 fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
2335 }
2336#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002337 vim_free(buffer);
2338
2339#ifdef HAVE_DUP
2340 if (read_stdin)
2341 {
2342 /* Use stderr for stdin, makes shell commands work. */
2343 close(0);
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00002344 ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002345 }
2346#endif
2347
2348#ifdef FEAT_MBYTE
2349 if (tmpname != NULL)
2350 {
2351 mch_remove(tmpname); /* delete converted file */
2352 vim_free(tmpname);
2353 }
2354#endif
2355 --no_wait_return; /* may wait for return now */
2356
2357 /*
2358 * In recovery mode everything but autocommands is skipped.
2359 */
2360 if (!recoverymode)
2361 {
2362 /* need to delete the last line, which comes from the empty buffer */
2363 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2364 {
2365#ifdef FEAT_NETBEANS_INTG
2366 netbeansFireChanges = 0;
2367#endif
2368 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2369#ifdef FEAT_NETBEANS_INTG
2370 netbeansFireChanges = 1;
2371#endif
2372 --linecnt;
2373 }
2374 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2375 if (filesize == 0)
2376 linecnt = 0;
2377 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002378 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002379 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002380#ifdef FEAT_DIFF
2381 /* After reading the text into the buffer the diff info needs to
2382 * be updated. */
2383 diff_invalidate(curbuf);
2384#endif
2385#ifdef FEAT_FOLDING
2386 /* All folds in the window are invalid now. Mark them for update
2387 * before triggering autocommands. */
2388 foldUpdateAll(curwin);
2389#endif
2390 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 else if (linecnt) /* appended at least one line */
2392 appended_lines_mark(from, linecnt);
2393
Bram Moolenaar071d4272004-06-13 20:20:40 +00002394#ifndef ALWAYS_USE_GUI
2395 /*
2396 * If we were reading from the same terminal as where messages go,
2397 * the screen will have been messed up.
2398 * Switch on raw mode now and clear the screen.
2399 */
2400 if (read_stdin)
2401 {
2402 settmode(TMODE_RAW); /* set to raw mode */
2403 starttermcap();
2404 screenclear();
2405 }
2406#endif
2407
2408 if (got_int)
2409 {
2410 if (!(flags & READ_DUMMY))
2411 {
2412 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2413 if (newfile)
2414 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2415 }
2416 msg_scroll = msg_save;
2417#ifdef FEAT_VIMINFO
2418 check_marks_read();
2419#endif
2420 return OK; /* an interrupt isn't really an error */
2421 }
2422
2423 if (!filtering && !(flags & READ_DUMMY))
2424 {
2425 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2426 c = FALSE;
2427
2428#ifdef UNIX
2429# ifdef S_ISFIFO
2430 if (S_ISFIFO(perm)) /* fifo or socket */
2431 {
2432 STRCAT(IObuff, _("[fifo/socket]"));
2433 c = TRUE;
2434 }
2435# else
2436# ifdef S_IFIFO
2437 if ((perm & S_IFMT) == S_IFIFO) /* fifo */
2438 {
2439 STRCAT(IObuff, _("[fifo]"));
2440 c = TRUE;
2441 }
2442# endif
2443# ifdef S_IFSOCK
2444 if ((perm & S_IFMT) == S_IFSOCK) /* or socket */
2445 {
2446 STRCAT(IObuff, _("[socket]"));
2447 c = TRUE;
2448 }
2449# endif
2450# endif
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002451# ifdef OPEN_CHR_FILES
2452 if (S_ISCHR(perm)) /* or character special */
2453 {
2454 STRCAT(IObuff, _("[character special]"));
2455 c = TRUE;
2456 }
2457# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002458#endif
2459 if (curbuf->b_p_ro)
2460 {
2461 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2462 c = TRUE;
2463 }
2464 if (read_no_eol_lnum)
2465 {
2466 msg_add_eol();
2467 c = TRUE;
2468 }
2469 if (ff_error == EOL_DOS)
2470 {
2471 STRCAT(IObuff, _("[CR missing]"));
2472 c = TRUE;
2473 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002474 if (split)
2475 {
2476 STRCAT(IObuff, _("[long lines split]"));
2477 c = TRUE;
2478 }
2479#ifdef FEAT_MBYTE
2480 if (notconverted)
2481 {
2482 STRCAT(IObuff, _("[NOT converted]"));
2483 c = TRUE;
2484 }
2485 else if (converted)
2486 {
2487 STRCAT(IObuff, _("[converted]"));
2488 c = TRUE;
2489 }
2490#endif
2491#ifdef FEAT_CRYPT
2492 if (cryptkey != NULL)
2493 {
2494 STRCAT(IObuff, _("[crypted]"));
2495 c = TRUE;
2496 }
2497#endif
2498#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002499 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002501 sprintf((char *)IObuff + STRLEN(IObuff),
2502 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002503 c = TRUE;
2504 }
2505 else if (illegal_byte > 0)
2506 {
2507 sprintf((char *)IObuff + STRLEN(IObuff),
2508 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2509 c = TRUE;
2510 }
2511 else
2512#endif
2513 if (error)
2514 {
2515 STRCAT(IObuff, _("[READ ERRORS]"));
2516 c = TRUE;
2517 }
2518 if (msg_add_fileformat(fileformat))
2519 c = TRUE;
2520#ifdef FEAT_CRYPT
2521 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002522 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar80794b12010-06-13 05:20:42 +02002523 - CRYPT_MAGIC_LEN
2524 - crypt_salt_len[use_crypt_method]
2525 - crypt_seed_len[use_crypt_method]);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 else
2527#endif
2528 msg_add_lines(c, (long)linecnt, filesize);
2529
2530 vim_free(keep_msg);
2531 keep_msg = NULL;
2532 msg_scrolled_ign = TRUE;
2533#ifdef ALWAYS_USE_GUI
2534 /* Don't show the message when reading stdin, it would end up in a
2535 * message box (which might be shown when exiting!) */
2536 if (read_stdin || read_buffer)
2537 p = msg_may_trunc(FALSE, IObuff);
2538 else
2539#endif
2540 p = msg_trunc_attr(IObuff, FALSE, 0);
2541 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002542 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543 /* Need to repeat the message after redrawing when:
2544 * - When reading from stdin (the screen will be cleared next).
2545 * - When restart_edit is set (otherwise there will be a delay
2546 * before redrawing).
2547 * - When the screen was scrolled but there is no wait-return
2548 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002549 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002550 msg_scrolled_ign = FALSE;
2551 }
2552
2553 /* with errors writing the file requires ":w!" */
2554 if (newfile && (error
2555#ifdef FEAT_MBYTE
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002556 || conv_error != 0
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002557 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002558#endif
2559 ))
2560 curbuf->b_p_ro = TRUE;
2561
2562 u_clearline(); /* cannot use "U" command after adding lines */
2563
2564 /*
2565 * In Ex mode: cursor at last new line.
2566 * Otherwise: cursor at first new line.
2567 */
2568 if (exmode_active)
2569 curwin->w_cursor.lnum = from + linecnt;
2570 else
2571 curwin->w_cursor.lnum = from + 1;
2572 check_cursor_lnum();
2573 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2574
2575 /*
2576 * Set '[ and '] marks to the newly read lines.
2577 */
2578 curbuf->b_op_start.lnum = from + 1;
2579 curbuf->b_op_start.col = 0;
2580 curbuf->b_op_end.lnum = from + linecnt;
2581 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002582
2583#ifdef WIN32
2584 /*
2585 * Work around a weird problem: When a file has two links (only
2586 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002587 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002588 * It's correct again after reading the file, thus reset the timestamp
2589 * here.
2590 */
2591 if (newfile && !read_stdin && !read_buffer
2592 && mch_stat((char *)fname, &st) >= 0)
2593 {
2594 buf_store_time(curbuf, &st, fname);
2595 curbuf->b_mtime_read = curbuf->b_mtime;
2596 }
2597#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002598 }
2599 msg_scroll = msg_save;
2600
2601#ifdef FEAT_VIMINFO
2602 /*
2603 * Get the marks before executing autocommands, so they can be used there.
2604 */
2605 check_marks_read();
2606#endif
2607
Bram Moolenaar071d4272004-06-13 20:20:40 +00002608 /*
2609 * Trick: We remember if the last line of the read didn't have
2610 * an eol for when writing it again. This is required for
2611 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
2612 */
2613 write_no_eol_lnum = read_no_eol_lnum;
2614
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002615 /* When reloading a buffer put the cursor at the first line that is
2616 * different. */
2617 if (flags & READ_KEEP_UNDO)
2618 u_find_first_changed();
2619
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002620#ifdef FEAT_PERSISTENT_UNDO
2621 /*
2622 * When opening a new file locate undo info and read it.
2623 */
2624 if (read_undo_file)
2625 {
2626 char_u hash[UNDO_HASH_SIZE];
2627
2628 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002629 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002630 }
2631#endif
2632
Bram Moolenaardf177f62005-02-22 08:39:57 +00002633#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00002634 if (!read_stdin && !read_buffer)
2635 {
2636 int m = msg_scroll;
2637 int n = msg_scrolled;
2638
2639 /* Save the fileformat now, otherwise the buffer will be considered
2640 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002641 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 save_file_ff(curbuf);
2643
2644 /*
2645 * The output from the autocommands should not overwrite anything and
2646 * should not be overwritten: Set msg_scroll, restore its value if no
2647 * output was done.
2648 */
2649 msg_scroll = TRUE;
2650 if (filtering)
2651 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2652 FALSE, curbuf, eap);
2653 else if (newfile)
2654 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2655 FALSE, curbuf, eap);
2656 else
2657 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2658 FALSE, NULL, eap);
2659 if (msg_scrolled == n)
2660 msg_scroll = m;
2661#ifdef FEAT_EVAL
2662 if (aborting()) /* autocmds may abort script processing */
2663 return FAIL;
2664#endif
2665 }
2666#endif
2667
2668 if (recoverymode && error)
2669 return FAIL;
2670 return OK;
2671}
2672
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002673#ifdef OPEN_CHR_FILES
2674/*
2675 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2676 * which is the name of files used for process substitution output by
2677 * some shells on some operating systems, e.g., bash on SunOS.
2678 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2679 */
2680 static int
2681is_dev_fd_file(fname)
2682 char_u *fname;
2683{
2684 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2685 && VIM_ISDIGIT(fname[8])
2686 && *skipdigits(fname + 9) == NUL
2687 && (fname[9] != NUL
2688 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2689}
2690#endif
2691
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002692#ifdef FEAT_MBYTE
2693
2694/*
2695 * From the current line count and characters read after that, estimate the
2696 * line number where we are now.
2697 * Used for error messages that include a line number.
2698 */
2699 static linenr_T
2700readfile_linenr(linecnt, p, endp)
2701 linenr_T linecnt; /* line count before reading more bytes */
2702 char_u *p; /* start of more bytes read */
2703 char_u *endp; /* end of more bytes read */
2704{
2705 char_u *s;
2706 linenr_T lnum;
2707
2708 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2709 for (s = p; s < endp; ++s)
2710 if (*s == '\n')
2711 ++lnum;
2712 return lnum;
2713}
2714#endif
2715
Bram Moolenaar071d4272004-06-13 20:20:40 +00002716/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002717 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2718 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002719 * Returns OK or FAIL.
2720 */
2721 int
2722prep_exarg(eap, buf)
2723 exarg_T *eap;
2724 buf_T *buf;
2725{
2726 eap->cmd = alloc((unsigned)(STRLEN(buf->b_p_ff)
2727#ifdef FEAT_MBYTE
2728 + STRLEN(buf->b_p_fenc)
2729#endif
2730 + 15));
2731 if (eap->cmd == NULL)
2732 return FAIL;
2733
2734#ifdef FEAT_MBYTE
2735 sprintf((char *)eap->cmd, "e ++ff=%s ++enc=%s", buf->b_p_ff, buf->b_p_fenc);
2736 eap->force_enc = 14 + (int)STRLEN(buf->b_p_ff);
Bram Moolenaar195d6352005-12-19 22:08:24 +00002737 eap->bad_char = buf->b_bad_char;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002738#else
2739 sprintf((char *)eap->cmd, "e ++ff=%s", buf->b_p_ff);
2740#endif
2741 eap->force_ff = 7;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002742
2743 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002744 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002745 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746 return OK;
2747}
2748
2749#ifdef FEAT_MBYTE
2750/*
2751 * Find next fileencoding to use from 'fileencodings'.
2752 * "pp" points to fenc_next. It's advanced to the next item.
2753 * When there are no more items, an empty string is returned and *pp is set to
2754 * NULL.
2755 * When *pp is not set to NULL, the result is in allocated memory.
2756 */
2757 static char_u *
2758next_fenc(pp)
2759 char_u **pp;
2760{
2761 char_u *p;
2762 char_u *r;
2763
2764 if (**pp == NUL)
2765 {
2766 *pp = NULL;
2767 return (char_u *)"";
2768 }
2769 p = vim_strchr(*pp, ',');
2770 if (p == NULL)
2771 {
2772 r = enc_canonize(*pp);
2773 *pp += STRLEN(*pp);
2774 }
2775 else
2776 {
2777 r = vim_strnsave(*pp, (int)(p - *pp));
2778 *pp = p + 1;
2779 if (r != NULL)
2780 {
2781 p = enc_canonize(r);
2782 vim_free(r);
2783 r = p;
2784 }
2785 }
2786 if (r == NULL) /* out of memory */
2787 {
2788 r = (char_u *)"";
2789 *pp = NULL;
2790 }
2791 return r;
2792}
2793
2794# ifdef FEAT_EVAL
2795/*
2796 * Convert a file with the 'charconvert' expression.
2797 * This closes the file which is to be read, converts it and opens the
2798 * resulting file for reading.
2799 * Returns name of the resulting converted file (the caller should delete it
2800 * after reading it).
2801 * Returns NULL if the conversion failed ("*fdp" is not set) .
2802 */
2803 static char_u *
2804readfile_charconvert(fname, fenc, fdp)
2805 char_u *fname; /* name of input file */
2806 char_u *fenc; /* converted from */
2807 int *fdp; /* in/out: file descriptor of file */
2808{
2809 char_u *tmpname;
2810 char_u *errmsg = NULL;
2811
2812 tmpname = vim_tempname('r');
2813 if (tmpname == NULL)
2814 errmsg = (char_u *)_("Can't find temp file for conversion");
2815 else
2816 {
2817 close(*fdp); /* close the input file, ignore errors */
2818 *fdp = -1;
2819 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2820 fname, tmpname) == FAIL)
2821 errmsg = (char_u *)_("Conversion with 'charconvert' failed");
2822 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2823 O_RDONLY | O_EXTRA, 0)) < 0)
2824 errmsg = (char_u *)_("can't read output of 'charconvert'");
2825 }
2826
2827 if (errmsg != NULL)
2828 {
2829 /* Don't use emsg(), it breaks mappings, the retry with
2830 * another type of conversion might still work. */
2831 MSG(errmsg);
2832 if (tmpname != NULL)
2833 {
2834 mch_remove(tmpname); /* delete converted file */
2835 vim_free(tmpname);
2836 tmpname = NULL;
2837 }
2838 }
2839
2840 /* If the input file is closed, open it (caller should check for error). */
2841 if (*fdp < 0)
2842 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2843
2844 return tmpname;
2845}
2846# endif
2847
2848#endif
2849
2850#ifdef FEAT_VIMINFO
2851/*
2852 * Read marks for the current buffer from the viminfo file, when we support
2853 * buffer marks and the buffer has a name.
2854 */
2855 static void
2856check_marks_read()
2857{
2858 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2859 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002860 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002861
2862 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2863 * the ' parameter after opening a buffer. */
2864 curbuf->b_marks_read = TRUE;
2865}
2866#endif
2867
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002868#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002869/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002870 * Get the crypt method used for a file from "ptr[len]", the magic text at the
2871 * start of the file.
2872 * Returns -1 when no encryption used.
2873 */
2874 static int
Bram Moolenaar49771f42010-07-20 17:32:38 +02002875crypt_method_from_magic(ptr, len)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002876 char *ptr;
2877 int len;
2878{
2879 int i;
2880
2881 for (i = 0; i < (int)(sizeof(crypt_magic) / sizeof(crypt_magic[0])); i++)
2882 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002883 if (len < (CRYPT_MAGIC_LEN + crypt_salt_len[i] + crypt_seed_len[i]))
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002884 continue;
2885 if (memcmp(ptr, crypt_magic[i], CRYPT_MAGIC_LEN) == 0)
2886 return i;
2887 }
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002888
Bram Moolenaar442b4222010-05-24 21:34:22 +02002889 i = (int)STRLEN(crypt_magic_head);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002890 if (len >= i && memcmp(ptr, crypt_magic_head, i) == 0)
2891 EMSG(_("E821: File is encrypted with unknown method"));
2892
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002893 return -1;
2894}
2895
2896/*
2897 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2899 * *filesizep are updated.
2900 * Return the (new) encryption key, NULL for no encryption.
2901 */
2902 static char_u *
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002903check_for_cryptkey(cryptkey, ptr, sizep, filesizep, newfile, fname, did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002904 char_u *cryptkey; /* previous encryption key or NULL */
2905 char_u *ptr; /* pointer to read bytes */
2906 long *sizep; /* length of read bytes */
Bram Moolenaar914703b2010-05-31 21:59:46 +02002907 off_t *filesizep; /* nr of bytes used from file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002908 int newfile; /* editing a new buffer */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002909 char_u *fname; /* file name to display */
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002910 int *did_ask; /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002911{
Bram Moolenaar49771f42010-07-20 17:32:38 +02002912 int method = crypt_method_from_magic((char *)ptr, *sizep);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002913
2914 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002915 {
Bram Moolenaar49771f42010-07-20 17:32:38 +02002916 set_crypt_method(curbuf, method);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002917 if (method > 0)
2918 (void)blowfish_self_test();
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002919 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002920 {
2921 if (*curbuf->b_p_key)
2922 cryptkey = curbuf->b_p_key;
2923 else
2924 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002925 /* When newfile is TRUE, store the typed key in the 'key'
2926 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002927 * Don't ask for the key again when first time Enter was hit.
2928 * Happens when retrying to detect encoding. */
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002929 smsg((char_u *)_(need_key_msg), fname);
2930 msg_scroll = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002931 cryptkey = get_crypt_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002932 *did_ask = TRUE;
2933
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 /* check if empty key entered */
2935 if (cryptkey != NULL && *cryptkey == NUL)
2936 {
2937 if (cryptkey != curbuf->b_p_key)
2938 vim_free(cryptkey);
2939 cryptkey = NULL;
2940 }
2941 }
2942 }
2943
2944 if (cryptkey != NULL)
2945 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002946 int seed_len = crypt_seed_len[method];
Bram Moolenaar80794b12010-06-13 05:20:42 +02002947 int salt_len = crypt_salt_len[method];
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002948
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002949 crypt_push_state();
2950 use_crypt_method = method;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002951 if (method == 0)
2952 crypt_init_keys(cryptkey);
2953 else
2954 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02002955 bf_key_init(cryptkey, ptr + CRYPT_MAGIC_LEN, salt_len);
2956 bf_ofb_init(ptr + CRYPT_MAGIC_LEN + salt_len, seed_len);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002957 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002958
2959 /* Remove magic number from the text */
Bram Moolenaar80794b12010-06-13 05:20:42 +02002960 *filesizep += CRYPT_MAGIC_LEN + salt_len + seed_len;
2961 *sizep -= CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002962 mch_memmove(ptr, ptr + CRYPT_MAGIC_LEN + salt_len + seed_len,
2963 (size_t)*sizep);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002964 }
2965 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002966 /* When starting to edit a new file which does not have encryption, clear
2967 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002968 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002969 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2970
2971 return cryptkey;
2972}
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002973
2974/*
2975 * Check for magic number used for encryption. Applies to the current buffer.
2976 * If found and decryption is possible returns OK;
2977 */
2978 int
2979prepare_crypt_read(fp)
2980 FILE *fp;
2981{
2982 int method;
Bram Moolenaar80794b12010-06-13 05:20:42 +02002983 char_u buffer[CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
2984 + CRYPT_SEED_LEN_MAX + 2];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002985
2986 if (fread(buffer, CRYPT_MAGIC_LEN, 1, fp) != 1)
2987 return FAIL;
Bram Moolenaar49771f42010-07-20 17:32:38 +02002988 method = crypt_method_from_magic((char *)buffer,
Bram Moolenaar80794b12010-06-13 05:20:42 +02002989 CRYPT_MAGIC_LEN +
Bram Moolenaarcc448b32010-07-14 16:52:17 +02002990 CRYPT_SEED_LEN_MAX +
2991 CRYPT_SALT_LEN_MAX);
Bram Moolenaar49771f42010-07-20 17:32:38 +02002992 if (method < 0 || method != get_crypt_method(curbuf))
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002993 return FAIL;
2994
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002995 crypt_push_state();
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002996 if (method == 0)
2997 crypt_init_keys(curbuf->b_p_key);
2998 else
2999 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003000 int salt_len = crypt_salt_len[method];
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003001 int seed_len = crypt_seed_len[method];
3002
Bram Moolenaar80794b12010-06-13 05:20:42 +02003003 if (fread(buffer, salt_len + seed_len, 1, fp) != 1)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003004 return FAIL;
Bram Moolenaar80794b12010-06-13 05:20:42 +02003005 bf_key_init(curbuf->b_p_key, buffer, salt_len);
3006 bf_ofb_init(buffer + salt_len, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003007 }
3008 return OK;
3009}
3010
3011/*
3012 * Prepare for writing encrypted bytes for buffer "buf".
3013 * Returns a pointer to an allocated header of length "*lenp".
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003014 * When out of memory returns NULL.
3015 * Otherwise calls crypt_push_state(), call crypt_pop_state() later.
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003016 */
3017 char_u *
3018prepare_crypt_write(buf, lenp)
3019 buf_T *buf;
3020 int *lenp;
3021{
3022 char_u *header;
Bram Moolenaar49771f42010-07-20 17:32:38 +02003023 int seed_len = crypt_seed_len[get_crypt_method(buf)];
3024 int salt_len = crypt_salt_len[get_crypt_method(buf)];
Bram Moolenaar80794b12010-06-13 05:20:42 +02003025 char_u *salt;
3026 char_u *seed;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003027
Bram Moolenaar80794b12010-06-13 05:20:42 +02003028 header = alloc_clear(CRYPT_MAGIC_LEN + CRYPT_SALT_LEN_MAX
3029 + CRYPT_SEED_LEN_MAX + 2);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003030 if (header != NULL)
3031 {
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02003032 crypt_push_state();
Bram Moolenaar49771f42010-07-20 17:32:38 +02003033 use_crypt_method = get_crypt_method(buf); /* select zip or blowfish */
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003034 vim_strncpy(header, (char_u *)crypt_magic[use_crypt_method],
3035 CRYPT_MAGIC_LEN);
Bram Moolenaar49771f42010-07-20 17:32:38 +02003036 if (use_crypt_method == 0)
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003037 crypt_init_keys(buf->b_p_key);
3038 else
3039 {
Bram Moolenaar80794b12010-06-13 05:20:42 +02003040 /* Using blowfish, add salt and seed. */
3041 salt = header + CRYPT_MAGIC_LEN;
3042 seed = salt + salt_len;
3043 sha2_seed(salt, salt_len, seed, seed_len);
3044 bf_key_init(buf->b_p_key, salt, salt_len);
3045 bf_ofb_init(seed, seed_len);
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003046 }
3047 }
Bram Moolenaar80794b12010-06-13 05:20:42 +02003048 *lenp = CRYPT_MAGIC_LEN + salt_len + seed_len;
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02003049 return header;
3050}
3051
Bram Moolenaar80794b12010-06-13 05:20:42 +02003052#endif /* FEAT_CRYPT */
3053
Bram Moolenaar071d4272004-06-13 20:20:40 +00003054#ifdef UNIX
3055 static void
3056set_file_time(fname, atime, mtime)
3057 char_u *fname;
3058 time_t atime; /* access time */
3059 time_t mtime; /* modification time */
3060{
3061# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
3062 struct utimbuf buf;
3063
3064 buf.actime = atime;
3065 buf.modtime = mtime;
3066 (void)utime((char *)fname, &buf);
3067# else
3068# if defined(HAVE_UTIMES)
3069 struct timeval tvp[2];
3070
3071 tvp[0].tv_sec = atime;
3072 tvp[0].tv_usec = 0;
3073 tvp[1].tv_sec = mtime;
3074 tvp[1].tv_usec = 0;
3075# ifdef NeXT
3076 (void)utimes((char *)fname, tvp);
3077# else
3078 (void)utimes((char *)fname, (const struct timeval *)&tvp);
3079# endif
3080# endif
3081# endif
3082}
3083#endif /* UNIX */
3084
Bram Moolenaard4755bb2004-09-02 19:12:26 +00003085#if defined(VMS) && !defined(MIN)
3086/* Older DECC compiler for VAX doesn't define MIN() */
3087# define MIN(a, b) ((a) < (b) ? (a) : (b))
3088#endif
3089
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00003091 * Return TRUE if a file appears to be read-only from the file permissions.
3092 */
3093 int
3094check_file_readonly(fname, perm)
3095 char_u *fname; /* full path to file */
3096 int perm; /* known permissions on file */
3097{
3098#ifndef USE_MCH_ACCESS
3099 int fd = 0;
3100#endif
3101
3102 return (
3103#ifdef USE_MCH_ACCESS
3104# ifdef UNIX
3105 (perm & 0222) == 0 ||
3106# endif
3107 mch_access((char *)fname, W_OK)
3108#else
3109 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3110 ? TRUE : (close(fd), FALSE)
3111#endif
3112 );
3113}
3114
3115
3116/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003117 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003118 *
3119 * We do our own buffering here because fwrite() is so slow.
3120 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003121 * If "forceit" is true, we don't care for errors when attempting backups.
3122 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003123 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003124 *
3125 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3126 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003127 *
3128 * This function must NOT use NameBuff (because it's called by autowrite()).
3129 *
3130 * return FAIL for failure, OK otherwise
3131 */
3132 int
3133buf_write(buf, fname, sfname, start, end, eap, append, forceit,
3134 reset_changed, filtering)
3135 buf_T *buf;
3136 char_u *fname;
3137 char_u *sfname;
3138 linenr_T start, end;
3139 exarg_T *eap; /* for forced 'ff' and 'fenc', can be
3140 NULL! */
Bram Moolenaar292ad192005-12-11 21:29:51 +00003141 int append; /* append to the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142 int forceit;
3143 int reset_changed;
3144 int filtering;
3145{
3146 int fd;
3147 char_u *backup = NULL;
3148 int backup_copy = FALSE; /* copy the original file? */
3149 int dobackup;
3150 char_u *ffname;
3151 char_u *wfname = NULL; /* name of file to write to */
3152 char_u *s;
3153 char_u *ptr;
3154 char_u c;
3155 int len;
3156 linenr_T lnum;
3157 long nchars;
3158 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003159 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 char_u *errnum = NULL;
3161 char_u *buffer;
3162 char_u smallbuf[SMBUFSIZE];
3163 char_u *backup_ext;
3164 int bufsize;
3165 long perm; /* file permissions */
3166 int retval = OK;
3167 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3168 int msg_save = msg_scroll;
3169 int overwriting; /* TRUE if writing over original */
3170 int no_eol = FALSE; /* no end-of-line written */
3171 int device = FALSE; /* writing to a device */
3172 struct stat st_old;
3173 int prev_got_int = got_int;
3174 int file_readonly = FALSE; /* overwritten file is read-only */
3175 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
3176#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
3177 int made_writable = FALSE; /* 'w' bit has been set */
3178#endif
3179 /* writing everything */
3180 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
3181#ifdef FEAT_AUTOCMD
3182 linenr_T old_line_count = buf->b_ml.ml_line_count;
3183#endif
3184 int attr;
3185 int fileformat;
3186 int write_bin;
3187 struct bw_info write_info; /* info for buf_write_bytes() */
3188#ifdef FEAT_MBYTE
3189 int converted = FALSE;
3190 int notconverted = FALSE;
3191 char_u *fenc; /* effective 'fileencoding' */
3192 char_u *fenc_tofree = NULL; /* allocated "fenc" */
3193#endif
3194#ifdef HAS_BW_FLAGS
3195 int wb_flags = 0;
3196#endif
3197#ifdef HAVE_ACL
3198 vim_acl_T acl = NULL; /* ACL copied from original file to
3199 backup or new file */
3200#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003201#ifdef FEAT_PERSISTENT_UNDO
3202 int write_undo_file = FALSE;
3203 context_sha256_T sha_ctx;
3204#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205
3206 if (fname == NULL || *fname == NUL) /* safety check */
3207 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003208 if (buf->b_ml.ml_mfp == NULL)
3209 {
3210 /* This can happen during startup when there is a stray "w" in the
3211 * vimrc file. */
3212 EMSG(_(e_emptybuf));
3213 return FAIL;
3214 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215
3216 /*
3217 * Disallow writing from .exrc and .vimrc in current directory for
3218 * security reasons.
3219 */
3220 if (check_secure())
3221 return FAIL;
3222
3223 /* Avoid a crash for a long name. */
3224 if (STRLEN(fname) >= MAXPATHL)
3225 {
3226 EMSG(_(e_longname));
3227 return FAIL;
3228 }
3229
3230#ifdef FEAT_MBYTE
3231 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3232 write_info.bw_conv_buf = NULL;
3233 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003234 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003235 write_info.bw_restlen = 0;
3236# ifdef USE_ICONV
3237 write_info.bw_iconv_fd = (iconv_t)-1;
3238# endif
3239#endif
3240
Bram Moolenaardf177f62005-02-22 08:39:57 +00003241 /* After writing a file changedtick changes but we don't want to display
3242 * the line. */
3243 ex_no_reprint = TRUE;
3244
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 /*
3246 * If there is no file name yet, use the one for the written file.
3247 * BF_NOTEDITED is set to reflect this (in case the write fails).
3248 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003249 * Don't do this when appending.
3250 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003251 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003252 if (buf->b_ffname == NULL
3253 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003254 && whole
3255 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003256#ifdef FEAT_QUICKFIX
3257 && !bt_nofile(buf)
3258#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003259 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003260 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003261 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3262 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003263 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003264 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003265 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003266 }
3267
3268 if (sfname == NULL)
3269 sfname = fname;
3270 /*
3271 * For Unix: Use the short file name whenever possible.
3272 * Avoids problems with networks and when directory names are changed.
3273 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3274 * another directory, which we don't detect
3275 */
3276 ffname = fname; /* remember full fname */
3277#ifdef UNIX
3278 fname = sfname;
3279#endif
3280
3281 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3282 overwriting = TRUE;
3283 else
3284 overwriting = FALSE;
3285
3286 if (exiting)
3287 settmode(TMODE_COOK); /* when exiting allow typahead now */
3288
3289 ++no_wait_return; /* don't wait for return yet */
3290
3291 /*
3292 * Set '[ and '] marks to the lines to be written.
3293 */
3294 buf->b_op_start.lnum = start;
3295 buf->b_op_start.col = 0;
3296 buf->b_op_end.lnum = end;
3297 buf->b_op_end.col = 0;
3298
3299#ifdef FEAT_AUTOCMD
3300 {
3301 aco_save_T aco;
3302 int buf_ffname = FALSE;
3303 int buf_sfname = FALSE;
3304 int buf_fname_f = FALSE;
3305 int buf_fname_s = FALSE;
3306 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003307 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003308 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003309
3310 /*
3311 * Apply PRE aucocommands.
3312 * Set curbuf to the buffer to be written.
3313 * Careful: The autocommands may call buf_write() recursively!
3314 */
3315 if (ffname == buf->b_ffname)
3316 buf_ffname = TRUE;
3317 if (sfname == buf->b_sfname)
3318 buf_sfname = TRUE;
3319 if (fname == buf->b_ffname)
3320 buf_fname_f = TRUE;
3321 if (fname == buf->b_sfname)
3322 buf_fname_s = TRUE;
3323
3324 /* set curwin/curbuf to buf and save a few things */
3325 aucmd_prepbuf(&aco, buf);
3326
3327 if (append)
3328 {
3329 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3330 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003331 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003332#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003333 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003334 nofile_err = TRUE;
3335 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003336#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003337 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003338 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003340 }
3341 else if (filtering)
3342 {
3343 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3344 NULL, sfname, FALSE, curbuf, eap);
3345 }
3346 else if (reset_changed && whole)
3347 {
3348 if (!(did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3349 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003350 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003351#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003352 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003353 nofile_err = TRUE;
3354 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003355#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003356 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003357 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003358 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003359 }
3360 else
3361 {
3362 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3363 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003364 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003365#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003366 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003367 nofile_err = TRUE;
3368 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003369#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003370 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003371 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003373 }
3374
3375 /* restore curwin/curbuf and a few other things */
3376 aucmd_restbuf(&aco);
3377
3378 /*
3379 * In three situations we return here and don't write the file:
3380 * 1. the autocommands deleted or unloaded the buffer.
3381 * 2. The autocommands abort script processing.
3382 * 3. If one of the "Cmd" autocommands was executed.
3383 */
3384 if (!buf_valid(buf))
3385 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003386 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003387 || did_cmd || nofile_err
3388#ifdef FEAT_EVAL
3389 || aborting()
3390#endif
3391 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003392 {
3393 --no_wait_return;
3394 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003395 if (nofile_err)
3396 EMSG(_("E676: No matching autocommands for acwrite buffer"));
3397
Bram Moolenaar1e015462005-09-25 22:16:38 +00003398 if (nofile_err
3399#ifdef FEAT_EVAL
3400 || aborting()
3401#endif
3402 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003403 /* An aborting error, interrupt or exception in the
3404 * autocommands. */
3405 return FAIL;
3406 if (did_cmd)
3407 {
3408 if (buf == NULL)
3409 /* The buffer was deleted. We assume it was written
3410 * (can't retry anyway). */
3411 return OK;
3412 if (overwriting)
3413 {
3414 /* Assume the buffer was written, update the timestamp. */
3415 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003416 if (append)
3417 buf->b_flags &= ~BF_NEW;
3418 else
3419 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003421 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003422 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003423 /* Buffer still changed, the autocommands didn't work
3424 * properly. */
3425 return FAIL;
3426 return OK;
3427 }
3428#ifdef FEAT_EVAL
3429 if (!aborting())
3430#endif
3431 EMSG(_("E203: Autocommands deleted or unloaded buffer to be written"));
3432 return FAIL;
3433 }
3434
3435 /*
3436 * The autocommands may have changed the number of lines in the file.
3437 * When writing the whole file, adjust the end.
3438 * When writing part of the file, assume that the autocommands only
3439 * changed the number of lines that are to be written (tricky!).
3440 */
3441 if (buf->b_ml.ml_line_count != old_line_count)
3442 {
3443 if (whole) /* write all */
3444 end = buf->b_ml.ml_line_count;
3445 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3446 end += buf->b_ml.ml_line_count - old_line_count;
3447 else /* less lines */
3448 {
3449 end -= old_line_count - buf->b_ml.ml_line_count;
3450 if (end < start)
3451 {
3452 --no_wait_return;
3453 msg_scroll = msg_save;
3454 EMSG(_("E204: Autocommand changed number of lines in unexpected way"));
3455 return FAIL;
3456 }
3457 }
3458 }
3459
3460 /*
3461 * The autocommands may have changed the name of the buffer, which may
3462 * be kept in fname, ffname and sfname.
3463 */
3464 if (buf_ffname)
3465 ffname = buf->b_ffname;
3466 if (buf_sfname)
3467 sfname = buf->b_sfname;
3468 if (buf_fname_f)
3469 fname = buf->b_ffname;
3470 if (buf_fname_s)
3471 fname = buf->b_sfname;
3472 }
3473#endif
3474
3475#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003476 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003477 {
3478 if (whole)
3479 {
3480 /*
3481 * b_changed can be 0 after an undo, but we still need to write
3482 * the buffer to NetBeans.
3483 */
3484 if (buf->b_changed || isNetbeansModified(buf))
3485 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003486 --no_wait_return; /* may wait for return now */
3487 msg_scroll = msg_save;
3488 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003489 return retval;
3490 }
3491 else
3492 {
3493 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003494 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495 buffer = NULL;
3496 goto fail;
3497 }
3498 }
3499 else
3500 {
3501 errnum = (char_u *)"E657: ";
3502 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3503 buffer = NULL;
3504 goto fail;
3505 }
3506 }
3507#endif
3508
3509 if (shortmess(SHM_OVER) && !exiting)
3510 msg_scroll = FALSE; /* overwrite previous file message */
3511 else
3512 msg_scroll = TRUE; /* don't overwrite previous file message */
3513 if (!filtering)
3514 filemess(buf,
3515#ifndef UNIX
3516 sfname,
3517#else
3518 fname,
3519#endif
3520 (char_u *)"", 0); /* show that we are busy */
3521 msg_scroll = FALSE; /* always overwrite the file message now */
3522
3523 buffer = alloc(BUFSIZE);
3524 if (buffer == NULL) /* can't allocate big buffer, use small
3525 * one (to be able to write when out of
3526 * memory) */
3527 {
3528 buffer = smallbuf;
3529 bufsize = SMBUFSIZE;
3530 }
3531 else
3532 bufsize = BUFSIZE;
3533
3534 /*
3535 * Get information about original file (if there is one).
3536 */
3537#if defined(UNIX) && !defined(ARCHIE)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003538 st_old.st_dev = 0;
3539 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540 perm = -1;
3541 if (mch_stat((char *)fname, &st_old) < 0)
3542 newfile = TRUE;
3543 else
3544 {
3545 perm = st_old.st_mode;
3546 if (!S_ISREG(st_old.st_mode)) /* not a file */
3547 {
3548 if (S_ISDIR(st_old.st_mode))
3549 {
3550 errnum = (char_u *)"E502: ";
3551 errmsg = (char_u *)_("is a directory");
3552 goto fail;
3553 }
3554 if (mch_nodetype(fname) != NODE_WRITABLE)
3555 {
3556 errnum = (char_u *)"E503: ";
3557 errmsg = (char_u *)_("is not a file or writable device");
3558 goto fail;
3559 }
3560 /* It's a device of some kind (or a fifo) which we can write to
3561 * but for which we can't make a backup. */
3562 device = TRUE;
3563 newfile = TRUE;
3564 perm = -1;
3565 }
3566 }
3567#else /* !UNIX */
3568 /*
3569 * Check for a writable device name.
3570 */
3571 c = mch_nodetype(fname);
3572 if (c == NODE_OTHER)
3573 {
3574 errnum = (char_u *)"E503: ";
3575 errmsg = (char_u *)_("is not a file or writable device");
3576 goto fail;
3577 }
3578 if (c == NODE_WRITABLE)
3579 {
Bram Moolenaar043545e2006-10-10 16:44:07 +00003580# if defined(MSDOS) || defined(MSWIN) || defined(OS2)
3581 /* MS-Windows allows opening a device, but we will probably get stuck
3582 * trying to write to it. */
3583 if (!p_odev)
3584 {
3585 errnum = (char_u *)"E796: ";
3586 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3587 goto fail;
3588 }
3589# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003590 device = TRUE;
3591 newfile = TRUE;
3592 perm = -1;
3593 }
3594 else
3595 {
3596 perm = mch_getperm(fname);
3597 if (perm < 0)
3598 newfile = TRUE;
3599 else if (mch_isdir(fname))
3600 {
3601 errnum = (char_u *)"E502: ";
3602 errmsg = (char_u *)_("is a directory");
3603 goto fail;
3604 }
3605 if (overwriting)
3606 (void)mch_stat((char *)fname, &st_old);
3607 }
3608#endif /* !UNIX */
3609
3610 if (!device && !newfile)
3611 {
3612 /*
3613 * Check if the file is really writable (when renaming the file to
3614 * make a backup we won't discover it later).
3615 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003616 file_readonly = check_file_readonly(fname, (int)perm);
3617
Bram Moolenaar071d4272004-06-13 20:20:40 +00003618 if (!forceit && file_readonly)
3619 {
3620 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3621 {
3622 errnum = (char_u *)"E504: ";
3623 errmsg = (char_u *)_(err_readonly);
3624 }
3625 else
3626 {
3627 errnum = (char_u *)"E505: ";
3628 errmsg = (char_u *)_("is read-only (add ! to override)");
3629 }
3630 goto fail;
3631 }
3632
3633 /*
3634 * Check if the timestamp hasn't changed since reading the file.
3635 */
3636 if (overwriting)
3637 {
3638 retval = check_mtime(buf, &st_old);
3639 if (retval == FAIL)
3640 goto fail;
3641 }
3642 }
3643
3644#ifdef HAVE_ACL
3645 /*
3646 * For systems that support ACL: get the ACL from the original file.
3647 */
3648 if (!newfile)
3649 acl = mch_get_acl(fname);
3650#endif
3651
3652 /*
3653 * If 'backupskip' is not empty, don't make a backup for some files.
3654 */
3655 dobackup = (p_wb || p_bk || *p_pm != NUL);
3656#ifdef FEAT_WILDIGN
3657 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3658 dobackup = FALSE;
3659#endif
3660
3661 /*
3662 * Save the value of got_int and reset it. We don't want a previous
3663 * interruption cancel writing, only hitting CTRL-C while writing should
3664 * abort it.
3665 */
3666 prev_got_int = got_int;
3667 got_int = FALSE;
3668
3669 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3670 buf->b_saving = TRUE;
3671
3672 /*
3673 * If we are not appending or filtering, the file exists, and the
3674 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3675 * When 'patchmode' is set also make a backup when appending.
3676 *
3677 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3678 * off. This helps when editing large files on almost-full disks.
3679 */
3680 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3681 {
3682#if defined(UNIX) || defined(WIN32)
3683 struct stat st;
3684#endif
3685
3686 if ((bkc_flags & BKC_YES) || append) /* "yes" */
3687 backup_copy = TRUE;
3688#if defined(UNIX) || defined(WIN32)
3689 else if ((bkc_flags & BKC_AUTO)) /* "auto" */
3690 {
3691 int i;
3692
3693# ifdef UNIX
3694 /*
3695 * Don't rename the file when:
3696 * - it's a hard link
3697 * - it's a symbolic link
3698 * - we don't have write permission in the directory
3699 * - we can't set the owner/group of the new file
3700 */
3701 if (st_old.st_nlink > 1
3702 || mch_lstat((char *)fname, &st) < 0
3703 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003704 || st.st_ino != st_old.st_ino
3705# ifndef HAVE_FCHOWN
3706 || st.st_uid != st_old.st_uid
3707 || st.st_gid != st_old.st_gid
3708# endif
3709 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003710 backup_copy = TRUE;
3711 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003712# else
3713# ifdef WIN32
3714 /* On NTFS file systems hard links are possible. */
3715 if (mch_is_linked(fname))
3716 backup_copy = TRUE;
3717 else
3718# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003719# endif
3720 {
3721 /*
3722 * Check if we can create a file and set the owner/group to
3723 * the ones from the original file.
3724 * First find a file name that doesn't exist yet (use some
3725 * arbitrary numbers).
3726 */
3727 STRCPY(IObuff, fname);
3728 for (i = 4913; ; i += 123)
3729 {
3730 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003731 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 break;
3733 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003734 fd = mch_open((char *)IObuff,
3735 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003736 if (fd < 0) /* can't write in directory */
3737 backup_copy = TRUE;
3738 else
3739 {
3740# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003741# ifdef HAVE_FCHOWN
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00003742 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003743# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003744 if (mch_stat((char *)IObuff, &st) < 0
3745 || st.st_uid != st_old.st_uid
3746 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003747 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003748 backup_copy = TRUE;
3749# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003750 /* Close the file before removing it, on MS-Windows we
3751 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003752 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003753 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003754# ifdef MSWIN
3755 /* MS-Windows may trigger a virus scanner to open the
3756 * file, we can't delete it then. Keep trying for half a
3757 * second. */
3758 {
3759 int try;
3760
3761 for (try = 0; try < 10; ++try)
3762 {
3763 if (mch_lstat((char *)IObuff, &st) < 0)
3764 break;
3765 ui_delay(50L, TRUE); /* wait 50 msec */
3766 mch_remove(IObuff);
3767 }
3768 }
3769# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003770 }
3771 }
3772 }
3773
3774# ifdef UNIX
3775 /*
3776 * Break symlinks and/or hardlinks if we've been asked to.
3777 */
3778 if ((bkc_flags & BKC_BREAKSYMLINK) || (bkc_flags & BKC_BREAKHARDLINK))
3779 {
3780 int lstat_res;
3781
3782 lstat_res = mch_lstat((char *)fname, &st);
3783
3784 /* Symlinks. */
3785 if ((bkc_flags & BKC_BREAKSYMLINK)
3786 && lstat_res == 0
3787 && st.st_ino != st_old.st_ino)
3788 backup_copy = FALSE;
3789
3790 /* Hardlinks. */
3791 if ((bkc_flags & BKC_BREAKHARDLINK)
3792 && st_old.st_nlink > 1
3793 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3794 backup_copy = FALSE;
3795 }
3796#endif
3797
3798#endif
3799
3800 /* make sure we have a valid backup extension to use */
3801 if (*p_bex == NUL)
3802 {
3803#ifdef RISCOS
3804 backup_ext = (char_u *)"/bak";
3805#else
3806 backup_ext = (char_u *)".bak";
3807#endif
3808 }
3809 else
3810 backup_ext = p_bex;
3811
3812 if (backup_copy
3813 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3814 {
3815 int bfd;
3816 char_u *copybuf, *wp;
3817 int some_error = FALSE;
3818 struct stat st_new;
3819 char_u *dirp;
3820 char_u *rootname;
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003821#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003822 int did_set_shortname;
3823#endif
3824
3825 copybuf = alloc(BUFSIZE + 1);
3826 if (copybuf == NULL)
3827 {
3828 some_error = TRUE; /* out of memory */
3829 goto nobackup;
3830 }
3831
3832 /*
3833 * Try to make the backup in each directory in the 'bdir' option.
3834 *
3835 * Unix semantics has it, that we may have a writable file,
3836 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3837 * - the directory is not writable,
3838 * - the file may be a symbolic link,
3839 * - the file may belong to another user/group, etc.
3840 *
3841 * For these reasons, the existing writable file must be truncated
3842 * and reused. Creation of a backup COPY will be attempted.
3843 */
3844 dirp = p_bdir;
3845 while (*dirp)
3846 {
3847#ifdef UNIX
3848 st_new.st_ino = 0;
3849 st_new.st_dev = 0;
3850 st_new.st_gid = 0;
3851#endif
3852
3853 /*
3854 * Isolate one directory name, using an entry in 'bdir'.
3855 */
3856 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
3857 rootname = get_file_in_dir(fname, copybuf);
3858 if (rootname == NULL)
3859 {
3860 some_error = TRUE; /* out of memory */
3861 goto nobackup;
3862 }
3863
Bram Moolenaard857f0e2005-06-21 22:37:39 +00003864#if defined(UNIX) && !defined(SHORT_FNAME)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003865 did_set_shortname = FALSE;
3866#endif
3867
3868 /*
3869 * May try twice if 'shortname' not set.
3870 */
3871 for (;;)
3872 {
3873 /*
3874 * Make backup file name.
3875 */
3876 backup = buf_modname(
3877#ifdef SHORT_FNAME
3878 TRUE,
3879#else
3880 (buf->b_p_sn || buf->b_shortname),
3881#endif
3882 rootname, backup_ext, FALSE);
3883 if (backup == NULL)
3884 {
3885 vim_free(rootname);
3886 some_error = TRUE; /* out of memory */
3887 goto nobackup;
3888 }
3889
3890 /*
3891 * Check if backup file already exists.
3892 */
3893 if (mch_stat((char *)backup, &st_new) >= 0)
3894 {
3895#ifdef UNIX
3896 /*
3897 * Check if backup file is same as original file.
3898 * May happen when modname() gave the same file back.
3899 * E.g. silly link, or file name-length reached.
3900 * If we don't check here, we either ruin the file
3901 * when copying or erase it after writing. jw.
3902 */
3903 if (st_new.st_dev == st_old.st_dev
3904 && st_new.st_ino == st_old.st_ino)
3905 {
3906 vim_free(backup);
3907 backup = NULL; /* no backup file to delete */
3908# ifndef SHORT_FNAME
3909 /*
3910 * may try again with 'shortname' set
3911 */
3912 if (!(buf->b_shortname || buf->b_p_sn))
3913 {
3914 buf->b_shortname = TRUE;
3915 did_set_shortname = TRUE;
3916 continue;
3917 }
3918 /* setting shortname didn't help */
3919 if (did_set_shortname)
3920 buf->b_shortname = FALSE;
3921# endif
3922 break;
3923 }
3924#endif
3925
3926 /*
3927 * If we are not going to keep the backup file, don't
3928 * delete an existing one, try to use another name.
3929 * Change one character, just before the extension.
3930 */
3931 if (!p_bk)
3932 {
3933 wp = backup + STRLEN(backup) - 1
3934 - STRLEN(backup_ext);
3935 if (wp < backup) /* empty file name ??? */
3936 wp = backup;
3937 *wp = 'z';
3938 while (*wp > 'a'
3939 && mch_stat((char *)backup, &st_new) >= 0)
3940 --*wp;
3941 /* They all exist??? Must be something wrong. */
3942 if (*wp == 'a')
3943 {
3944 vim_free(backup);
3945 backup = NULL;
3946 }
3947 }
3948 }
3949 break;
3950 }
3951 vim_free(rootname);
3952
3953 /*
3954 * Try to create the backup file
3955 */
3956 if (backup != NULL)
3957 {
3958 /* remove old backup, if present */
3959 mch_remove(backup);
3960 /* Open with O_EXCL to avoid the file being created while
3961 * we were sleeping (symlink hacker attack?) */
3962 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003963 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3964 perm & 0777);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965 if (bfd < 0)
3966 {
3967 vim_free(backup);
3968 backup = NULL;
3969 }
3970 else
3971 {
3972 /* set file protection same as original file, but
3973 * strip s-bit */
3974 (void)mch_setperm(backup, perm & 0777);
3975
3976#ifdef UNIX
3977 /*
3978 * Try to set the group of the backup same as the
3979 * original file. If this fails, set the protection
3980 * bits for the group same as the protection bits for
3981 * others.
3982 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003983 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003984# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003985 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003986# endif
3987 )
3988 mch_setperm(backup,
3989 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003990# ifdef HAVE_SELINUX
3991 mch_copy_sec(fname, backup);
3992# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003993#endif
3994
3995 /*
3996 * copy the file.
3997 */
3998 write_info.bw_fd = bfd;
3999 write_info.bw_buf = copybuf;
4000#ifdef HAS_BW_FLAGS
4001 write_info.bw_flags = FIO_NOCONVERT;
4002#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004003 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004004 BUFSIZE)) > 0)
4005 {
4006 if (buf_write_bytes(&write_info) == FAIL)
4007 {
4008 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
4009 break;
4010 }
4011 ui_breakcheck();
4012 if (got_int)
4013 {
4014 errmsg = (char_u *)_(e_interr);
4015 break;
4016 }
4017 }
4018
4019 if (close(bfd) < 0 && errmsg == NULL)
4020 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
4021 if (write_info.bw_len < 0)
4022 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
4023#ifdef UNIX
4024 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
4025#endif
4026#ifdef HAVE_ACL
4027 mch_set_acl(backup, acl);
4028#endif
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004029#ifdef HAVE_SELINUX
4030 mch_copy_sec(fname, backup);
4031#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004032 break;
4033 }
4034 }
4035 }
4036 nobackup:
4037 close(fd); /* ignore errors for closing read file */
4038 vim_free(copybuf);
4039
4040 if (backup == NULL && errmsg == NULL)
4041 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
4042 /* ignore errors when forceit is TRUE */
4043 if ((some_error || errmsg != NULL) && !forceit)
4044 {
4045 retval = FAIL;
4046 goto fail;
4047 }
4048 errmsg = NULL;
4049 }
4050 else
4051 {
4052 char_u *dirp;
4053 char_u *p;
4054 char_u *rootname;
4055
4056 /*
4057 * Make a backup by renaming the original file.
4058 */
4059 /*
4060 * If 'cpoptions' includes the "W" flag, we don't want to
4061 * overwrite a read-only file. But rename may be possible
4062 * anyway, thus we need an extra check here.
4063 */
4064 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
4065 {
4066 errnum = (char_u *)"E504: ";
4067 errmsg = (char_u *)_(err_readonly);
4068 goto fail;
4069 }
4070
4071 /*
4072 *
4073 * Form the backup file name - change path/fo.o.h to
4074 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4075 * that works is used.
4076 */
4077 dirp = p_bdir;
4078 while (*dirp)
4079 {
4080 /*
4081 * Isolate one directory name and make the backup file name.
4082 */
4083 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
4084 rootname = get_file_in_dir(fname, IObuff);
4085 if (rootname == NULL)
4086 backup = NULL;
4087 else
4088 {
4089 backup = buf_modname(
4090#ifdef SHORT_FNAME
4091 TRUE,
4092#else
4093 (buf->b_p_sn || buf->b_shortname),
4094#endif
4095 rootname, backup_ext, FALSE);
4096 vim_free(rootname);
4097 }
4098
4099 if (backup != NULL)
4100 {
4101 /*
4102 * If we are not going to keep the backup file, don't
4103 * delete an existing one, try to use another name.
4104 * Change one character, just before the extension.
4105 */
4106 if (!p_bk && mch_getperm(backup) >= 0)
4107 {
4108 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4109 if (p < backup) /* empty file name ??? */
4110 p = backup;
4111 *p = 'z';
4112 while (*p > 'a' && mch_getperm(backup) >= 0)
4113 --*p;
4114 /* They all exist??? Must be something wrong! */
4115 if (*p == 'a')
4116 {
4117 vim_free(backup);
4118 backup = NULL;
4119 }
4120 }
4121 }
4122 if (backup != NULL)
4123 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004125 * Delete any existing backup and move the current version
4126 * to the backup. For safety, we don't remove the backup
4127 * until the write has finished successfully. And if the
4128 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004129 */
4130 /*
4131 * If the renaming of the original file to the backup file
4132 * works, quit here.
4133 */
4134 if (vim_rename(fname, backup) == 0)
4135 break;
4136
4137 vim_free(backup); /* don't do the rename below */
4138 backup = NULL;
4139 }
4140 }
4141 if (backup == NULL && !forceit)
4142 {
4143 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4144 goto fail;
4145 }
4146 }
4147 }
4148
4149#if defined(UNIX) && !defined(ARCHIE)
4150 /* When using ":w!" and the file was read-only: make it writable */
4151 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4152 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4153 {
4154 perm |= 0200;
4155 (void)mch_setperm(fname, perm);
4156 made_writable = TRUE;
4157 }
4158#endif
4159
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004160 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004161 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4162 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004163 {
4164 buf->b_p_ro = FALSE;
4165#ifdef FEAT_TITLE
4166 need_maketitle = TRUE; /* set window title later */
4167#endif
4168#ifdef FEAT_WINDOWS
4169 status_redraw_all(); /* redraw status lines later */
4170#endif
4171 }
4172
4173 if (end > buf->b_ml.ml_line_count)
4174 end = buf->b_ml.ml_line_count;
4175 if (buf->b_ml.ml_flags & ML_EMPTY)
4176 start = end + 1;
4177
4178 /*
4179 * If the original file is being overwritten, there is a small chance that
4180 * we crash in the middle of writing. Therefore the file is preserved now.
4181 * This makes all block numbers positive so that recovery does not need
4182 * the original file.
4183 * Don't do this if there is a backup file and we are exiting.
4184 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004185 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186 && !(exiting && backup != NULL))
4187 {
4188 ml_preserve(buf, FALSE);
4189 if (got_int)
4190 {
4191 errmsg = (char_u *)_(e_interr);
4192 goto restore_backup;
4193 }
4194 }
4195
4196#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
4197 /*
4198 * Before risking to lose the original file verify if there's
4199 * a resource fork to preserve, and if cannot be done warn
4200 * the users. This happens when overwriting without backups.
4201 */
4202 if (backup == NULL && overwriting && !append)
4203 if (mch_has_resource_fork(fname))
4204 {
4205 errmsg = (char_u *)_("E460: The resource fork would be lost (add ! to override)");
4206 goto restore_backup;
4207 }
4208#endif
4209
4210#ifdef VMS
4211 vms_remove_version(fname); /* remove version */
4212#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004213 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004214 * multi-byte conversion. */
4215 wfname = fname;
4216
4217#ifdef FEAT_MBYTE
4218 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4219 if (eap != NULL && eap->force_enc != 0)
4220 {
4221 fenc = eap->cmd + eap->force_enc;
4222 fenc = enc_canonize(fenc);
4223 fenc_tofree = fenc;
4224 }
4225 else
4226 fenc = buf->b_p_fenc;
4227
4228 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004229 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004230 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004231 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004232
4233 /*
4234 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4235 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4236 * Prepare the flags for it and allocate bw_conv_buf when needed.
4237 */
4238 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4239 {
4240 wb_flags = get_fio_flags(fenc);
4241 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4242 {
4243 /* Need to allocate a buffer to translate into. */
4244 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4245 write_info.bw_conv_buflen = bufsize * 2;
4246 else /* FIO_UCS4 */
4247 write_info.bw_conv_buflen = bufsize * 4;
4248 write_info.bw_conv_buf
4249 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4250 if (write_info.bw_conv_buf == NULL)
4251 end = 0;
4252 }
4253 }
4254
4255# ifdef WIN3264
4256 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4257 {
4258 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4259 write_info.bw_conv_buflen = bufsize * 4;
4260 write_info.bw_conv_buf
4261 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4262 if (write_info.bw_conv_buf == NULL)
4263 end = 0;
4264 }
4265# endif
4266
4267# ifdef MACOS_X
4268 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4269 {
4270 write_info.bw_conv_buflen = bufsize * 3;
4271 write_info.bw_conv_buf
4272 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4273 if (write_info.bw_conv_buf == NULL)
4274 end = 0;
4275 }
4276# endif
4277
4278# if defined(FEAT_EVAL) || defined(USE_ICONV)
4279 if (converted && wb_flags == 0)
4280 {
4281# ifdef USE_ICONV
4282 /*
4283 * Use iconv() conversion when conversion is needed and it's not done
4284 * internally.
4285 */
4286 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4287 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4288 if (write_info.bw_iconv_fd != (iconv_t)-1)
4289 {
4290 /* We're going to use iconv(), allocate a buffer to convert in. */
4291 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
4292 write_info.bw_conv_buf
4293 = lalloc((long_u)write_info.bw_conv_buflen, TRUE);
4294 if (write_info.bw_conv_buf == NULL)
4295 end = 0;
4296 write_info.bw_first = TRUE;
4297 }
4298# ifdef FEAT_EVAL
4299 else
4300# endif
4301# endif
4302
4303# ifdef FEAT_EVAL
4304 /*
4305 * When the file needs to be converted with 'charconvert' after
4306 * writing, write to a temp file instead and let the conversion
4307 * overwrite the original file.
4308 */
4309 if (*p_ccv != NUL)
4310 {
4311 wfname = vim_tempname('w');
4312 if (wfname == NULL) /* Can't write without a tempfile! */
4313 {
4314 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4315 goto restore_backup;
4316 }
4317 }
4318# endif
4319 }
4320# endif
4321 if (converted && wb_flags == 0
4322# ifdef USE_ICONV
4323 && write_info.bw_iconv_fd == (iconv_t)-1
4324# endif
4325# ifdef FEAT_EVAL
4326 && wfname == fname
4327# endif
4328 )
4329 {
4330 if (!forceit)
4331 {
4332 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4333 goto restore_backup;
4334 }
4335 notconverted = TRUE;
4336 }
4337#endif
4338
4339 /*
4340 * Open the file "wfname" for writing.
4341 * We may try to open the file twice: If we can't write to the
4342 * file and forceit is TRUE we delete the existing file and try to create
4343 * a new one. If this still fails we may have lost the original file!
4344 * (this may happen when the user reached his quotum for number of files).
4345 * Appending will fail if the file does not exist and forceit is FALSE.
4346 */
4347 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4348 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
4349 : (O_CREAT | O_TRUNC))
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004350 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004351 {
4352 /*
4353 * A forced write will try to create a new file if the old one is
4354 * still readonly. This may also happen when the directory is
4355 * read-only. In that case the mch_remove() will fail.
4356 */
4357 if (errmsg == NULL)
4358 {
4359#ifdef UNIX
4360 struct stat st;
4361
4362 /* Don't delete the file when it's a hard or symbolic link. */
4363 if ((!newfile && st_old.st_nlink > 1)
4364 || (mch_lstat((char *)fname, &st) == 0
4365 && (st.st_dev != st_old.st_dev
4366 || st.st_ino != st_old.st_ino)))
4367 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4368 else
4369#endif
4370 {
4371 errmsg = (char_u *)_("E212: Can't open file for writing");
4372 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4373 && perm >= 0)
4374 {
4375#ifdef UNIX
4376 /* we write to the file, thus it should be marked
4377 writable after all */
4378 if (!(perm & 0200))
4379 made_writable = TRUE;
4380 perm |= 0200;
4381 if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
4382 perm &= 0777;
4383#endif
4384 if (!append) /* don't remove when appending */
4385 mch_remove(wfname);
4386 continue;
4387 }
4388 }
4389 }
4390
4391restore_backup:
4392 {
4393 struct stat st;
4394
4395 /*
4396 * If we failed to open the file, we don't need a backup. Throw it
4397 * away. If we moved or removed the original file try to put the
4398 * backup in its place.
4399 */
4400 if (backup != NULL && wfname == fname)
4401 {
4402 if (backup_copy)
4403 {
4404 /*
4405 * There is a small chance that we removed the original,
4406 * try to move the copy in its place.
4407 * This may not work if the vim_rename() fails.
4408 * In that case we leave the copy around.
4409 */
4410 /* If file does not exist, put the copy in its place */
4411 if (mch_stat((char *)fname, &st) < 0)
4412 vim_rename(backup, fname);
4413 /* if original file does exist throw away the copy */
4414 if (mch_stat((char *)fname, &st) >= 0)
4415 mch_remove(backup);
4416 }
4417 else
4418 {
4419 /* try to put the original file back */
4420 vim_rename(backup, fname);
4421 }
4422 }
4423
4424 /* if original file no longer exists give an extra warning */
4425 if (!newfile && mch_stat((char *)fname, &st) < 0)
4426 end = 0;
4427 }
4428
4429#ifdef FEAT_MBYTE
4430 if (wfname != fname)
4431 vim_free(wfname);
4432#endif
4433 goto fail;
4434 }
4435 errmsg = NULL;
4436
4437#if defined(MACOS_CLASSIC) || defined(WIN3264)
4438 /* TODO: Is it need for MACOS_X? (Dany) */
4439 /*
4440 * On macintosh copy the original files attributes (i.e. the backup)
Bram Moolenaar7263a772007-05-10 17:35:54 +00004441 * This is done in order to preserve the resource fork and the
4442 * Finder attribute (label, comments, custom icons, file creator)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004443 */
4444 if (backup != NULL && overwriting && !append)
4445 {
4446 if (backup_copy)
4447 (void)mch_copy_file_attribute(wfname, backup);
4448 else
4449 (void)mch_copy_file_attribute(backup, wfname);
4450 }
4451
4452 if (!overwriting && !append)
4453 {
4454 if (buf->b_ffname != NULL)
4455 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
Bram Moolenaar7263a772007-05-10 17:35:54 +00004456 /* Should copy resource fork */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457 }
4458#endif
4459
4460 write_info.bw_fd = fd;
4461
4462#ifdef FEAT_CRYPT
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004463 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004464 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004465 char_u *header;
4466 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004467
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004468 header = prepare_crypt_write(buf, &header_len);
4469 if (header == NULL)
4470 end = 0;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004471 else
4472 {
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02004473 /* Write magic number, so that Vim knows that this file is
4474 * encrypted when reading it again. This also undergoes utf-8 to
4475 * ucs-2/4 conversion when needed. */
4476 write_info.bw_buf = header;
4477 write_info.bw_len = header_len;
4478 write_info.bw_flags = FIO_NOCONVERT;
4479 if (buf_write_bytes(&write_info) == FAIL)
4480 end = 0;
4481 wb_flags |= FIO_ENCRYPTED;
4482 vim_free(header);
Bram Moolenaar40e6a712010-05-16 22:32:54 +02004483 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004484 }
4485#endif
4486
4487 write_info.bw_buf = buffer;
4488 nchars = 0;
4489
4490 /* use "++bin", "++nobin" or 'binary' */
4491 if (eap != NULL && eap->force_bin != 0)
4492 write_bin = (eap->force_bin == FORCE_BIN);
4493 else
4494 write_bin = buf->b_p_bin;
4495
4496#ifdef FEAT_MBYTE
4497 /*
4498 * The BOM is written just after the encryption magic number.
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004499 * Skip it when appending and the file already existed, the BOM only makes
4500 * sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004501 */
Bram Moolenaarc0197e22004-09-13 20:26:32 +00004502 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004503 {
4504 write_info.bw_len = make_bom(buffer, fenc);
4505 if (write_info.bw_len > 0)
4506 {
4507 /* don't convert, do encryption */
4508 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4509 if (buf_write_bytes(&write_info) == FAIL)
4510 end = 0;
4511 else
4512 nchars += write_info.bw_len;
4513 }
4514 }
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004515 write_info.bw_start_lnum = start;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004516#endif
4517
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004518#ifdef FEAT_PERSISTENT_UNDO
4519 write_undo_file = (buf->b_p_udf && overwriting && !append
4520 && !filtering && reset_changed);
4521 if (write_undo_file)
4522 /* Prepare for computing the hash value of the text. */
4523 sha256_start(&sha_ctx);
4524#endif
4525
Bram Moolenaar071d4272004-06-13 20:20:40 +00004526 write_info.bw_len = bufsize;
4527#ifdef HAS_BW_FLAGS
4528 write_info.bw_flags = wb_flags;
4529#endif
4530 fileformat = get_fileformat_force(buf, eap);
4531 s = buffer;
4532 len = 0;
4533 for (lnum = start; lnum <= end; ++lnum)
4534 {
4535 /*
4536 * The next while loop is done once for each character written.
4537 * Keep it fast!
4538 */
4539 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004540#ifdef FEAT_PERSISTENT_UNDO
4541 if (write_undo_file)
Bram Moolenaar442b4222010-05-24 21:34:22 +02004542 sha256_update(&sha_ctx, ptr + 1, (UINT32_T)(STRLEN(ptr + 1) + 1));
Bram Moolenaar55debbe2010-05-23 23:34:36 +02004543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004544 while ((c = *++ptr) != NUL)
4545 {
4546 if (c == NL)
4547 *s = NUL; /* replace newlines with NULs */
4548 else if (c == CAR && fileformat == EOL_MAC)
4549 *s = NL; /* Mac: replace CRs with NLs */
4550 else
4551 *s = c;
4552 ++s;
4553 if (++len != bufsize)
4554 continue;
4555 if (buf_write_bytes(&write_info) == FAIL)
4556 {
4557 end = 0; /* write error: break loop */
4558 break;
4559 }
4560 nchars += bufsize;
4561 s = buffer;
4562 len = 0;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004563#ifdef FEAT_MBYTE
4564 write_info.bw_start_lnum = lnum;
4565#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004566 }
4567 /* write failed or last line has no EOL: stop here */
4568 if (end == 0
4569 || (lnum == end
4570 && write_bin
4571 && (lnum == write_no_eol_lnum
4572 || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
4573 {
4574 ++lnum; /* written the line, count it */
4575 no_eol = TRUE;
4576 break;
4577 }
4578 if (fileformat == EOL_UNIX)
4579 *s++ = NL;
4580 else
4581 {
4582 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4583 if (fileformat == EOL_DOS) /* write CR-NL */
4584 {
4585 if (++len == bufsize)
4586 {
4587 if (buf_write_bytes(&write_info) == FAIL)
4588 {
4589 end = 0; /* write error: break loop */
4590 break;
4591 }
4592 nchars += bufsize;
4593 s = buffer;
4594 len = 0;
4595 }
4596 *s++ = NL;
4597 }
4598 }
4599 if (++len == bufsize && end)
4600 {
4601 if (buf_write_bytes(&write_info) == FAIL)
4602 {
4603 end = 0; /* write error: break loop */
4604 break;
4605 }
4606 nchars += bufsize;
4607 s = buffer;
4608 len = 0;
4609
4610 ui_breakcheck();
4611 if (got_int)
4612 {
4613 end = 0; /* Interrupted, break loop */
4614 break;
4615 }
4616 }
4617#ifdef VMS
4618 /*
4619 * On VMS there is a problem: newlines get added when writing blocks
4620 * at a time. Fix it by writing a line at a time.
4621 * This is much slower!
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004622 * Explanation: VAX/DECC RTL insists that records in some RMS
4623 * structures end with a newline (carriage return) character, and if
4624 * they don't it adds one.
4625 * With other RMS structures it works perfect without this fix.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626 */
Bram Moolenaarb52e2602007-10-29 21:38:54 +00004627 if (buf->b_fab_rfm == FAB$C_VFC
4628 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004629 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004630 int b2write;
4631
4632 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4633 ? MIN(4096, bufsize)
4634 : MIN(buf->b_fab_mrs, bufsize));
4635
4636 b2write = len;
4637 while (b2write > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004638 {
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004639 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4640 if (buf_write_bytes(&write_info) == FAIL)
4641 {
4642 end = 0;
4643 break;
4644 }
4645 b2write -= MIN(b2write, buf->b_fab_mrs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004646 }
4647 write_info.bw_len = bufsize;
4648 nchars += len;
4649 s = buffer;
4650 len = 0;
4651 }
4652#endif
4653 }
4654 if (len > 0 && end > 0)
4655 {
4656 write_info.bw_len = len;
4657 if (buf_write_bytes(&write_info) == FAIL)
4658 end = 0; /* write error */
4659 nchars += len;
4660 }
4661
4662#if defined(UNIX) && defined(HAVE_FSYNC)
4663 /* On many journalling file systems there is a bug that causes both the
4664 * original and the backup file to be lost when halting the system right
4665 * after writing the file. That's because only the meta-data is
4666 * journalled. Syncing the file slows down the system, but assures it has
Bram Moolenaarf4b8e572004-06-24 15:53:16 +00004667 * been written to disk and we don't lose it.
4668 * For a device do try the fsync() but don't complain if it does not work
Bram Moolenaar293ee4d2004-12-09 21:34:53 +00004669 * (could be a pipe).
4670 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops. */
4671 if (p_fs && fsync(fd) != 0 && !device)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004672 {
4673 errmsg = (char_u *)_("E667: Fsync failed");
4674 end = 0;
4675 }
4676#endif
4677
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004678#ifdef HAVE_SELINUX
4679 /* Probably need to set the security context. */
4680 if (!backup_copy)
4681 mch_copy_sec(backup, wfname);
4682#endif
4683
Bram Moolenaara5792f52005-11-23 21:25:05 +00004684#ifdef UNIX
4685 /* When creating a new file, set its owner/group to that of the original
4686 * file. Get the new device and inode number. */
4687 if (backup != NULL && !backup_copy)
4688 {
4689# ifdef HAVE_FCHOWN
4690 struct stat st;
4691
4692 /* don't change the owner when it's already OK, some systems remove
4693 * permission or ACL stuff */
4694 if (mch_stat((char *)wfname, &st) < 0
4695 || st.st_uid != st_old.st_uid
4696 || st.st_gid != st_old.st_gid)
4697 {
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00004698 ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004699 if (perm >= 0) /* set permission again, may have changed */
4700 (void)mch_setperm(wfname, perm);
4701 }
4702# endif
4703 buf_setino(buf);
4704 }
Bram Moolenaarf1726cc2009-05-13 18:48:16 +00004705 else if (!buf->b_dev_valid)
Bram Moolenaar8fa04452005-12-23 22:13:51 +00004706 /* Set the inode when creating a new file. */
4707 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004708#endif
4709
Bram Moolenaar071d4272004-06-13 20:20:40 +00004710 if (close(fd) != 0)
4711 {
4712 errmsg = (char_u *)_("E512: Close failed");
4713 end = 0;
4714 }
4715
4716#ifdef UNIX
4717 if (made_writable)
4718 perm &= ~0200; /* reset 'w' bit for security reasons */
4719#endif
4720 if (perm >= 0) /* set perm. of new file same as old file */
4721 (void)mch_setperm(wfname, perm);
4722#ifdef RISCOS
4723 if (!append && !filtering)
4724 /* Set the filetype after writing the file. */
4725 mch_set_filetype(wfname, buf->b_p_oft);
4726#endif
4727#ifdef HAVE_ACL
4728 /* Probably need to set the ACL before changing the user (can't set the
4729 * ACL on a file the user doesn't own). */
4730 if (!backup_copy)
4731 mch_set_acl(wfname, acl);
4732#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004733#ifdef FEAT_CRYPT
4734 if (wb_flags & FIO_ENCRYPTED)
4735 crypt_pop_state();
4736#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737
Bram Moolenaar071d4272004-06-13 20:20:40 +00004738
4739#if defined(FEAT_MBYTE) && defined(FEAT_EVAL)
4740 if (wfname != fname)
4741 {
4742 /*
4743 * The file was written to a temp file, now it needs to be converted
4744 * with 'charconvert' to (overwrite) the output file.
4745 */
4746 if (end != 0)
4747 {
4748 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc,
4749 wfname, fname) == FAIL)
4750 {
4751 write_info.bw_conv_error = TRUE;
4752 end = 0;
4753 }
4754 }
4755 mch_remove(wfname);
4756 vim_free(wfname);
4757 }
4758#endif
4759
4760 if (end == 0)
4761 {
4762 if (errmsg == NULL)
4763 {
4764#ifdef FEAT_MBYTE
4765 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004766 {
4767 if (write_info.bw_conv_error_lnum == 0)
4768 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4769 else
4770 {
4771 errmsg_allocated = TRUE;
4772 errmsg = alloc(300);
4773 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4774 (long)write_info.bw_conv_error_lnum);
4775 }
4776 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004777 else
4778#endif
4779 if (got_int)
4780 errmsg = (char_u *)_(e_interr);
4781 else
4782 errmsg = (char_u *)_("E514: write error (file system full?)");
4783 }
4784
4785 /*
4786 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004787 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004788 * original file when trying to make a backup when writing the file a
4789 * second time.
4790 * When "backup_copy" is set we need to copy the backup over the new
4791 * file. Otherwise rename the backup file.
4792 * If this is OK, don't give the extra warning message.
4793 */
4794 if (backup != NULL)
4795 {
4796 if (backup_copy)
4797 {
4798 /* This may take a while, if we were interrupted let the user
4799 * know we got the message. */
4800 if (got_int)
4801 {
4802 MSG(_(e_interr));
4803 out_flush();
4804 }
4805 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4806 {
4807 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004808 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4809 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004810 {
4811 /* copy the file. */
4812 write_info.bw_buf = smallbuf;
4813#ifdef HAS_BW_FLAGS
4814 write_info.bw_flags = FIO_NOCONVERT;
4815#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004816 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004817 SMBUFSIZE)) > 0)
4818 if (buf_write_bytes(&write_info) == FAIL)
4819 break;
4820
4821 if (close(write_info.bw_fd) >= 0
4822 && write_info.bw_len == 0)
4823 end = 1; /* success */
4824 }
4825 close(fd); /* ignore errors for closing read file */
4826 }
4827 }
4828 else
4829 {
4830 if (vim_rename(backup, fname) == 0)
4831 end = 1;
4832 }
4833 }
4834 goto fail;
4835 }
4836
4837 lnum -= start; /* compute number of written lines */
4838 --no_wait_return; /* may wait for return now */
4839
4840#if !(defined(UNIX) || defined(VMS))
4841 fname = sfname; /* use shortname now, for the messages */
4842#endif
4843 if (!filtering)
4844 {
4845 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4846 c = FALSE;
4847#ifdef FEAT_MBYTE
4848 if (write_info.bw_conv_error)
4849 {
4850 STRCAT(IObuff, _(" CONVERSION ERROR"));
4851 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004852 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004853 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004854 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004855 }
4856 else if (notconverted)
4857 {
4858 STRCAT(IObuff, _("[NOT converted]"));
4859 c = TRUE;
4860 }
4861 else if (converted)
4862 {
4863 STRCAT(IObuff, _("[converted]"));
4864 c = TRUE;
4865 }
4866#endif
4867 if (device)
4868 {
4869 STRCAT(IObuff, _("[Device]"));
4870 c = TRUE;
4871 }
4872 else if (newfile)
4873 {
4874 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4875 c = TRUE;
4876 }
4877 if (no_eol)
4878 {
4879 msg_add_eol();
4880 c = TRUE;
4881 }
4882 /* may add [unix/dos/mac] */
4883 if (msg_add_fileformat(fileformat))
4884 c = TRUE;
4885#ifdef FEAT_CRYPT
4886 if (wb_flags & FIO_ENCRYPTED)
4887 {
4888 STRCAT(IObuff, _("[crypted]"));
4889 c = TRUE;
4890 }
4891#endif
4892 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4893 if (!shortmess(SHM_WRITE))
4894 {
4895 if (append)
4896 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4897 else
4898 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4899 }
4900
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00004901 set_keep_msg(msg_trunc_attr(IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004902 }
4903
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004904 /* When written everything correctly: reset 'modified'. Unless not
4905 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004906 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004907#ifdef FEAT_MBYTE
4908 && !write_info.bw_conv_error
4909#endif
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004910 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)
4911 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00004912 {
4913 unchanged(buf, TRUE);
4914 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004915 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916 }
4917
4918 /*
4919 * If written to the current file, update the timestamp of the swap file
4920 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4921 */
4922 if (overwriting)
4923 {
4924 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004925 if (append)
4926 buf->b_flags &= ~BF_NEW;
4927 else
4928 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004929 }
4930
4931 /*
4932 * If we kept a backup until now, and we are in patch mode, then we make
4933 * the backup file our 'original' file.
4934 */
4935 if (*p_pm && dobackup)
4936 {
4937 char *org = (char *)buf_modname(
4938#ifdef SHORT_FNAME
4939 TRUE,
4940#else
4941 (buf->b_p_sn || buf->b_shortname),
4942#endif
4943 fname, p_pm, FALSE);
4944
4945 if (backup != NULL)
4946 {
4947 struct stat st;
4948
4949 /*
4950 * If the original file does not exist yet
4951 * the current backup file becomes the original file
4952 */
4953 if (org == NULL)
4954 EMSG(_("E205: Patchmode: can't save original file"));
4955 else if (mch_stat(org, &st) < 0)
4956 {
4957 vim_rename(backup, (char_u *)org);
4958 vim_free(backup); /* don't delete the file */
4959 backup = NULL;
4960#ifdef UNIX
4961 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4962#endif
4963 }
4964 }
4965 /*
4966 * If there is no backup file, remember that a (new) file was
4967 * created.
4968 */
4969 else
4970 {
4971 int empty_fd;
4972
4973 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004974 || (empty_fd = mch_open(org,
4975 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004976 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004977 EMSG(_("E206: patchmode: can't touch empty original file"));
4978 else
4979 close(empty_fd);
4980 }
4981 if (org != NULL)
4982 {
4983 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4984 vim_free(org);
4985 }
4986 }
4987
4988 /*
4989 * Remove the backup unless 'backup' option is set
4990 */
4991 if (!p_bk && backup != NULL && mch_remove(backup) != 0)
4992 EMSG(_("E207: Can't delete backup file"));
4993
4994#ifdef FEAT_SUN_WORKSHOP
4995 if (usingSunWorkShop)
4996 workshop_file_saved((char *) ffname);
4997#endif
4998
4999 goto nofail;
5000
5001 /*
5002 * Finish up. We get here either after failure or success.
5003 */
5004fail:
5005 --no_wait_return; /* may wait for return now */
5006nofail:
5007
5008 /* Done saving, we accept changed buffer warnings again */
5009 buf->b_saving = FALSE;
5010
5011 vim_free(backup);
5012 if (buffer != smallbuf)
5013 vim_free(buffer);
5014#ifdef FEAT_MBYTE
5015 vim_free(fenc_tofree);
5016 vim_free(write_info.bw_conv_buf);
5017# ifdef USE_ICONV
5018 if (write_info.bw_iconv_fd != (iconv_t)-1)
5019 {
5020 iconv_close(write_info.bw_iconv_fd);
5021 write_info.bw_iconv_fd = (iconv_t)-1;
5022 }
5023# endif
5024#endif
5025#ifdef HAVE_ACL
5026 mch_free_acl(acl);
5027#endif
5028
5029 if (errmsg != NULL)
5030 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005031 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005032
5033 attr = hl_attr(HLF_E); /* set highlight for error messages */
5034 msg_add_fname(buf,
5035#ifndef UNIX
5036 sfname
5037#else
5038 fname
5039#endif
5040 ); /* put file name in IObuff with quotes */
5041 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5042 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5043 /* If the error message has the form "is ...", put the error number in
5044 * front of the file name. */
5045 if (errnum != NULL)
5046 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005047 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005048 mch_memmove(IObuff, errnum, (size_t)numlen);
5049 }
5050 STRCAT(IObuff, errmsg);
5051 emsg(IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005052 if (errmsg_allocated)
5053 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005054
5055 retval = FAIL;
5056 if (end == 0)
5057 {
5058 MSG_PUTS_ATTR(_("\nWARNING: Original file may be lost or damaged\n"),
5059 attr | MSG_HIST);
5060 MSG_PUTS_ATTR(_("don't quit the editor until the file is successfully written!"),
5061 attr | MSG_HIST);
5062
5063 /* Update the timestamp to avoid an "overwrite changed file"
5064 * prompt when writing again. */
5065 if (mch_stat((char *)fname, &st_old) >= 0)
5066 {
5067 buf_store_time(buf, &st_old, fname);
5068 buf->b_mtime_read = buf->b_mtime;
5069 }
5070 }
5071 }
5072 msg_scroll = msg_save;
5073
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005074#ifdef FEAT_PERSISTENT_UNDO
5075 /*
5076 * When writing the whole file and 'undofile' is set, also write the undo
5077 * file.
5078 */
5079 if (retval == OK && write_undo_file)
5080 {
5081 char_u hash[UNDO_HASH_SIZE];
5082
5083 sha256_finish(&sha_ctx, hash);
5084 u_write_undo(NULL, FALSE, buf, hash);
5085 }
5086#endif
5087
Bram Moolenaar071d4272004-06-13 20:20:40 +00005088#ifdef FEAT_AUTOCMD
5089#ifdef FEAT_EVAL
5090 if (!should_abort(retval))
5091#else
5092 if (!got_int)
5093#endif
5094 {
5095 aco_save_T aco;
5096
5097 write_no_eol_lnum = 0; /* in case it was set by the previous read */
5098
5099 /*
5100 * Apply POST autocommands.
5101 * Careful: The autocommands may call buf_write() recursively!
5102 */
5103 aucmd_prepbuf(&aco, buf);
5104
5105 if (append)
5106 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5107 FALSE, curbuf, eap);
5108 else if (filtering)
5109 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5110 FALSE, curbuf, eap);
5111 else if (reset_changed && whole)
5112 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5113 FALSE, curbuf, eap);
5114 else
5115 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5116 FALSE, curbuf, eap);
5117
5118 /* restore curwin/curbuf and a few other things */
5119 aucmd_restbuf(&aco);
5120
5121#ifdef FEAT_EVAL
5122 if (aborting()) /* autocmds may abort script processing */
5123 retval = FALSE;
5124#endif
5125 }
5126#endif
5127
5128 got_int |= prev_got_int;
5129
5130#ifdef MACOS_CLASSIC /* TODO: Is it need for MACOS_X? (Dany) */
5131 /* Update machine specific information. */
5132 mch_post_buffer_write(buf);
5133#endif
5134 return retval;
5135}
5136
5137/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005138 * Set the name of the current buffer. Use when the buffer doesn't have a
5139 * name and a ":r" or ":w" command with a file name is used.
5140 */
5141 static int
5142set_rw_fname(fname, sfname)
5143 char_u *fname;
5144 char_u *sfname;
5145{
5146#ifdef FEAT_AUTOCMD
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005147 buf_T *buf = curbuf;
5148
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005149 /* It's like the unnamed buffer is deleted.... */
5150 if (curbuf->b_p_bl)
5151 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5152 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
5153# ifdef FEAT_EVAL
5154 if (aborting()) /* autocmds may abort script processing */
5155 return FAIL;
5156# endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005157 if (curbuf != buf)
5158 {
5159 /* We are in another buffer now, don't do the renaming. */
5160 EMSG(_(e_auchangedbuf));
5161 return FAIL;
5162 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005163#endif
5164
5165 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5166 curbuf->b_flags |= BF_NOTEDITED;
5167
5168#ifdef FEAT_AUTOCMD
5169 /* ....and a new named one is created */
5170 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5171 if (curbuf->b_p_bl)
5172 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5173# ifdef FEAT_EVAL
5174 if (aborting()) /* autocmds may abort script processing */
5175 return FAIL;
5176# endif
5177
5178 /* Do filetype detection now if 'filetype' is empty. */
5179 if (*curbuf->b_p_ft == NUL)
5180 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005181 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar70836c82006-02-20 21:28:49 +00005182 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005183 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005184 }
5185#endif
5186
5187 return OK;
5188}
5189
5190/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191 * Put file name into IObuff with quotes.
5192 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005193 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005194msg_add_fname(buf, fname)
5195 buf_T *buf;
5196 char_u *fname;
5197{
5198 if (fname == NULL)
5199 fname = (char_u *)"-stdin-";
5200 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5201 IObuff[0] = '"';
5202 STRCAT(IObuff, "\" ");
5203}
5204
5205/*
5206 * Append message for text mode to IObuff.
5207 * Return TRUE if something appended.
5208 */
5209 static int
5210msg_add_fileformat(eol_type)
5211 int eol_type;
5212{
5213#ifndef USE_CRNL
5214 if (eol_type == EOL_DOS)
5215 {
5216 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5217 return TRUE;
5218 }
5219#endif
5220#ifndef USE_CR
5221 if (eol_type == EOL_MAC)
5222 {
5223 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5224 return TRUE;
5225 }
5226#endif
5227#if defined(USE_CRNL) || defined(USE_CR)
5228 if (eol_type == EOL_UNIX)
5229 {
5230 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5231 return TRUE;
5232 }
5233#endif
5234 return FALSE;
5235}
5236
5237/*
5238 * Append line and character count to IObuff.
5239 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005240 void
Bram Moolenaar071d4272004-06-13 20:20:40 +00005241msg_add_lines(insert_space, lnum, nchars)
5242 int insert_space;
5243 long lnum;
Bram Moolenaar914703b2010-05-31 21:59:46 +02005244 off_t nchars;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005245{
5246 char_u *p;
5247
5248 p = IObuff + STRLEN(IObuff);
5249
5250 if (insert_space)
5251 *p++ = ' ';
5252 if (shortmess(SHM_LINES))
Bram Moolenaar914703b2010-05-31 21:59:46 +02005253 sprintf((char *)p,
5254#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005255 "%ldL, %lldC", lnum, nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005256#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005257 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5258 "%ldL, %ldC", lnum, (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005259#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005260 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 else
5262 {
5263 if (lnum == 1)
5264 STRCPY(p, _("1 line, "));
5265 else
5266 sprintf((char *)p, _("%ld lines, "), lnum);
5267 p += STRLEN(p);
5268 if (nchars == 1)
5269 STRCPY(p, _("1 character"));
5270 else
Bram Moolenaar914703b2010-05-31 21:59:46 +02005271 sprintf((char *)p,
5272#ifdef LONG_LONG_OFF_T
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005273 _("%lld characters"), nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005274#else
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005275 /* Explicit typecast avoids warning on Mac OS X 10.6 */
5276 _("%ld characters"), (long)nchars
Bram Moolenaar914703b2010-05-31 21:59:46 +02005277#endif
Bram Moolenaarf9b01292010-06-12 06:45:20 +02005278 );
Bram Moolenaar071d4272004-06-13 20:20:40 +00005279 }
5280}
5281
5282/*
5283 * Append message for missing line separator to IObuff.
5284 */
5285 static void
5286msg_add_eol()
5287{
5288 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5289}
5290
5291/*
5292 * Check modification time of file, before writing to it.
5293 * The size isn't checked, because using a tool like "gzip" takes care of
5294 * using the same timestamp but can't set the size.
5295 */
5296 static int
5297check_mtime(buf, st)
5298 buf_T *buf;
5299 struct stat *st;
5300{
5301 if (buf->b_mtime_read != 0
5302 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5303 {
5304 msg_scroll = TRUE; /* don't overwrite messages here */
5305 msg_silent = 0; /* must give this prompt */
5306 /* don't use emsg() here, don't want to flush the buffers */
5307 MSG_ATTR(_("WARNING: The file has been changed since reading it!!!"),
5308 hl_attr(HLF_E));
5309 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5310 TRUE) == 'n')
5311 return FAIL;
5312 msg_scroll = FALSE; /* always overwrite the file message now */
5313 }
5314 return OK;
5315}
5316
5317 static int
5318time_differs(t1, t2)
5319 long t1, t2;
5320{
5321#if defined(__linux__) || defined(MSDOS) || defined(MSWIN)
5322 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5323 * the seconds. Since the roundoff is done when flushing the inode, the
5324 * time may change unexpectedly by one second!!! */
5325 return (t1 - t2 > 1 || t2 - t1 > 1);
5326#else
5327 return (t1 != t2);
5328#endif
5329}
5330
5331/*
5332 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005333 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005334 *
5335 * Return FAIL for failure, OK otherwise.
5336 */
5337 static int
5338buf_write_bytes(ip)
5339 struct bw_info *ip;
5340{
5341 int wlen;
5342 char_u *buf = ip->bw_buf; /* data to write */
5343 int len = ip->bw_len; /* length of data */
5344#ifdef HAS_BW_FLAGS
5345 int flags = ip->bw_flags; /* extra flags */
5346#endif
5347
5348#ifdef FEAT_MBYTE
5349 /*
5350 * Skip conversion when writing the crypt magic number or the BOM.
5351 */
5352 if (!(flags & FIO_NOCONVERT))
5353 {
5354 char_u *p;
5355 unsigned c;
5356 int n;
5357
5358 if (flags & FIO_UTF8)
5359 {
5360 /*
5361 * Convert latin1 in the buffer to UTF-8 in the file.
5362 */
5363 p = ip->bw_conv_buf; /* translate to buffer */
5364 for (wlen = 0; wlen < len; ++wlen)
5365 p += utf_char2bytes(buf[wlen], p);
5366 buf = ip->bw_conv_buf;
5367 len = (int)(p - ip->bw_conv_buf);
5368 }
5369 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5370 {
5371 /*
5372 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5373 * Latin1 chars in the file.
5374 */
5375 if (flags & FIO_LATIN1)
5376 p = buf; /* translate in-place (can only get shorter) */
5377 else
5378 p = ip->bw_conv_buf; /* translate to buffer */
5379 for (wlen = 0; wlen < len; wlen += n)
5380 {
5381 if (wlen == 0 && ip->bw_restlen != 0)
5382 {
5383 int l;
5384
5385 /* Use remainder of previous call. Append the start of
5386 * buf[] to get a full sequence. Might still be too
5387 * short! */
5388 l = CONV_RESTLEN - ip->bw_restlen;
5389 if (l > len)
5390 l = len;
5391 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005392 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005393 if (n > ip->bw_restlen + len)
5394 {
5395 /* We have an incomplete byte sequence at the end to
5396 * be written. We can't convert it without the
5397 * remaining bytes. Keep them for the next call. */
5398 if (ip->bw_restlen + len > CONV_RESTLEN)
5399 return FAIL;
5400 ip->bw_restlen += len;
5401 break;
5402 }
5403 if (n > 1)
5404 c = utf_ptr2char(ip->bw_rest);
5405 else
5406 c = ip->bw_rest[0];
5407 if (n >= ip->bw_restlen)
5408 {
5409 n -= ip->bw_restlen;
5410 ip->bw_restlen = 0;
5411 }
5412 else
5413 {
5414 ip->bw_restlen -= n;
5415 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5416 (size_t)ip->bw_restlen);
5417 n = 0;
5418 }
5419 }
5420 else
5421 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005422 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005423 if (n > len - wlen)
5424 {
5425 /* We have an incomplete byte sequence at the end to
5426 * be written. We can't convert it without the
5427 * remaining bytes. Keep them for the next call. */
5428 if (len - wlen > CONV_RESTLEN)
5429 return FAIL;
5430 ip->bw_restlen = len - wlen;
5431 mch_memmove(ip->bw_rest, buf + wlen,
5432 (size_t)ip->bw_restlen);
5433 break;
5434 }
5435 if (n > 1)
5436 c = utf_ptr2char(buf + wlen);
5437 else
5438 c = buf[wlen];
5439 }
5440
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005441 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5442 {
5443 ip->bw_conv_error = TRUE;
5444 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5445 }
5446 if (c == NL)
5447 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005448 }
5449 if (flags & FIO_LATIN1)
5450 len = (int)(p - buf);
5451 else
5452 {
5453 buf = ip->bw_conv_buf;
5454 len = (int)(p - ip->bw_conv_buf);
5455 }
5456 }
5457
5458# ifdef WIN3264
5459 else if (flags & FIO_CODEPAGE)
5460 {
5461 /*
5462 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5463 * codepage.
5464 */
5465 char_u *from;
5466 size_t fromlen;
5467 char_u *to;
5468 int u8c;
5469 BOOL bad = FALSE;
5470 int needed;
5471
5472 if (ip->bw_restlen > 0)
5473 {
5474 /* Need to concatenate the remainder of the previous call and
5475 * the bytes of the current call. Use the end of the
5476 * conversion buffer for this. */
5477 fromlen = len + ip->bw_restlen;
5478 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5479 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5480 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5481 }
5482 else
5483 {
5484 from = buf;
5485 fromlen = len;
5486 }
5487
5488 to = ip->bw_conv_buf;
5489 if (enc_utf8)
5490 {
5491 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5492 * The buffer has been allocated to be big enough. */
5493 while (fromlen > 0)
5494 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005495 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005496 if (n > (int)fromlen) /* incomplete byte sequence */
5497 break;
5498 u8c = utf_ptr2char(from);
5499 *to++ = (u8c & 0xff);
5500 *to++ = (u8c >> 8);
5501 fromlen -= n;
5502 from += n;
5503 }
5504
5505 /* Copy remainder to ip->bw_rest[] to be used for the next
5506 * call. */
5507 if (fromlen > CONV_RESTLEN)
5508 {
5509 /* weird overlong sequence */
5510 ip->bw_conv_error = TRUE;
5511 return FAIL;
5512 }
5513 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005514 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005515 }
5516 else
5517 {
5518 /* Convert from enc_codepage to UCS-2, to the start of the
5519 * buffer. The buffer has been allocated to be big enough. */
5520 ip->bw_restlen = 0;
5521 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005522 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005523 NULL, 0);
5524 if (needed == 0)
5525 {
5526 /* When conversion fails there may be a trailing byte. */
5527 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005528 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005529 NULL, 0);
5530 if (needed == 0)
5531 {
5532 /* Conversion doesn't work. */
5533 ip->bw_conv_error = TRUE;
5534 return FAIL;
5535 }
5536 /* Save the trailing byte for the next call. */
5537 ip->bw_rest[0] = from[fromlen - 1];
5538 ip->bw_restlen = 1;
5539 }
5540 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005541 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005542 (LPWSTR)to, needed);
5543 if (needed == 0)
5544 {
5545 /* Safety check: Conversion doesn't work. */
5546 ip->bw_conv_error = TRUE;
5547 return FAIL;
5548 }
5549 to += needed * 2;
5550 }
5551
5552 fromlen = to - ip->bw_conv_buf;
5553 buf = to;
5554# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5555 if (FIO_GET_CP(flags) == CP_UTF8)
5556 {
5557 /* Convert from UCS-2 to UTF-8, using the remainder of the
5558 * conversion buffer. Fails when out of space. */
5559 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5560 {
5561 u8c = *from++;
5562 u8c += (*from++ << 8);
5563 to += utf_char2bytes(u8c, to);
5564 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5565 {
5566 ip->bw_conv_error = TRUE;
5567 return FAIL;
5568 }
5569 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005570 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005571 }
5572 else
5573#endif
5574 {
5575 /* Convert from UCS-2 to the codepage, using the remainder of
5576 * the conversion buffer. If the conversion uses the default
5577 * character "0", the data doesn't fit in this encoding, so
5578 * fail. */
5579 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5580 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005581 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5582 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005583 if (bad)
5584 {
5585 ip->bw_conv_error = TRUE;
5586 return FAIL;
5587 }
5588 }
5589 }
5590# endif
5591
Bram Moolenaar56718732006-03-15 22:53:57 +00005592# ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 else if (flags & FIO_MACROMAN)
5594 {
5595 /*
5596 * Convert UTF-8 or latin1 to Apple MacRoman.
5597 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 char_u *from;
5599 size_t fromlen;
5600
5601 if (ip->bw_restlen > 0)
5602 {
5603 /* Need to concatenate the remainder of the previous call and
5604 * the bytes of the current call. Use the end of the
5605 * conversion buffer for this. */
5606 fromlen = len + ip->bw_restlen;
5607 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5608 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5609 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5610 }
5611 else
5612 {
5613 from = buf;
5614 fromlen = len;
5615 }
5616
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005617 if (enc2macroman(from, fromlen,
5618 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5619 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005620 {
5621 ip->bw_conv_error = TRUE;
5622 return FAIL;
5623 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005624 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005625 }
5626# endif
5627
5628# ifdef USE_ICONV
5629 if (ip->bw_iconv_fd != (iconv_t)-1)
5630 {
5631 const char *from;
5632 size_t fromlen;
5633 char *to;
5634 size_t tolen;
5635
5636 /* Convert with iconv(). */
5637 if (ip->bw_restlen > 0)
5638 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005639 char *fp;
5640
Bram Moolenaar071d4272004-06-13 20:20:40 +00005641 /* Need to concatenate the remainder of the previous call and
5642 * the bytes of the current call. Use the end of the
5643 * conversion buffer for this. */
5644 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005645 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5646 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5647 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5648 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005649 tolen = ip->bw_conv_buflen - fromlen;
5650 }
5651 else
5652 {
5653 from = (const char *)buf;
5654 fromlen = len;
5655 tolen = ip->bw_conv_buflen;
5656 }
5657 to = (char *)ip->bw_conv_buf;
5658
5659 if (ip->bw_first)
5660 {
5661 size_t save_len = tolen;
5662
5663 /* output the initial shift state sequence */
5664 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5665
5666 /* There is a bug in iconv() on Linux (which appears to be
5667 * wide-spread) which sets "to" to NULL and messes up "tolen".
5668 */
5669 if (to == NULL)
5670 {
5671 to = (char *)ip->bw_conv_buf;
5672 tolen = save_len;
5673 }
5674 ip->bw_first = FALSE;
5675 }
5676
5677 /*
5678 * If iconv() has an error or there is not enough room, fail.
5679 */
5680 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5681 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5682 || fromlen > CONV_RESTLEN)
5683 {
5684 ip->bw_conv_error = TRUE;
5685 return FAIL;
5686 }
5687
5688 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5689 if (fromlen > 0)
5690 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5691 ip->bw_restlen = (int)fromlen;
5692
5693 buf = ip->bw_conv_buf;
5694 len = (int)((char_u *)to - ip->bw_conv_buf);
5695 }
5696# endif
5697 }
5698#endif /* FEAT_MBYTE */
5699
5700#ifdef FEAT_CRYPT
5701 if (flags & FIO_ENCRYPTED) /* encrypt the data */
Bram Moolenaar04c9baf2010-06-01 23:37:39 +02005702 crypt_encode(buf, len, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703#endif
5704
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005705 wlen = write_eintr(ip->bw_fd, buf, len);
5706 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005707}
5708
5709#ifdef FEAT_MBYTE
5710/*
5711 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005712 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005713 */
5714 static int
5715ucs2bytes(c, pp, flags)
5716 unsigned c; /* in: character */
5717 char_u **pp; /* in/out: pointer to result */
5718 int flags; /* FIO_ flags */
5719{
5720 char_u *p = *pp;
5721 int error = FALSE;
5722 int cc;
5723
5724
5725 if (flags & FIO_UCS4)
5726 {
5727 if (flags & FIO_ENDIAN_L)
5728 {
5729 *p++ = c;
5730 *p++ = (c >> 8);
5731 *p++ = (c >> 16);
5732 *p++ = (c >> 24);
5733 }
5734 else
5735 {
5736 *p++ = (c >> 24);
5737 *p++ = (c >> 16);
5738 *p++ = (c >> 8);
5739 *p++ = c;
5740 }
5741 }
5742 else if (flags & (FIO_UCS2 | FIO_UTF16))
5743 {
5744 if (c >= 0x10000)
5745 {
5746 if (flags & FIO_UTF16)
5747 {
5748 /* Make two words, ten bits of the character in each. First
5749 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5750 c -= 0x10000;
5751 if (c >= 0x100000)
5752 error = TRUE;
5753 cc = ((c >> 10) & 0x3ff) + 0xd800;
5754 if (flags & FIO_ENDIAN_L)
5755 {
5756 *p++ = cc;
5757 *p++ = ((unsigned)cc >> 8);
5758 }
5759 else
5760 {
5761 *p++ = ((unsigned)cc >> 8);
5762 *p++ = cc;
5763 }
5764 c = (c & 0x3ff) + 0xdc00;
5765 }
5766 else
5767 error = TRUE;
5768 }
5769 if (flags & FIO_ENDIAN_L)
5770 {
5771 *p++ = c;
5772 *p++ = (c >> 8);
5773 }
5774 else
5775 {
5776 *p++ = (c >> 8);
5777 *p++ = c;
5778 }
5779 }
5780 else /* Latin1 */
5781 {
5782 if (c >= 0x100)
5783 {
5784 error = TRUE;
5785 *p++ = 0xBF;
5786 }
5787 else
5788 *p++ = c;
5789 }
5790
5791 *pp = p;
5792 return error;
5793}
5794
5795/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005796 * Return TRUE if file encoding "fenc" requires conversion from or to
5797 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798 */
5799 static int
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005800need_conversion(fenc)
5801 char_u *fenc;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005802{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005803 int same_encoding;
5804 int enc_flags;
5805 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005806
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005807 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005808 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005809 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005810 fenc_flags = 0;
5811 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005812 else
5813 {
5814 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5815 * "ucs-4be", etc. */
5816 enc_flags = get_fio_flags(p_enc);
5817 fenc_flags = get_fio_flags(fenc);
5818 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5819 }
5820 if (same_encoding)
5821 {
5822 /* Specified encoding matches with 'encoding'. This requires
5823 * conversion when 'encoding' is Unicode but not UTF-8. */
5824 return enc_unicode != 0;
5825 }
5826
5827 /* Encodings differ. However, conversion is not needed when 'enc' is any
5828 * Unicode encoding and the file is UTF-8. */
5829 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005830}
5831
5832/*
5833 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5834 * internal conversion.
5835 * if "ptr" is an empty string, use 'encoding'.
5836 */
5837 static int
5838get_fio_flags(ptr)
5839 char_u *ptr;
5840{
5841 int prop;
5842
5843 if (*ptr == NUL)
5844 ptr = p_enc;
5845
5846 prop = enc_canon_props(ptr);
5847 if (prop & ENC_UNICODE)
5848 {
5849 if (prop & ENC_2BYTE)
5850 {
5851 if (prop & ENC_ENDIAN_L)
5852 return FIO_UCS2 | FIO_ENDIAN_L;
5853 return FIO_UCS2;
5854 }
5855 if (prop & ENC_4BYTE)
5856 {
5857 if (prop & ENC_ENDIAN_L)
5858 return FIO_UCS4 | FIO_ENDIAN_L;
5859 return FIO_UCS4;
5860 }
5861 if (prop & ENC_2WORD)
5862 {
5863 if (prop & ENC_ENDIAN_L)
5864 return FIO_UTF16 | FIO_ENDIAN_L;
5865 return FIO_UTF16;
5866 }
5867 return FIO_UTF8;
5868 }
5869 if (prop & ENC_LATIN1)
5870 return FIO_LATIN1;
5871 /* must be ENC_DBCS, requires iconv() */
5872 return 0;
5873}
5874
5875#ifdef WIN3264
5876/*
5877 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5878 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5879 * Used for conversion between 'encoding' and 'fileencoding'.
5880 */
5881 static int
5882get_win_fio_flags(ptr)
5883 char_u *ptr;
5884{
5885 int cp;
5886
5887 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5888 if (!enc_utf8 && enc_codepage <= 0)
5889 return 0;
5890
5891 cp = encname2codepage(ptr);
5892 if (cp == 0)
5893 {
5894# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5895 if (STRCMP(ptr, "utf-8") == 0)
5896 cp = CP_UTF8;
5897 else
5898# endif
5899 return 0;
5900 }
5901 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5902}
5903#endif
5904
5905#ifdef MACOS_X
5906/*
5907 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5908 * needed for the internal conversion to/from utf-8 or latin1.
5909 */
5910 static int
5911get_mac_fio_flags(ptr)
5912 char_u *ptr;
5913{
5914 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5915 && (enc_canon_props(ptr) & ENC_MACROMAN))
5916 return FIO_MACROMAN;
5917 return 0;
5918}
5919#endif
5920
5921/*
5922 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5923 * "size" must be at least 2.
5924 * Return the name of the encoding and set "*lenp" to the length.
5925 * Returns NULL when no BOM found.
5926 */
5927 static char_u *
5928check_for_bom(p, size, lenp, flags)
5929 char_u *p;
5930 long size;
5931 int *lenp;
5932 int flags;
5933{
5934 char *name = NULL;
5935 int len = 2;
5936
5937 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005938 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005939 {
5940 name = "utf-8"; /* EF BB BF */
5941 len = 3;
5942 }
5943 else if (p[0] == 0xff && p[1] == 0xfe)
5944 {
5945 if (size >= 4 && p[2] == 0 && p[3] == 0
5946 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5947 {
5948 name = "ucs-4le"; /* FF FE 00 00 */
5949 len = 4;
5950 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005951 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005952 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005953 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5954 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005955 name = "utf-16le"; /* FF FE */
5956 }
5957 else if (p[0] == 0xfe && p[1] == 0xff
5958 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5959 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005960 /* Default to utf-16, it works also for ucs-2 text. */
5961 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005962 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005963 else
5964 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005965 }
5966 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5967 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5968 {
5969 name = "ucs-4"; /* 00 00 FE FF */
5970 len = 4;
5971 }
5972
5973 *lenp = len;
5974 return (char_u *)name;
5975}
5976
5977/*
5978 * Generate a BOM in "buf[4]" for encoding "name".
5979 * Return the length of the BOM (zero when no BOM).
5980 */
5981 static int
5982make_bom(buf, name)
5983 char_u *buf;
5984 char_u *name;
5985{
5986 int flags;
5987 char_u *p;
5988
5989 flags = get_fio_flags(name);
5990
5991 /* Can't put a BOM in a non-Unicode file. */
5992 if (flags == FIO_LATIN1 || flags == 0)
5993 return 0;
5994
5995 if (flags == FIO_UTF8) /* UTF-8 */
5996 {
5997 buf[0] = 0xef;
5998 buf[1] = 0xbb;
5999 buf[2] = 0xbf;
6000 return 3;
6001 }
6002 p = buf;
6003 (void)ucs2bytes(0xfeff, &p, flags);
6004 return (int)(p - buf);
6005}
6006#endif
6007
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006008#if defined(FEAT_VIMINFO) || defined(FEAT_BROWSE) || \
Bram Moolenaara0174af2008-01-02 20:08:25 +00006009 defined(FEAT_QUICKFIX) || defined(FEAT_AUTOCMD) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006010/*
6011 * Try to find a shortname by comparing the fullname with the current
6012 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006013 * Returns "full_path" or pointer into "full_path" if shortened.
6014 */
6015 char_u *
6016shorten_fname1(full_path)
6017 char_u *full_path;
6018{
6019 char_u dirname[MAXPATHL];
6020 char_u *p = full_path;
6021
6022 if (mch_dirname(dirname, MAXPATHL) == OK)
6023 {
6024 p = shorten_fname(full_path, dirname);
6025 if (p == NULL || *p == NUL)
6026 p = full_path;
6027 }
6028 return p;
6029}
Bram Moolenaard4cacdf2007-10-03 10:50:10 +00006030#endif
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006031
6032/*
6033 * Try to find a shortname by comparing the fullname with the current
6034 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006035 * Returns NULL if not shorter name possible, pointer into "full_path"
6036 * otherwise.
6037 */
6038 char_u *
6039shorten_fname(full_path, dir_name)
6040 char_u *full_path;
6041 char_u *dir_name;
6042{
6043 int len;
6044 char_u *p;
6045
6046 if (full_path == NULL)
6047 return NULL;
6048 len = (int)STRLEN(dir_name);
6049 if (fnamencmp(dir_name, full_path, len) == 0)
6050 {
6051 p = full_path + len;
6052#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6053 /*
6054 * MSDOS: when a file is in the root directory, dir_name will end in a
6055 * slash, since C: by itself does not define a specific dir. In this
6056 * case p may already be correct. <negri>
6057 */
6058 if (!((len > 2) && (*(p - 2) == ':')))
6059#endif
6060 {
6061 if (vim_ispathsep(*p))
6062 ++p;
6063#ifndef VMS /* the path separator is always part of the path */
6064 else
6065 p = NULL;
6066#endif
6067 }
6068 }
6069#if defined(MSDOS) || defined(MSWIN) || defined(OS2)
6070 /*
6071 * When using a file in the current drive, remove the drive name:
6072 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6073 * a floppy from "A:\dir" to "B:\dir".
6074 */
6075 else if (len > 3
6076 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6077 && full_path[1] == ':'
6078 && vim_ispathsep(full_path[2]))
6079 p = full_path + 2;
6080#endif
6081 else
6082 p = NULL;
6083 return p;
6084}
6085
6086/*
6087 * Shorten filenames for all buffers.
6088 * When "force" is TRUE: Use full path from now on for files currently being
6089 * edited, both for file name and swap file name. Try to shorten the file
6090 * names a bit, if safe to do so.
6091 * When "force" is FALSE: Only try to shorten absolute file names.
6092 * For buffers that have buftype "nofile" or "scratch": never change the file
6093 * name.
6094 */
6095 void
6096shorten_fnames(force)
6097 int force;
6098{
6099 char_u dirname[MAXPATHL];
6100 buf_T *buf;
6101 char_u *p;
6102
6103 mch_dirname(dirname, MAXPATHL);
6104 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
6105 {
6106 if (buf->b_fname != NULL
6107#ifdef FEAT_QUICKFIX
6108 && !bt_nofile(buf)
6109#endif
6110 && !path_with_url(buf->b_fname)
6111 && (force
6112 || buf->b_sfname == NULL
6113 || mch_isFullName(buf->b_sfname)))
6114 {
6115 vim_free(buf->b_sfname);
6116 buf->b_sfname = NULL;
6117 p = shorten_fname(buf->b_ffname, dirname);
6118 if (p != NULL)
6119 {
6120 buf->b_sfname = vim_strsave(p);
6121 buf->b_fname = buf->b_sfname;
6122 }
6123 if (p == NULL || buf->b_fname == NULL)
6124 buf->b_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006125 }
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006126
6127 /* Always make the swap file name a full path, a "nofile" buffer may
6128 * also have a swap file. */
6129 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006130 }
6131#ifdef FEAT_WINDOWS
6132 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006133 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006134#endif
6135}
6136
6137#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6138 || defined(FEAT_GUI_MSWIN) \
6139 || defined(FEAT_GUI_MAC) \
6140 || defined(PROTO)
6141/*
6142 * Shorten all filenames in "fnames[count]" by current directory.
6143 */
6144 void
6145shorten_filenames(fnames, count)
6146 char_u **fnames;
6147 int count;
6148{
6149 int i;
6150 char_u dirname[MAXPATHL];
6151 char_u *p;
6152
6153 if (fnames == NULL || count < 1)
6154 return;
6155 mch_dirname(dirname, sizeof(dirname));
6156 for (i = 0; i < count; ++i)
6157 {
6158 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6159 {
6160 /* shorten_fname() returns pointer in given "fnames[i]". If free
6161 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6162 * "p" first then free fnames[i]. */
6163 p = vim_strsave(p);
6164 vim_free(fnames[i]);
6165 fnames[i] = p;
6166 }
6167 }
6168}
6169#endif
6170
6171/*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006172 * add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006173 * fo_o_h.ext for MSDOS or when shortname option set.
6174 *
6175 * Assumed that fname is a valid name found in the filesystem we assure that
6176 * the return value is a different name and ends in 'ext'.
6177 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6178 * characters otherwise.
6179 * Space for the returned name is allocated, must be freed later.
6180 * Returns NULL when out of memory.
6181 */
6182 char_u *
6183modname(fname, ext, prepend_dot)
6184 char_u *fname, *ext;
6185 int prepend_dot; /* may prepend a '.' to file name */
6186{
6187 return buf_modname(
6188#ifdef SHORT_FNAME
6189 TRUE,
6190#else
6191 (curbuf->b_p_sn || curbuf->b_shortname),
6192#endif
6193 fname, ext, prepend_dot);
6194}
6195
6196 char_u *
6197buf_modname(shortname, fname, ext, prepend_dot)
6198 int shortname; /* use 8.3 file name */
6199 char_u *fname, *ext;
6200 int prepend_dot; /* may prepend a '.' to file name */
6201{
6202 char_u *retval;
6203 char_u *s;
6204 char_u *e;
6205 char_u *ptr;
6206 int fnamelen, extlen;
6207
6208 extlen = (int)STRLEN(ext);
6209
6210 /*
6211 * If there is no file name we must get the name of the current directory
6212 * (we need the full path in case :cd is used).
6213 */
6214 if (fname == NULL || *fname == NUL)
6215 {
6216 retval = alloc((unsigned)(MAXPATHL + extlen + 3));
6217 if (retval == NULL)
6218 return NULL;
6219 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6220 (fnamelen = (int)STRLEN(retval)) == 0)
6221 {
6222 vim_free(retval);
6223 return NULL;
6224 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006225 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006226 {
6227 retval[fnamelen++] = PATHSEP;
6228 retval[fnamelen] = NUL;
6229 }
6230#ifndef SHORT_FNAME
6231 prepend_dot = FALSE; /* nothing to prepend a dot to */
6232#endif
6233 }
6234 else
6235 {
6236 fnamelen = (int)STRLEN(fname);
6237 retval = alloc((unsigned)(fnamelen + extlen + 3));
6238 if (retval == NULL)
6239 return NULL;
6240 STRCPY(retval, fname);
6241#ifdef VMS
6242 vms_remove_version(retval); /* we do not need versions here */
6243#endif
6244 }
6245
6246 /*
6247 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6248 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6249 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6250 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6251 */
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006252 for (ptr = retval + fnamelen; ptr > retval; mb_ptr_back(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006253 {
6254#ifndef RISCOS
6255 if (*ext == '.'
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006256# ifdef USE_LONG_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 && (!USE_LONG_FNAME || shortname)
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006258# else
6259# ifndef SHORT_FNAME
Bram Moolenaar071d4272004-06-13 20:20:40 +00006260 && shortname
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006261# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006262# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006263 )
6264 if (*ptr == '.') /* replace '.' by '_' */
6265 *ptr = '_';
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006266#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006268 {
6269 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006270 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006271 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006272 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006273
6274 /* the file name has at most BASENAMELEN characters. */
6275#ifndef SHORT_FNAME
6276 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6277 ptr[BASENAMELEN] = '\0';
6278#endif
6279
6280 s = ptr + STRLEN(ptr);
6281
6282 /*
6283 * For 8.3 file names we may have to reduce the length.
6284 */
6285#ifdef USE_LONG_FNAME
6286 if (!USE_LONG_FNAME || shortname)
6287#else
6288# ifndef SHORT_FNAME
6289 if (shortname)
6290# endif
6291#endif
6292 {
6293 /*
6294 * If there is no file name, or the file name ends in '/', and the
6295 * extension starts with '.', put a '_' before the dot, because just
6296 * ".ext" is invalid.
6297 */
6298 if (fname == NULL || *fname == NUL
6299 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6300 {
6301#ifdef RISCOS
6302 if (*ext == '/')
6303#else
6304 if (*ext == '.')
6305#endif
6306 *s++ = '_';
6307 }
6308 /*
6309 * If the extension starts with '.', truncate the base name at 8
6310 * characters
6311 */
6312#ifdef RISCOS
6313 /* We normally use '/', but swap files are '_' */
6314 else if (*ext == '/' || *ext == '_')
6315#else
6316 else if (*ext == '.')
6317#endif
6318 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006319 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006320 {
6321 s = ptr + 8;
6322 *s = '\0';
6323 }
6324 }
6325 /*
6326 * If the extension doesn't start with '.', and the file name
6327 * doesn't have an extension yet, append a '.'
6328 */
6329#ifdef RISCOS
6330 else if ((e = vim_strchr(ptr, '/')) == NULL)
6331 *s++ = '/';
6332#else
6333 else if ((e = vim_strchr(ptr, '.')) == NULL)
6334 *s++ = '.';
6335#endif
6336 /*
6337 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006338 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006339 */
6340 else if ((int)STRLEN(e) + extlen > 4)
6341 s = e + 4 - extlen;
6342 }
6343#if defined(OS2) || defined(USE_LONG_FNAME) || defined(WIN3264)
6344 /*
6345 * If there is no file name, and the extension starts with '.', put a
6346 * '_' before the dot, because just ".ext" may be invalid if it's on a
6347 * FAT partition, and on HPFS it doesn't matter.
6348 */
6349 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6350 *s++ = '_';
6351#endif
6352
6353 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006354 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 * ext can start with '.' and cannot exceed 3 more characters.
6356 */
6357 STRCPY(s, ext);
6358
6359#ifndef SHORT_FNAME
6360 /*
6361 * Prepend the dot.
6362 */
6363 if (prepend_dot && !shortname && *(e = gettail(retval)) !=
6364#ifdef RISCOS
6365 '/'
6366#else
6367 '.'
6368#endif
6369#ifdef USE_LONG_FNAME
6370 && USE_LONG_FNAME
6371#endif
6372 )
6373 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006374 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006375#ifdef RISCOS
6376 *e = '/';
6377#else
6378 *e = '.';
6379#endif
6380 }
6381#endif
6382
6383 /*
6384 * Check that, after appending the extension, the file name is really
6385 * different.
6386 */
6387 if (fname != NULL && STRCMP(fname, retval) == 0)
6388 {
6389 /* we search for a character that can be replaced by '_' */
6390 while (--s >= ptr)
6391 {
6392 if (*s != '_')
6393 {
6394 *s = '_';
6395 break;
6396 }
6397 }
6398 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6399 *ptr = 'v';
6400 }
6401 return retval;
6402}
6403
6404/*
6405 * Like fgets(), but if the file line is too long, it is truncated and the
6406 * rest of the line is thrown away. Returns TRUE for end-of-file.
6407 */
6408 int
6409vim_fgets(buf, size, fp)
6410 char_u *buf;
6411 int size;
6412 FILE *fp;
6413{
6414 char *eof;
6415#define FGETS_SIZE 200
6416 char tbuf[FGETS_SIZE];
6417
6418 buf[size - 2] = NUL;
6419#ifdef USE_CR
6420 eof = fgets_cr((char *)buf, size, fp);
6421#else
6422 eof = fgets((char *)buf, size, fp);
6423#endif
6424 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6425 {
6426 buf[size - 1] = NUL; /* Truncate the line */
6427
6428 /* Now throw away the rest of the line: */
6429 do
6430 {
6431 tbuf[FGETS_SIZE - 2] = NUL;
6432#ifdef USE_CR
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006433 ignoredp = fgets_cr((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006434#else
Bram Moolenaarfe86f2d2008-11-28 20:29:07 +00006435 ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006436#endif
6437 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6438 }
6439 return (eof == NULL);
6440}
6441
6442#if defined(USE_CR) || defined(PROTO)
6443/*
6444 * Like vim_fgets(), but accept any line terminator: CR, CR-LF or LF.
6445 * Returns TRUE for end-of-file.
6446 * Only used for the Mac, because it's much slower than vim_fgets().
6447 */
6448 int
6449tag_fgets(buf, size, fp)
6450 char_u *buf;
6451 int size;
6452 FILE *fp;
6453{
6454 int i = 0;
6455 int c;
6456 int eof = FALSE;
6457
6458 for (;;)
6459 {
6460 c = fgetc(fp);
6461 if (c == EOF)
6462 {
6463 eof = TRUE;
6464 break;
6465 }
6466 if (c == '\r')
6467 {
6468 /* Always store a NL for end-of-line. */
6469 if (i < size - 1)
6470 buf[i++] = '\n';
6471 c = fgetc(fp);
6472 if (c != '\n') /* Macintosh format: single CR. */
6473 ungetc(c, fp);
6474 break;
6475 }
6476 if (i < size - 1)
6477 buf[i++] = c;
6478 if (c == '\n')
6479 break;
6480 }
6481 buf[i] = NUL;
6482 return eof;
6483}
6484#endif
6485
6486/*
6487 * rename() only works if both files are on the same file system, this
6488 * function will (attempts to?) copy the file across if rename fails -- webb
6489 * Return -1 for failure, 0 for success.
6490 */
6491 int
6492vim_rename(from, to)
6493 char_u *from;
6494 char_u *to;
6495{
6496 int fd_in;
6497 int fd_out;
6498 int n;
6499 char *errmsg = NULL;
6500 char *buffer;
6501#ifdef AMIGA
6502 BPTR flock;
6503#endif
6504 struct stat st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006505 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006506#ifdef HAVE_ACL
6507 vim_acl_T acl; /* ACL from original file */
6508#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006509#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6510 int use_tmp_file = FALSE;
6511#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006512
6513 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006514 * When the names are identical, there is nothing to do. When they refer
6515 * to the same file (ignoring case and slash/backslash differences) but
6516 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006517 */
6518 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006519 {
6520#ifdef CASE_INSENSITIVE_FILENAME
6521 if (STRCMP(gettail(from), gettail(to)) != 0)
6522 use_tmp_file = TRUE;
6523 else
6524#endif
6525 return 0;
6526 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527
6528 /*
6529 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6530 */
6531 if (mch_stat((char *)from, &st) < 0)
6532 return -1;
6533
Bram Moolenaar3576da72008-12-30 15:15:57 +00006534#ifdef UNIX
6535 {
6536 struct stat st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006537
6538 /* It's possible for the source and destination to be the same file.
6539 * This happens when "from" and "to" differ in case and are on a FAT32
6540 * filesystem. In that case go through a temp file name. */
6541 if (mch_stat((char *)to, &st_to) >= 0
6542 && st.st_dev == st_to.st_dev
6543 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006544 use_tmp_file = TRUE;
6545 }
6546#endif
6547
6548#if defined(UNIX) || defined(CASE_INSENSITIVE_FILENAME)
6549 if (use_tmp_file)
6550 {
6551 char tempname[MAXPATHL + 1];
6552
6553 /*
6554 * Find a name that doesn't exist and is in the same directory.
6555 * Rename "from" to "tempname" and then rename "tempname" to "to".
6556 */
6557 if (STRLEN(from) >= MAXPATHL - 5)
6558 return -1;
6559 STRCPY(tempname, from);
6560 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006561 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006562 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6563 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006564 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006565 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006566 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006567 if (mch_rename(tempname, (char *)to) == 0)
6568 return 0;
6569 /* Strange, the second step failed. Try moving the
6570 * file back and return failure. */
6571 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006572 return -1;
6573 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006574 /* If it fails for one temp name it will most likely fail
6575 * for any temp name, give up. */
6576 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006577 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006578 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006579 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006580 }
6581#endif
6582
Bram Moolenaar071d4272004-06-13 20:20:40 +00006583 /*
6584 * Delete the "to" file, this is required on some systems to make the
6585 * mch_rename() work, on other systems it makes sure that we don't have
6586 * two files when the mch_rename() fails.
6587 */
6588
6589#ifdef AMIGA
6590 /*
6591 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6592 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006593 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006594 * deleting the "from" file (horror!) we lock it during the remove.
6595 *
6596 * When used for making a backup before writing the file: This should not
6597 * happen with ":w", because startscript() should detect this problem and
6598 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6599 * name. This problem does exist with ":w filename", but then the
6600 * original file will be somewhere else so the backup isn't really
6601 * important. If autoscripting is off the rename may fail.
6602 */
6603 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6604#endif
6605 mch_remove(to);
6606#ifdef AMIGA
6607 if (flock)
6608 UnLock(flock);
6609#endif
6610
6611 /*
6612 * First try a normal rename, return if it works.
6613 */
6614 if (mch_rename((char *)from, (char *)to) == 0)
6615 return 0;
6616
6617 /*
6618 * Rename() failed, try copying the file.
6619 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006620 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006621#ifdef HAVE_ACL
6622 /* For systems that support ACL: get the ACL from the original file. */
6623 acl = mch_get_acl(from);
6624#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006625 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6626 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006627 {
6628#ifdef HAVE_ACL
6629 mch_free_acl(acl);
6630#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006631 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006632 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006633
6634 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006635 fd_out = mch_open((char *)to,
6636 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006637 if (fd_out == -1)
6638 {
6639 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006640#ifdef HAVE_ACL
6641 mch_free_acl(acl);
6642#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006643 return -1;
6644 }
6645
6646 buffer = (char *)alloc(BUFSIZE);
6647 if (buffer == NULL)
6648 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006649 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006650 close(fd_in);
6651#ifdef HAVE_ACL
6652 mch_free_acl(acl);
6653#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006654 return -1;
6655 }
6656
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006657 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6658 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006659 {
6660 errmsg = _("E208: Error writing to \"%s\"");
6661 break;
6662 }
6663
6664 vim_free(buffer);
6665 close(fd_in);
6666 if (close(fd_out) < 0)
6667 errmsg = _("E209: Error closing \"%s\"");
6668 if (n < 0)
6669 {
6670 errmsg = _("E210: Error reading \"%s\"");
6671 to = from;
6672 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006673#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006674 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006675#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006676#ifdef HAVE_ACL
6677 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006678 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006679#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006680 if (errmsg != NULL)
6681 {
6682 EMSG2(errmsg, to);
6683 return -1;
6684 }
6685 mch_remove(from);
6686 return 0;
6687}
6688
6689static int already_warned = FALSE;
6690
6691/*
6692 * Check if any not hidden buffer has been changed.
6693 * Postpone the check if there are characters in the stuff buffer, a global
6694 * command is being executed, a mapping is being executed or an autocommand is
6695 * busy.
6696 * Returns TRUE if some message was written (screen should be redrawn and
6697 * cursor positioned).
6698 */
6699 int
6700check_timestamps(focus)
6701 int focus; /* called for GUI focus event */
6702{
6703 buf_T *buf;
6704 int didit = 0;
6705 int n;
6706
6707 /* Don't check timestamps while system() or another low-level function may
6708 * cause us to lose and gain focus. */
6709 if (no_check_timestamps > 0)
6710 return FALSE;
6711
6712 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6713 * event and we would keep on checking if the file is steadily growing.
6714 * Do check again after typing something. */
6715 if (focus && did_check_timestamps)
6716 {
6717 need_check_timestamps = TRUE;
6718 return FALSE;
6719 }
6720
6721 if (!stuff_empty() || global_busy || !typebuf_typed()
6722#ifdef FEAT_AUTOCMD
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006723 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00006724#endif
6725 )
6726 need_check_timestamps = TRUE; /* check later */
6727 else
6728 {
6729 ++no_wait_return;
6730 did_check_timestamps = TRUE;
6731 already_warned = FALSE;
6732 for (buf = firstbuf; buf != NULL; )
6733 {
6734 /* Only check buffers in a window. */
6735 if (buf->b_nwindows > 0)
6736 {
6737 n = buf_check_timestamp(buf, focus);
6738 if (didit < n)
6739 didit = n;
6740 if (n > 0 && !buf_valid(buf))
6741 {
6742 /* Autocommands have removed the buffer, start at the
6743 * first one again. */
6744 buf = firstbuf;
6745 continue;
6746 }
6747 }
6748 buf = buf->b_next;
6749 }
6750 --no_wait_return;
6751 need_check_timestamps = FALSE;
6752 if (need_wait_return && didit == 2)
6753 {
6754 /* make sure msg isn't overwritten */
6755 msg_puts((char_u *)"\n");
6756 out_flush();
6757 }
6758 }
6759 return didit;
6760}
6761
6762/*
6763 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6764 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6765 * empty.
6766 */
6767 static int
6768move_lines(frombuf, tobuf)
6769 buf_T *frombuf;
6770 buf_T *tobuf;
6771{
6772 buf_T *tbuf = curbuf;
6773 int retval = OK;
6774 linenr_T lnum;
6775 char_u *p;
6776
6777 /* Copy the lines in "frombuf" to "tobuf". */
6778 curbuf = tobuf;
6779 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6780 {
6781 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6782 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6783 {
6784 vim_free(p);
6785 retval = FAIL;
6786 break;
6787 }
6788 vim_free(p);
6789 }
6790
6791 /* Delete all the lines in "frombuf". */
6792 if (retval != FAIL)
6793 {
6794 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006795 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6796 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006797 {
6798 /* Oops! We could try putting back the saved lines, but that
6799 * might fail again... */
6800 retval = FAIL;
6801 break;
6802 }
6803 }
6804
6805 curbuf = tbuf;
6806 return retval;
6807}
6808
6809/*
6810 * Check if buffer "buf" has been changed.
6811 * Also check if the file for a new buffer unexpectedly appeared.
6812 * return 1 if a changed buffer was found.
6813 * return 2 if a message has been displayed.
6814 * return 0 otherwise.
6815 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006816 int
6817buf_check_timestamp(buf, focus)
6818 buf_T *buf;
Bram Moolenaar78a15312009-05-15 19:33:18 +00006819 int focus UNUSED; /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006820{
6821 struct stat st;
6822 int stat_res;
6823 int retval = 0;
6824 char_u *path;
6825 char_u *tbuf;
6826 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006827 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006828 int helpmesg = FALSE;
6829 int reload = FALSE;
6830#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6831 int can_reload = FALSE;
6832#endif
Bram Moolenaar914703b2010-05-31 21:59:46 +02006833 off_t orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006834 int orig_mode = buf->b_orig_mode;
6835#ifdef FEAT_GUI
6836 int save_mouse_correct = need_mouse_correct;
6837#endif
6838#ifdef FEAT_AUTOCMD
6839 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006840 int n;
6841 char_u *s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006843 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006844
6845 /* If there is no file name, the buffer is not loaded, 'buftype' is
6846 * set, we are in the middle of a save or being called recursively: ignore
6847 * this buffer. */
6848 if (buf->b_ffname == NULL
6849 || buf->b_ml.ml_mfp == NULL
6850#if defined(FEAT_QUICKFIX)
6851 || *buf->b_p_bt != NUL
6852#endif
6853 || buf->b_saving
6854#ifdef FEAT_AUTOCMD
6855 || busy
6856#endif
Bram Moolenaar009b2592004-10-24 19:18:58 +00006857#ifdef FEAT_NETBEANS_INTG
6858 || isNetbeansBuffer(buf)
6859#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006860 )
6861 return 0;
6862
6863 if ( !(buf->b_flags & BF_NOTEDITED)
6864 && buf->b_mtime != 0
6865 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6866 || time_differs((long)st.st_mtime, buf->b_mtime)
6867#ifdef HAVE_ST_MODE
6868 || (int)st.st_mode != buf->b_orig_mode
6869#else
6870 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6871#endif
6872 ))
6873 {
6874 retval = 1;
6875
Bram Moolenaar316059c2006-01-14 21:18:42 +00006876 /* set b_mtime to stop further warnings (e.g., when executing
6877 * FileChangedShell autocmd) */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006878 if (stat_res < 0)
6879 {
6880 buf->b_mtime = 0;
6881 buf->b_orig_size = 0;
6882 buf->b_orig_mode = 0;
6883 }
6884 else
6885 buf_store_time(buf, &st, buf->b_ffname);
6886
6887 /* Don't do anything for a directory. Might contain the file
6888 * explorer. */
6889 if (mch_isdir(buf->b_fname))
6890 ;
6891
6892 /*
6893 * If 'autoread' is set, the buffer has no changes and the file still
6894 * exists, reload the buffer. Use the buffer-local option value if it
6895 * was set, the global option value otherwise.
6896 */
6897 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6898 && !bufIsChanged(buf) && stat_res >= 0)
6899 reload = TRUE;
6900 else
6901 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006902 if (stat_res < 0)
6903 reason = "deleted";
6904 else if (bufIsChanged(buf))
6905 reason = "conflict";
6906 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6907 reason = "changed";
6908 else if (orig_mode != buf->b_orig_mode)
6909 reason = "mode";
6910 else
6911 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006913#ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00006914 /*
6915 * Only give the warning if there are no FileChangedShell
6916 * autocommands.
6917 * Avoid being called recursively by setting "busy".
6918 */
6919 busy = TRUE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00006920# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006921 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6922 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaar1e015462005-09-25 22:16:38 +00006923# endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006924 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006925 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6926 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006927 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 busy = FALSE;
6929 if (n)
6930 {
6931 if (!buf_valid(buf))
6932 EMSG(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaar1e015462005-09-25 22:16:38 +00006933# ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006934 s = get_vim_var_str(VV_FCS_CHOICE);
6935 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6936 reload = TRUE;
6937 else if (STRCMP(s, "ask") == 0)
6938 n = FALSE;
6939 else
Bram Moolenaar1e015462005-09-25 22:16:38 +00006940# endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006941 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006943 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006944#endif
6945 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006946 if (*reason == 'd')
6947 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006948 else
6949 {
6950 helpmesg = TRUE;
6951#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6952 can_reload = TRUE;
6953#endif
6954 /*
6955 * Check if the file contents really changed to avoid
6956 * giving a warning when only the timestamp was set (e.g.,
6957 * checked out of CVS). Always warn when the buffer was
6958 * changed.
6959 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006960 if (reason[2] == 'n')
6961 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006962 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006963 mesg2 = _("See \":help W12\" for more info.");
6964 }
6965 else if (reason[1] == 'h')
6966 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006967 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006968 mesg2 = _("See \":help W11\" for more info.");
6969 }
6970 else if (*reason == 'm')
6971 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006972 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006973 mesg2 = _("See \":help W16\" for more info.");
6974 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006975 else
6976 /* Only timestamp changed, store it to avoid a warning
6977 * in check_mtime() later. */
6978 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006979 }
6980 }
6981 }
6982
6983 }
6984 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6985 && vim_fexists(buf->b_ffname))
6986 {
6987 retval = 1;
6988 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6989 buf->b_flags |= BF_NEW_W;
6990#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6991 can_reload = TRUE;
6992#endif
6993 }
6994
6995 if (mesg != NULL)
6996 {
6997 path = home_replace_save(buf, buf->b_fname);
6998 if (path != NULL)
6999 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00007000 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007001 mesg2 = "";
7002 tbuf = alloc((unsigned)(STRLEN(path) + STRLEN(mesg)
7003 + STRLEN(mesg2) + 2));
7004 sprintf((char *)tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00007005#ifdef FEAT_EVAL
7006 /* Set warningmsg here, before the unimportant and output-specific
7007 * mesg2 has been appended. */
7008 set_vim_var_string(VV_WARNINGMSG, tbuf, -1);
7009#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007010#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
7011 if (can_reload)
7012 {
7013 if (*mesg2 != NUL)
7014 {
7015 STRCAT(tbuf, "\n");
7016 STRCAT(tbuf, mesg2);
7017 }
7018 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"), tbuf,
7019 (char_u *)_("&OK\n&Load File"), 1, NULL) == 2)
7020 reload = TRUE;
7021 }
7022 else
7023#endif
7024 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
7025 {
7026 if (*mesg2 != NUL)
7027 {
7028 STRCAT(tbuf, "; ");
7029 STRCAT(tbuf, mesg2);
7030 }
7031 EMSG(tbuf);
7032 retval = 2;
7033 }
7034 else
7035 {
Bram Moolenaared203462004-06-16 11:19:22 +00007036# ifdef FEAT_AUTOCMD
Bram Moolenaar071d4272004-06-13 20:20:40 +00007037 if (!autocmd_busy)
Bram Moolenaared203462004-06-16 11:19:22 +00007038# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007039 {
7040 msg_start();
7041 msg_puts_attr(tbuf, hl_attr(HLF_E) + MSG_HIST);
7042 if (*mesg2 != NUL)
7043 msg_puts_attr((char_u *)mesg2,
7044 hl_attr(HLF_W) + MSG_HIST);
7045 msg_clr_eos();
7046 (void)msg_end();
7047 if (emsg_silent == 0)
7048 {
7049 out_flush();
Bram Moolenaared203462004-06-16 11:19:22 +00007050# ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00007051 if (!focus)
Bram Moolenaared203462004-06-16 11:19:22 +00007052# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007053 /* give the user some time to think about it */
7054 ui_delay(1000L, TRUE);
7055
7056 /* don't redraw and erase the message */
7057 redraw_cmdline = FALSE;
7058 }
7059 }
7060 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007061 }
7062
7063 vim_free(path);
7064 vim_free(tbuf);
7065 }
7066 }
7067
7068 if (reload)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007069 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00007070 buf_reload(buf, orig_mode);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007071
Bram Moolenaar56718732006-03-15 22:53:57 +00007072#ifdef FEAT_AUTOCMD
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00007073 /* Trigger FileChangedShell when the file was changed in any way. */
7074 if (buf_valid(buf) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00007075 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
7076 buf->b_fname, buf->b_fname, FALSE, buf);
7077#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007078#ifdef FEAT_GUI
7079 /* restore this in case an autocommand has set it; it would break
7080 * 'mousefocus' */
7081 need_mouse_correct = save_mouse_correct;
7082#endif
7083
7084 return retval;
7085}
7086
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007087/*
7088 * Reload a buffer that is already loaded.
7089 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00007090 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
7091 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007092 */
7093 void
Bram Moolenaar316059c2006-01-14 21:18:42 +00007094buf_reload(buf, orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007095 buf_T *buf;
Bram Moolenaar316059c2006-01-14 21:18:42 +00007096 int orig_mode;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007097{
7098 exarg_T ea;
7099 pos_T old_cursor;
7100 linenr_T old_topline;
7101 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007102 buf_T *savebuf;
7103 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007104 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007105 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007106
7107 /* set curwin/curbuf for "buf" and save some things */
7108 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007109
7110 /* We only want to read the text from the file, not reset the syntax
7111 * highlighting, clear marks, diff status, etc. Force the fileformat
7112 * and encoding to be the same. */
7113 if (prep_exarg(&ea, buf) == OK)
7114 {
7115 old_cursor = curwin->w_cursor;
7116 old_topline = curwin->w_topline;
7117
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007118 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007119 {
7120 /* Save all the text, so that the reload can be undone.
7121 * Sync first so that this is a separate undo-able action. */
7122 u_sync(FALSE);
7123 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7124 flags |= READ_KEEP_UNDO;
7125 }
7126
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007127 /*
7128 * To behave like when a new file is edited (matters for
7129 * BufReadPost autocommands) we first need to delete the current
7130 * buffer contents. But if reading the file fails we should keep
7131 * the old contents. Can't use memory only, the file might be
7132 * too big. Use a hidden buffer to move the buffer contents to.
7133 */
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007134 if (bufempty() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007135 savebuf = NULL;
7136 else
7137 {
7138 /* Allocate a buffer without putting it in the buffer list. */
7139 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007140 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007141 {
7142 /* Open the memline. */
7143 curbuf = savebuf;
7144 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007145 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007146 curbuf = buf;
7147 curwin->w_buffer = buf;
7148 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007149 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007150 || move_lines(buf, savebuf) == FAIL)
7151 {
7152 EMSG2(_("E462: Could not prepare for reloading \"%s\""),
7153 buf->b_fname);
7154 saved = FAIL;
7155 }
7156 }
7157
7158 if (saved == OK)
7159 {
7160 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
7161#ifdef FEAT_AUTOCMD
7162 keep_filetype = TRUE; /* don't detect 'filetype' */
7163#endif
7164 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7165 (linenr_T)0,
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007166 (linenr_T)MAXLNUM, &ea, flags) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007167 {
7168#if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
7169 if (!aborting())
7170#endif
7171 EMSG2(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007172 if (savebuf != NULL && buf_valid(savebuf) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007173 {
7174 /* Put the text back from the save buffer. First
7175 * delete any lines that readfile() added. */
7176 while (!bufempty())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007177 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007178 break;
7179 (void)move_lines(savebuf, buf);
7180 }
7181 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007182 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007183 {
7184 /* Mark the buffer as unmodified and free undo info. */
7185 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007186 if ((flags & READ_KEEP_UNDO) == 0)
7187 {
7188 u_blockfree(buf);
7189 u_clearall(buf);
7190 }
7191 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007192 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007193 /* Mark all undo states as changed. */
7194 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007195 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007196 }
7197 }
7198 vim_free(ea.cmd);
7199
Bram Moolenaar8424a622006-04-19 21:23:36 +00007200 if (savebuf != NULL && buf_valid(savebuf))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007201 wipe_buffer(savebuf, FALSE);
7202
7203#ifdef FEAT_DIFF
7204 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007205 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007206#endif
7207
7208 /* Restore the topline and cursor position and check it (lines may
7209 * have been removed). */
7210 if (old_topline > curbuf->b_ml.ml_line_count)
7211 curwin->w_topline = curbuf->b_ml.ml_line_count;
7212 else
7213 curwin->w_topline = old_topline;
7214 curwin->w_cursor = old_cursor;
7215 check_cursor();
7216 update_topline();
7217#ifdef FEAT_AUTOCMD
7218 keep_filetype = FALSE;
7219#endif
7220#ifdef FEAT_FOLDING
7221 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007222 win_T *wp;
7223 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007224
7225 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007226 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007227 if (wp->w_buffer == curwin->w_buffer
7228 && !foldmethodIsManual(wp))
7229 foldUpdateAll(wp);
7230 }
7231#endif
7232 /* If the mode didn't change and 'readonly' was set, keep the old
7233 * value; the user probably used the ":view" command. But don't
7234 * reset it, might have had a read error. */
7235 if (orig_mode == curbuf->b_orig_mode)
7236 curbuf->b_p_ro |= old_ro;
7237 }
7238
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007239 /* restore curwin/curbuf and a few other things */
7240 aucmd_restbuf(&aco);
7241 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007242}
7243
Bram Moolenaar071d4272004-06-13 20:20:40 +00007244 void
7245buf_store_time(buf, st, fname)
7246 buf_T *buf;
7247 struct stat *st;
Bram Moolenaar78a15312009-05-15 19:33:18 +00007248 char_u *fname UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007249{
7250 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007251 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007252#ifdef HAVE_ST_MODE
7253 buf->b_orig_mode = (int)st->st_mode;
7254#else
7255 buf->b_orig_mode = mch_getperm(fname);
7256#endif
7257}
7258
7259/*
7260 * Adjust the line with missing eol, used for the next write.
7261 * Used for do_filter(), when the input lines for the filter are deleted.
7262 */
7263 void
7264write_lnum_adjust(offset)
7265 linenr_T offset;
7266{
Bram Moolenaardf177f62005-02-22 08:39:57 +00007267 if (write_no_eol_lnum != 0) /* only if there is a missing eol */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007268 write_no_eol_lnum += offset;
7269}
7270
7271#if defined(TEMPDIRNAMES) || defined(PROTO)
7272static long temp_count = 0; /* Temp filename counter. */
7273
7274/*
7275 * Delete the temp directory and all files it contains.
7276 */
7277 void
7278vim_deltempdir()
7279{
7280 char_u **files;
7281 int file_count;
7282 int i;
7283
7284 if (vim_tempdir != NULL)
7285 {
7286 sprintf((char *)NameBuff, "%s*", vim_tempdir);
7287 if (gen_expand_wildcards(1, &NameBuff, &file_count, &files,
7288 EW_DIR|EW_FILE|EW_SILENT) == OK)
7289 {
7290 for (i = 0; i < file_count; ++i)
7291 mch_remove(files[i]);
7292 FreeWild(file_count, files);
7293 }
7294 gettail(NameBuff)[-1] = NUL;
7295 (void)mch_rmdir(NameBuff);
7296
7297 vim_free(vim_tempdir);
7298 vim_tempdir = NULL;
7299 }
7300}
7301#endif
7302
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007303#ifdef TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00007304/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007305 * Directory "tempdir" was created. Expand this name to a full path and put
7306 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7307 * "tempdir" must be no longer than MAXPATHL.
7308 */
7309 static void
7310vim_settempdir(tempdir)
7311 char_u *tempdir;
7312{
7313 char_u *buf;
7314
7315 buf = alloc((unsigned)MAXPATHL + 2);
7316 if (buf != NULL)
7317 {
7318 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7319 STRCPY(buf, tempdir);
7320# ifdef __EMX__
7321 if (vim_strchr(buf, '/') != NULL)
7322 STRCAT(buf, "/");
7323 else
7324# endif
7325 add_pathsep(buf);
7326 vim_tempdir = vim_strsave(buf);
7327 vim_free(buf);
7328 }
7329}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007330#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007331
7332/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007333 * vim_tempname(): Return a unique name that can be used for a temp file.
7334 *
7335 * The temp file is NOT created.
7336 *
7337 * The returned pointer is to allocated memory.
7338 * The returned pointer is NULL if no valid name was found.
7339 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007340 char_u *
7341vim_tempname(extra_char)
Bram Moolenaar78a15312009-05-15 19:33:18 +00007342 int extra_char UNUSED; /* char to use in the name instead of '?' */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007343{
7344#ifdef USE_TMPNAM
7345 char_u itmp[L_tmpnam]; /* use tmpnam() */
7346#else
7347 char_u itmp[TEMPNAMELEN];
7348#endif
7349
7350#ifdef TEMPDIRNAMES
7351 static char *(tempdirs[]) = {TEMPDIRNAMES};
7352 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007353# ifndef EEXIST
7354 struct stat st;
7355# endif
7356
7357 /*
7358 * This will create a directory for private use by this instance of Vim.
7359 * This is done once, and the same directory is used for all temp files.
7360 * This method avoids security problems because of symlink attacks et al.
7361 * It's also a bit faster, because we only need to check for an existing
7362 * file when creating the directory and not for each temp file.
7363 */
7364 if (vim_tempdir == NULL)
7365 {
7366 /*
7367 * Try the entries in TEMPDIRNAMES to create the temp directory.
7368 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007369 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007370 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007371# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007372 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007373 long nr;
7374 long off;
7375# endif
7376
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377 /* expand $TMP, leave room for "/v1100000/999999999" */
7378 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
7379 if (mch_isdir(itmp)) /* directory exists */
7380 {
7381# ifdef __EMX__
7382 /* If $TMP contains a forward slash (perhaps using bash or
7383 * tcsh), don't add a backslash, use a forward slash!
7384 * Adding 2 backslashes didn't work. */
7385 if (vim_strchr(itmp, '/') != NULL)
7386 STRCAT(itmp, "/");
7387 else
7388# endif
7389 add_pathsep(itmp);
7390
Bram Moolenaareaf03392009-11-17 11:08:52 +00007391# ifdef HAVE_MKDTEMP
7392 /* Leave room for filename */
7393 STRCAT(itmp, "vXXXXXX");
7394 if (mkdtemp((char *)itmp) != NULL)
7395 vim_settempdir(itmp);
7396# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007397 /* Get an arbitrary number of up to 6 digits. When it's
7398 * unlikely that it already exists it will be faster,
7399 * otherwise it doesn't matter. The use of mkdir() avoids any
7400 * security problems because of the predictable number. */
7401 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007402 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403
7404 /* Try up to 10000 different values until we find a name that
7405 * doesn't exist. */
7406 for (off = 0; off < 10000L; ++off)
7407 {
7408 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007409# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007410 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007411# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007412
Bram Moolenaareaf03392009-11-17 11:08:52 +00007413 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7414# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415 /* If mkdir() does not set errno to EEXIST, check for
7416 * existing file here. There is a race condition then,
7417 * although it's fail-safe. */
7418 if (mch_stat((char *)itmp, &st) >= 0)
7419 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007420# endif
7421# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007422 /* Make sure the umask doesn't remove the executable bit.
7423 * "repl" has been reported to use "177". */
7424 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007425# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007426 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007427# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007428 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007429# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007430 if (r == 0)
7431 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007432 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007433 break;
7434 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007435# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007436 /* If the mkdir() didn't fail because the file/dir exists,
7437 * we probably can't create any dir here, try another
7438 * place. */
7439 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007440# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007441 break;
7442 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007443# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 if (vim_tempdir != NULL)
7445 break;
7446 }
7447 }
7448 }
7449
7450 if (vim_tempdir != NULL)
7451 {
7452 /* There is no need to check if the file exists, because we own the
7453 * directory and nobody else creates a file in it. */
7454 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7455 return vim_strsave(itmp);
7456 }
7457
7458 return NULL;
7459
7460#else /* TEMPDIRNAMES */
7461
7462# ifdef WIN3264
7463 char szTempFile[_MAX_PATH + 1];
7464 char buf4[4];
7465 char_u *retval;
7466 char_u *p;
7467
7468 STRCPY(itmp, "");
7469 if (GetTempPath(_MAX_PATH, szTempFile) == 0)
7470 szTempFile[0] = NUL; /* GetTempPath() failed, use current dir */
7471 strcpy(buf4, "VIM");
7472 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
7473 if (GetTempFileName(szTempFile, buf4, 0, itmp) == 0)
7474 return NULL;
7475 /* GetTempFileName() will create the file, we don't want that */
7476 (void)DeleteFile(itmp);
7477
7478 /* Backslashes in a temp file name cause problems when filtering with
7479 * "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7480 * didn't set 'shellslash'. */
7481 retval = vim_strsave(itmp);
7482 if (*p_shcf == '-' || p_ssl)
7483 for (p = retval; *p; ++p)
7484 if (*p == '\\')
7485 *p = '/';
7486 return retval;
7487
7488# else /* WIN3264 */
7489
7490# ifdef USE_TMPNAM
7491 /* tmpnam() will make its own name */
7492 if (*tmpnam((char *)itmp) == NUL)
7493 return NULL;
7494# else
7495 char_u *p;
7496
7497# ifdef VMS_TEMPNAM
7498 /* mktemp() is not working on VMS. It seems to be
7499 * a do-nothing function. Therefore we use tempnam().
7500 */
7501 sprintf((char *)itmp, "VIM%c", extra_char);
7502 p = (char_u *)tempnam("tmp:", (char *)itmp);
7503 if (p != NULL)
7504 {
7505 /* VMS will use '.LOG' if we don't explicitly specify an extension,
7506 * and VIM will then be unable to find the file later */
7507 STRCPY(itmp, p);
7508 STRCAT(itmp, ".txt");
7509 free(p);
7510 }
7511 else
7512 return NULL;
7513# else
7514 STRCPY(itmp, TEMPNAME);
7515 if ((p = vim_strchr(itmp, '?')) != NULL)
7516 *p = extra_char;
7517 if (mktemp((char *)itmp) == NULL)
7518 return NULL;
7519# endif
7520# endif
7521
7522 return vim_strsave(itmp);
7523# endif /* WIN3264 */
7524#endif /* TEMPDIRNAMES */
7525}
7526
7527#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7528/*
7529 * Convert all backslashes in fname to forward slashes in-place.
7530 */
7531 void
7532forward_slash(fname)
7533 char_u *fname;
7534{
7535 char_u *p;
7536
7537 for (p = fname; *p != NUL; ++p)
7538# ifdef FEAT_MBYTE
7539 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007540 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007541 ++p;
7542 else
7543# endif
7544 if (*p == '\\')
7545 *p = '/';
7546}
7547#endif
7548
7549
7550/*
7551 * Code for automatic commands.
7552 *
7553 * Only included when "FEAT_AUTOCMD" has been defined.
7554 */
7555
7556#if defined(FEAT_AUTOCMD) || defined(PROTO)
7557
7558/*
7559 * The autocommands are stored in a list for each event.
7560 * Autocommands for the same pattern, that are consecutive, are joined
7561 * together, to avoid having to match the pattern too often.
7562 * The result is an array of Autopat lists, which point to AutoCmd lists:
7563 *
7564 * first_autopat[0] --> Autopat.next --> Autopat.next --> NULL
7565 * Autopat.cmds Autopat.cmds
7566 * | |
7567 * V V
7568 * AutoCmd.next AutoCmd.next
7569 * | |
7570 * V V
7571 * AutoCmd.next NULL
7572 * |
7573 * V
7574 * NULL
7575 *
7576 * first_autopat[1] --> Autopat.next --> NULL
7577 * Autopat.cmds
7578 * |
7579 * V
7580 * AutoCmd.next
7581 * |
7582 * V
7583 * NULL
7584 * etc.
7585 *
7586 * The order of AutoCmds is important, this is the order in which they were
7587 * defined and will have to be executed.
7588 */
7589typedef struct AutoCmd
7590{
7591 char_u *cmd; /* The command to be executed (NULL
7592 when command has been removed) */
7593 char nested; /* If autocommands nest here */
7594 char last; /* last command in list */
7595#ifdef FEAT_EVAL
7596 scid_T scriptID; /* script ID where defined */
7597#endif
7598 struct AutoCmd *next; /* Next AutoCmd in list */
7599} AutoCmd;
7600
7601typedef struct AutoPat
7602{
7603 int group; /* group ID */
7604 char_u *pat; /* pattern as typed (NULL when pattern
7605 has been removed) */
7606 int patlen; /* strlen() of pat */
Bram Moolenaar748bf032005-02-02 23:04:36 +00007607 regprog_T *reg_prog; /* compiled regprog for pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007608 char allow_dirs; /* Pattern may match whole path */
7609 char last; /* last pattern for apply_autocmds() */
7610 AutoCmd *cmds; /* list of commands to do */
7611 struct AutoPat *next; /* next AutoPat in AutoPat list */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007612 int buflocal_nr; /* !=0 for buffer-local AutoPat */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007613} AutoPat;
7614
7615static struct event_name
7616{
7617 char *name; /* event name */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007618 event_T event; /* event number */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007619} event_names[] =
7620{
7621 {"BufAdd", EVENT_BUFADD},
7622 {"BufCreate", EVENT_BUFADD},
7623 {"BufDelete", EVENT_BUFDELETE},
7624 {"BufEnter", EVENT_BUFENTER},
7625 {"BufFilePost", EVENT_BUFFILEPOST},
7626 {"BufFilePre", EVENT_BUFFILEPRE},
7627 {"BufHidden", EVENT_BUFHIDDEN},
7628 {"BufLeave", EVENT_BUFLEAVE},
7629 {"BufNew", EVENT_BUFNEW},
7630 {"BufNewFile", EVENT_BUFNEWFILE},
7631 {"BufRead", EVENT_BUFREADPOST},
7632 {"BufReadCmd", EVENT_BUFREADCMD},
7633 {"BufReadPost", EVENT_BUFREADPOST},
7634 {"BufReadPre", EVENT_BUFREADPRE},
7635 {"BufUnload", EVENT_BUFUNLOAD},
7636 {"BufWinEnter", EVENT_BUFWINENTER},
7637 {"BufWinLeave", EVENT_BUFWINLEAVE},
7638 {"BufWipeout", EVENT_BUFWIPEOUT},
7639 {"BufWrite", EVENT_BUFWRITEPRE},
7640 {"BufWritePost", EVENT_BUFWRITEPOST},
7641 {"BufWritePre", EVENT_BUFWRITEPRE},
7642 {"BufWriteCmd", EVENT_BUFWRITECMD},
7643 {"CmdwinEnter", EVENT_CMDWINENTER},
7644 {"CmdwinLeave", EVENT_CMDWINLEAVE},
Bram Moolenaarcfbc5ee2004-07-02 15:38:35 +00007645 {"ColorScheme", EVENT_COLORSCHEME},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007646 {"CursorHold", EVENT_CURSORHOLD},
7647 {"CursorHoldI", EVENT_CURSORHOLDI},
7648 {"CursorMoved", EVENT_CURSORMOVED},
7649 {"CursorMovedI", EVENT_CURSORMOVEDI},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007650 {"EncodingChanged", EVENT_ENCODINGCHANGED},
7651 {"FileEncoding", EVENT_ENCODINGCHANGED},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007652 {"FileAppendPost", EVENT_FILEAPPENDPOST},
7653 {"FileAppendPre", EVENT_FILEAPPENDPRE},
7654 {"FileAppendCmd", EVENT_FILEAPPENDCMD},
7655 {"FileChangedShell",EVENT_FILECHANGEDSHELL},
Bram Moolenaar56718732006-03-15 22:53:57 +00007656 {"FileChangedShellPost",EVENT_FILECHANGEDSHELLPOST},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007657 {"FileChangedRO", EVENT_FILECHANGEDRO},
7658 {"FileReadPost", EVENT_FILEREADPOST},
7659 {"FileReadPre", EVENT_FILEREADPRE},
7660 {"FileReadCmd", EVENT_FILEREADCMD},
7661 {"FileType", EVENT_FILETYPE},
7662 {"FileWritePost", EVENT_FILEWRITEPOST},
7663 {"FileWritePre", EVENT_FILEWRITEPRE},
7664 {"FileWriteCmd", EVENT_FILEWRITECMD},
7665 {"FilterReadPost", EVENT_FILTERREADPOST},
7666 {"FilterReadPre", EVENT_FILTERREADPRE},
7667 {"FilterWritePost", EVENT_FILTERWRITEPOST},
7668 {"FilterWritePre", EVENT_FILTERWRITEPRE},
7669 {"FocusGained", EVENT_FOCUSGAINED},
7670 {"FocusLost", EVENT_FOCUSLOST},
7671 {"FuncUndefined", EVENT_FUNCUNDEFINED},
7672 {"GUIEnter", EVENT_GUIENTER},
Bram Moolenaar265e5072006-08-29 16:13:22 +00007673 {"GUIFailed", EVENT_GUIFAILED},
Bram Moolenaar843ee412004-06-30 16:16:41 +00007674 {"InsertChange", EVENT_INSERTCHANGE},
7675 {"InsertEnter", EVENT_INSERTENTER},
7676 {"InsertLeave", EVENT_INSERTLEAVE},
Bram Moolenaara3ffd9c2005-07-21 21:03:15 +00007677 {"MenuPopup", EVENT_MENUPOPUP},
Bram Moolenaar7c626922005-02-07 22:01:03 +00007678 {"QuickFixCmdPost", EVENT_QUICKFIXCMDPOST},
7679 {"QuickFixCmdPre", EVENT_QUICKFIXCMDPRE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007680 {"RemoteReply", EVENT_REMOTEREPLY},
Bram Moolenaar9372a112005-12-06 19:59:18 +00007681 {"SessionLoadPost", EVENT_SESSIONLOADPOST},
Bram Moolenaar5c4bab02006-03-10 21:37:46 +00007682 {"ShellCmdPost", EVENT_SHELLCMDPOST},
7683 {"ShellFilterPost", EVENT_SHELLFILTERPOST},
Bram Moolenaara2031822006-03-07 22:29:51 +00007684 {"SourcePre", EVENT_SOURCEPRE},
Bram Moolenaar8dd1aa52007-01-16 20:33:19 +00007685 {"SourceCmd", EVENT_SOURCECMD},
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00007686 {"SpellFileMissing",EVENT_SPELLFILEMISSING},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007687 {"StdinReadPost", EVENT_STDINREADPOST},
7688 {"StdinReadPre", EVENT_STDINREADPRE},
Bram Moolenaarb815dac2005-12-07 20:59:24 +00007689 {"SwapExists", EVENT_SWAPEXISTS},
Bram Moolenaar7e8fd632006-02-18 22:14:51 +00007690 {"Syntax", EVENT_SYNTAX},
Bram Moolenaar70836c82006-02-20 21:28:49 +00007691 {"TabEnter", EVENT_TABENTER},
7692 {"TabLeave", EVENT_TABLEAVE},
Bram Moolenaar071d4272004-06-13 20:20:40 +00007693 {"TermChanged", EVENT_TERMCHANGED},
7694 {"TermResponse", EVENT_TERMRESPONSE},
7695 {"User", EVENT_USER},
7696 {"VimEnter", EVENT_VIMENTER},
7697 {"VimLeave", EVENT_VIMLEAVE},
7698 {"VimLeavePre", EVENT_VIMLEAVEPRE},
7699 {"WinEnter", EVENT_WINENTER},
7700 {"WinLeave", EVENT_WINLEAVE},
Bram Moolenaar56718732006-03-15 22:53:57 +00007701 {"VimResized", EVENT_VIMRESIZED},
Bram Moolenaar754b5602006-02-09 23:53:20 +00007702 {NULL, (event_T)0}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007703};
7704
7705static AutoPat *first_autopat[NUM_EVENTS] =
7706{
7707 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7708 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7709 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7710 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00007711 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
7712 NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007713};
7714
7715/*
7716 * struct used to keep status while executing autocommands for an event.
7717 */
7718typedef struct AutoPatCmd
7719{
7720 AutoPat *curpat; /* next AutoPat to examine */
7721 AutoCmd *nextcmd; /* next AutoCmd to execute */
7722 int group; /* group being used */
7723 char_u *fname; /* fname to match with */
7724 char_u *sfname; /* sfname to match with */
7725 char_u *tail; /* tail of fname */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007726 event_T event; /* current event */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007727 int arg_bufnr; /* initially equal to <abuf>, set to zero when
7728 buf is deleted */
7729 struct AutoPatCmd *next; /* chain of active apc-s for auto-invalidation*/
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730} AutoPatCmd;
7731
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007732static AutoPatCmd *active_apc_list = NULL; /* stack of active autocommands */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007733
Bram Moolenaar071d4272004-06-13 20:20:40 +00007734/*
7735 * augroups stores a list of autocmd group names.
7736 */
Bram Moolenaard6f676d2005-06-01 21:51:55 +00007737static garray_T augroups = {0, 0, sizeof(char_u *), 10, NULL};
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738#define AUGROUP_NAME(i) (((char_u **)augroups.ga_data)[i])
7739
7740/*
7741 * The ID of the current group. Group 0 is the default one.
7742 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007743static int current_augroup = AUGROUP_DEFAULT;
7744
7745static int au_need_clean = FALSE; /* need to delete marked patterns */
7746
Bram Moolenaar754b5602006-02-09 23:53:20 +00007747static void show_autocmd __ARGS((AutoPat *ap, event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007748static void au_remove_pat __ARGS((AutoPat *ap));
7749static void au_remove_cmds __ARGS((AutoPat *ap));
7750static void au_cleanup __ARGS((void));
7751static int au_new_group __ARGS((char_u *name));
7752static void au_del_group __ARGS((char_u *name));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007753static event_T event_name2nr __ARGS((char_u *start, char_u **end));
7754static char_u *event_nr2name __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007755static char_u *find_end_event __ARGS((char_u *arg, int have_group));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007756static int event_ignored __ARGS((event_T event));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007757static int au_get_grouparg __ARGS((char_u **argp));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007758static int do_autocmd_event __ARGS((event_T event, char_u *pat, int nested, char_u *cmd, int forceit, int group));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007759static char_u *getnextac __ARGS((int c, void *cookie, int indent));
Bram Moolenaar754b5602006-02-09 23:53:20 +00007760static 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 +00007761static void auto_next_pat __ARGS((AutoPatCmd *apc, int stop_at_last));
7762
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007763
Bram Moolenaar754b5602006-02-09 23:53:20 +00007764static event_T last_event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007765static int last_group;
Bram Moolenaar78ab3312007-09-29 12:16:41 +00007766static int autocmd_blocked = 0; /* block all autocmds */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007767
7768/*
7769 * Show the autocommands for one AutoPat.
7770 */
7771 static void
7772show_autocmd(ap, event)
7773 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007774 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007775{
7776 AutoCmd *ac;
7777
7778 /* Check for "got_int" (here and at various places below), which is set
7779 * when "q" has been hit for the "--more--" prompt */
7780 if (got_int)
7781 return;
7782 if (ap->pat == NULL) /* pattern has been removed */
7783 return;
7784
7785 msg_putchar('\n');
7786 if (got_int)
7787 return;
7788 if (event != last_event || ap->group != last_group)
7789 {
7790 if (ap->group != AUGROUP_DEFAULT)
7791 {
7792 if (AUGROUP_NAME(ap->group) == NULL)
7793 msg_puts_attr((char_u *)_("--Deleted--"), hl_attr(HLF_E));
7794 else
7795 msg_puts_attr(AUGROUP_NAME(ap->group), hl_attr(HLF_T));
7796 msg_puts((char_u *)" ");
7797 }
7798 msg_puts_attr(event_nr2name(event), hl_attr(HLF_T));
7799 last_event = event;
7800 last_group = ap->group;
7801 msg_putchar('\n');
7802 if (got_int)
7803 return;
7804 }
7805 msg_col = 4;
7806 msg_outtrans(ap->pat);
7807
7808 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7809 {
7810 if (ac->cmd != NULL) /* skip removed commands */
7811 {
7812 if (msg_col >= 14)
7813 msg_putchar('\n');
7814 msg_col = 14;
7815 if (got_int)
7816 return;
7817 msg_outtrans(ac->cmd);
Bram Moolenaarac6e65f2005-08-29 22:25:38 +00007818#ifdef FEAT_EVAL
7819 if (p_verbose > 0)
7820 last_set_msg(ac->scriptID);
7821#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007822 if (got_int)
7823 return;
7824 if (ac->next != NULL)
7825 {
7826 msg_putchar('\n');
7827 if (got_int)
7828 return;
7829 }
7830 }
7831 }
7832}
7833
7834/*
7835 * Mark an autocommand pattern for deletion.
7836 */
7837 static void
7838au_remove_pat(ap)
7839 AutoPat *ap;
7840{
7841 vim_free(ap->pat);
7842 ap->pat = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007843 ap->buflocal_nr = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007844 au_need_clean = TRUE;
7845}
7846
7847/*
7848 * Mark all commands for a pattern for deletion.
7849 */
7850 static void
7851au_remove_cmds(ap)
7852 AutoPat *ap;
7853{
7854 AutoCmd *ac;
7855
7856 for (ac = ap->cmds; ac != NULL; ac = ac->next)
7857 {
7858 vim_free(ac->cmd);
7859 ac->cmd = NULL;
7860 }
7861 au_need_clean = TRUE;
7862}
7863
7864/*
7865 * Cleanup autocommands and patterns that have been deleted.
7866 * This is only done when not executing autocommands.
7867 */
7868 static void
7869au_cleanup()
7870{
7871 AutoPat *ap, **prev_ap;
7872 AutoCmd *ac, **prev_ac;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007873 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007874
7875 if (autocmd_busy || !au_need_clean)
7876 return;
7877
7878 /* loop over all events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007879 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7880 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007881 {
7882 /* loop over all autocommand patterns */
7883 prev_ap = &(first_autopat[(int)event]);
7884 for (ap = *prev_ap; ap != NULL; ap = *prev_ap)
7885 {
7886 /* loop over all commands for this pattern */
7887 prev_ac = &(ap->cmds);
7888 for (ac = *prev_ac; ac != NULL; ac = *prev_ac)
7889 {
7890 /* remove the command if the pattern is to be deleted or when
7891 * the command has been marked for deletion */
7892 if (ap->pat == NULL || ac->cmd == NULL)
7893 {
7894 *prev_ac = ac->next;
7895 vim_free(ac->cmd);
7896 vim_free(ac);
7897 }
7898 else
7899 prev_ac = &(ac->next);
7900 }
7901
7902 /* remove the pattern if it has been marked for deletion */
7903 if (ap->pat == NULL)
7904 {
7905 *prev_ap = ap->next;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007906 vim_free(ap->reg_prog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007907 vim_free(ap);
7908 }
7909 else
7910 prev_ap = &(ap->next);
7911 }
7912 }
7913
7914 au_need_clean = FALSE;
7915}
7916
7917/*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007918 * Called when buffer is freed, to remove/invalidate related buffer-local
7919 * autocmds.
7920 */
7921 void
7922aubuflocal_remove(buf)
7923 buf_T *buf;
7924{
7925 AutoPat *ap;
Bram Moolenaar754b5602006-02-09 23:53:20 +00007926 event_T event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007927 AutoPatCmd *apc;
7928
7929 /* invalidate currently executing autocommands */
7930 for (apc = active_apc_list; apc; apc = apc->next)
7931 if (buf->b_fnum == apc->arg_bufnr)
7932 apc->arg_bufnr = 0;
7933
7934 /* invalidate buflocals looping through events */
Bram Moolenaar754b5602006-02-09 23:53:20 +00007935 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
7936 event = (event_T)((int)event + 1))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007937 /* loop over all autocommand patterns */
7938 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
7939 if (ap->buflocal_nr == buf->b_fnum)
7940 {
7941 au_remove_pat(ap);
7942 if (p_verbose >= 6)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007943 {
7944 verbose_enter();
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007945 smsg((char_u *)
7946 _("auto-removing autocommand: %s <buffer=%d>"),
7947 event_nr2name(event), buf->b_fnum);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00007948 verbose_leave();
7949 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00007950 }
7951 au_cleanup();
7952}
7953
7954/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007955 * Add an autocmd group name.
7956 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
7957 */
7958 static int
7959au_new_group(name)
7960 char_u *name;
7961{
7962 int i;
7963
7964 i = au_find_group(name);
7965 if (i == AUGROUP_ERROR) /* the group doesn't exist yet, add it */
7966 {
7967 /* First try using a free entry. */
7968 for (i = 0; i < augroups.ga_len; ++i)
7969 if (AUGROUP_NAME(i) == NULL)
7970 break;
7971 if (i == augroups.ga_len && ga_grow(&augroups, 1) == FAIL)
7972 return AUGROUP_ERROR;
7973
7974 AUGROUP_NAME(i) = vim_strsave(name);
7975 if (AUGROUP_NAME(i) == NULL)
7976 return AUGROUP_ERROR;
7977 if (i == augroups.ga_len)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007978 ++augroups.ga_len;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007979 }
7980
7981 return i;
7982}
7983
7984 static void
7985au_del_group(name)
7986 char_u *name;
7987{
7988 int i;
7989
7990 i = au_find_group(name);
7991 if (i == AUGROUP_ERROR) /* the group doesn't exist */
7992 EMSG2(_("E367: No such group: \"%s\""), name);
7993 else
7994 {
7995 vim_free(AUGROUP_NAME(i));
7996 AUGROUP_NAME(i) = NULL;
7997 }
7998}
7999
8000/*
8001 * Find the ID of an autocmd group name.
8002 * Return it's ID. Returns AUGROUP_ERROR (< 0) for error.
8003 */
8004 static int
8005au_find_group(name)
8006 char_u *name;
8007{
8008 int i;
8009
8010 for (i = 0; i < augroups.ga_len; ++i)
8011 if (AUGROUP_NAME(i) != NULL && STRCMP(AUGROUP_NAME(i), name) == 0)
8012 return i;
8013 return AUGROUP_ERROR;
8014}
8015
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008016/*
8017 * Return TRUE if augroup "name" exists.
8018 */
8019 int
8020au_has_group(name)
8021 char_u *name;
8022{
8023 return au_find_group(name) != AUGROUP_ERROR;
8024}
Bram Moolenaar1d94f9b2005-08-04 21:29:45 +00008025
Bram Moolenaar071d4272004-06-13 20:20:40 +00008026/*
8027 * ":augroup {name}".
8028 */
8029 void
8030do_augroup(arg, del_group)
8031 char_u *arg;
8032 int del_group;
8033{
8034 int i;
8035
8036 if (del_group)
8037 {
8038 if (*arg == NUL)
8039 EMSG(_(e_argreq));
8040 else
8041 au_del_group(arg);
8042 }
8043 else if (STRICMP(arg, "end") == 0) /* ":aug end": back to group 0 */
8044 current_augroup = AUGROUP_DEFAULT;
8045 else if (*arg) /* ":aug xxx": switch to group xxx */
8046 {
8047 i = au_new_group(arg);
8048 if (i != AUGROUP_ERROR)
8049 current_augroup = i;
8050 }
8051 else /* ":aug": list the group names */
8052 {
8053 msg_start();
8054 for (i = 0; i < augroups.ga_len; ++i)
8055 {
8056 if (AUGROUP_NAME(i) != NULL)
8057 {
8058 msg_puts(AUGROUP_NAME(i));
8059 msg_puts((char_u *)" ");
8060 }
8061 }
8062 msg_clr_eos();
8063 msg_end();
8064 }
8065}
8066
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008067#if defined(EXITFREE) || defined(PROTO)
8068 void
8069free_all_autocmds()
8070{
8071 for (current_augroup = -1; current_augroup < augroups.ga_len;
8072 ++current_augroup)
8073 do_autocmd((char_u *)"", TRUE);
8074 ga_clear_strings(&augroups);
8075}
8076#endif
8077
Bram Moolenaar071d4272004-06-13 20:20:40 +00008078/*
8079 * Return the event number for event name "start".
8080 * Return NUM_EVENTS if the event name was not found.
8081 * Return a pointer to the next event name in "end".
8082 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008083 static event_T
Bram Moolenaar071d4272004-06-13 20:20:40 +00008084event_name2nr(start, end)
8085 char_u *start;
8086 char_u **end;
8087{
8088 char_u *p;
8089 int i;
8090 int len;
8091
8092 /* the event name ends with end of line, a blank or a comma */
8093 for (p = start; *p && !vim_iswhite(*p) && *p != ','; ++p)
8094 ;
8095 for (i = 0; event_names[i].name != NULL; ++i)
8096 {
8097 len = (int)STRLEN(event_names[i].name);
8098 if (len == p - start && STRNICMP(event_names[i].name, start, len) == 0)
8099 break;
8100 }
8101 if (*p == ',')
8102 ++p;
8103 *end = p;
8104 if (event_names[i].name == NULL)
8105 return NUM_EVENTS;
8106 return event_names[i].event;
8107}
8108
8109/*
8110 * Return the name for event "event".
8111 */
8112 static char_u *
8113event_nr2name(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008114 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008115{
8116 int i;
8117
8118 for (i = 0; event_names[i].name != NULL; ++i)
8119 if (event_names[i].event == event)
8120 return (char_u *)event_names[i].name;
8121 return (char_u *)"Unknown";
8122}
8123
8124/*
8125 * Scan over the events. "*" stands for all events.
8126 */
8127 static char_u *
8128find_end_event(arg, have_group)
8129 char_u *arg;
8130 int have_group; /* TRUE when group name was found */
8131{
8132 char_u *pat;
8133 char_u *p;
8134
8135 if (*arg == '*')
8136 {
8137 if (arg[1] && !vim_iswhite(arg[1]))
8138 {
8139 EMSG2(_("E215: Illegal character after *: %s"), arg);
8140 return NULL;
8141 }
8142 pat = arg + 1;
8143 }
8144 else
8145 {
8146 for (pat = arg; *pat && !vim_iswhite(*pat); pat = p)
8147 {
8148 if ((int)event_name2nr(pat, &p) >= (int)NUM_EVENTS)
8149 {
8150 if (have_group)
8151 EMSG2(_("E216: No such event: %s"), pat);
8152 else
8153 EMSG2(_("E216: No such group or event: %s"), pat);
8154 return NULL;
8155 }
8156 }
8157 }
8158 return pat;
8159}
8160
8161/*
8162 * Return TRUE if "event" is included in 'eventignore'.
8163 */
8164 static int
8165event_ignored(event)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008166 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008167{
8168 char_u *p = p_ei;
8169
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008170 while (*p != NUL)
8171 {
8172 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8173 return TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008174 if (event_name2nr(p, &p) == event)
8175 return TRUE;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008176 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008177
8178 return FALSE;
8179}
8180
8181/*
8182 * Return OK when the contents of p_ei is valid, FAIL otherwise.
8183 */
8184 int
8185check_ei()
8186{
8187 char_u *p = p_ei;
8188
Bram Moolenaar071d4272004-06-13 20:20:40 +00008189 while (*p)
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008190 {
8191 if (STRNICMP(p, "all", 3) == 0 && (p[3] == NUL || p[3] == ','))
8192 {
8193 p += 3;
8194 if (*p == ',')
8195 ++p;
8196 }
8197 else if (event_name2nr(p, &p) == NUM_EVENTS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008198 return FAIL;
Bram Moolenaarf193fff2006-04-27 00:02:13 +00008199 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008200
8201 return OK;
8202}
8203
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008204# if defined(FEAT_SYN_HL) || defined(PROTO)
8205
8206/*
8207 * Add "what" to 'eventignore' to skip loading syntax highlighting for every
8208 * buffer loaded into the window. "what" must start with a comma.
8209 * Returns the old value of 'eventignore' in allocated memory.
8210 */
8211 char_u *
8212au_event_disable(what)
8213 char *what;
8214{
8215 char_u *new_ei;
8216 char_u *save_ei;
8217
8218 save_ei = vim_strsave(p_ei);
8219 if (save_ei != NULL)
8220 {
Bram Moolenaara5792f52005-11-23 21:25:05 +00008221 new_ei = vim_strnsave(p_ei, (int)(STRLEN(p_ei) + STRLEN(what)));
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008222 if (new_ei != NULL)
8223 {
Bram Moolenaar8cac9fd2010-03-02 12:48:05 +01008224 if (*what == ',' && *p_ei == NUL)
8225 STRCPY(new_ei, what + 1);
8226 else
8227 STRCAT(new_ei, what);
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008228 set_string_option_direct((char_u *)"ei", -1, new_ei,
8229 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008230 vim_free(new_ei);
8231 }
8232 }
8233 return save_ei;
8234}
8235
8236 void
8237au_event_restore(old_ei)
8238 char_u *old_ei;
8239{
8240 if (old_ei != NULL)
8241 {
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00008242 set_string_option_direct((char_u *)"ei", -1, old_ei,
8243 OPT_FREE, SID_NONE);
Bram Moolenaardcaf10e2005-01-21 11:55:25 +00008244 vim_free(old_ei);
8245 }
8246}
8247# endif /* FEAT_SYN_HL */
8248
Bram Moolenaar071d4272004-06-13 20:20:40 +00008249/*
8250 * do_autocmd() -- implements the :autocmd command. Can be used in the
8251 * following ways:
8252 *
8253 * :autocmd <event> <pat> <cmd> Add <cmd> to the list of commands that
8254 * will be automatically executed for <event>
8255 * when editing a file matching <pat>, in
8256 * the current group.
8257 * :autocmd <event> <pat> Show the auto-commands associated with
8258 * <event> and <pat>.
8259 * :autocmd <event> Show the auto-commands associated with
8260 * <event>.
8261 * :autocmd Show all auto-commands.
8262 * :autocmd! <event> <pat> <cmd> Remove all auto-commands associated with
8263 * <event> and <pat>, and add the command
8264 * <cmd>, for the current group.
8265 * :autocmd! <event> <pat> Remove all auto-commands associated with
8266 * <event> and <pat> for the current group.
8267 * :autocmd! <event> Remove all auto-commands associated with
8268 * <event> for the current group.
8269 * :autocmd! Remove ALL auto-commands for the current
8270 * group.
8271 *
8272 * Multiple events and patterns may be given separated by commas. Here are
8273 * some examples:
8274 * :autocmd bufread,bufenter *.c,*.h set tw=0 smartindent noic
8275 * :autocmd bufleave * set tw=79 nosmartindent ic infercase
8276 *
8277 * :autocmd * *.c show all autocommands for *.c files.
Bram Moolenaard35f9712005-12-18 22:02:33 +00008278 *
8279 * Mostly a {group} argument can optionally appear before <event>.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008280 */
8281 void
8282do_autocmd(arg, forceit)
8283 char_u *arg;
8284 int forceit;
8285{
8286 char_u *pat;
8287 char_u *envpat = NULL;
8288 char_u *cmd;
Bram Moolenaar754b5602006-02-09 23:53:20 +00008289 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008290 int need_free = FALSE;
8291 int nested = FALSE;
8292 int group;
8293
8294 /*
8295 * Check for a legal group name. If not, use AUGROUP_ALL.
8296 */
8297 group = au_get_grouparg(&arg);
8298 if (arg == NULL) /* out of memory */
8299 return;
8300
8301 /*
8302 * Scan over the events.
8303 * If we find an illegal name, return here, don't do anything.
8304 */
8305 pat = find_end_event(arg, group != AUGROUP_ALL);
8306 if (pat == NULL)
8307 return;
8308
8309 /*
8310 * Scan over the pattern. Put a NUL at the end.
8311 */
8312 pat = skipwhite(pat);
8313 cmd = pat;
8314 while (*cmd && (!vim_iswhite(*cmd) || cmd[-1] == '\\'))
8315 cmd++;
8316 if (*cmd)
8317 *cmd++ = NUL;
8318
8319 /* Expand environment variables in the pattern. Set 'shellslash', we want
8320 * forward slashes here. */
8321 if (vim_strchr(pat, '$') != NULL || vim_strchr(pat, '~') != NULL)
8322 {
8323#ifdef BACKSLASH_IN_FILENAME
8324 int p_ssl_save = p_ssl;
8325
8326 p_ssl = TRUE;
8327#endif
8328 envpat = expand_env_save(pat);
8329#ifdef BACKSLASH_IN_FILENAME
8330 p_ssl = p_ssl_save;
8331#endif
8332 if (envpat != NULL)
8333 pat = envpat;
8334 }
8335
8336 /*
8337 * Check for "nested" flag.
8338 */
8339 cmd = skipwhite(cmd);
8340 if (*cmd != NUL && STRNCMP(cmd, "nested", 6) == 0 && vim_iswhite(cmd[6]))
8341 {
8342 nested = TRUE;
8343 cmd = skipwhite(cmd + 6);
8344 }
8345
8346 /*
8347 * Find the start of the commands.
8348 * Expand <sfile> in it.
8349 */
8350 if (*cmd != NUL)
8351 {
8352 cmd = expand_sfile(cmd);
8353 if (cmd == NULL) /* some error */
8354 return;
8355 need_free = TRUE;
8356 }
8357
8358 /*
8359 * Print header when showing autocommands.
8360 */
8361 if (!forceit && *cmd == NUL)
8362 {
8363 /* Highlight title */
8364 MSG_PUTS_TITLE(_("\n--- Auto-Commands ---"));
8365 }
8366
8367 /*
8368 * Loop over the events.
8369 */
Bram Moolenaar754b5602006-02-09 23:53:20 +00008370 last_event = (event_T)-1; /* for listing the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008371 last_group = AUGROUP_ERROR; /* for listing the group name */
8372 if (*arg == '*' || *arg == NUL)
8373 {
Bram Moolenaar754b5602006-02-09 23:53:20 +00008374 for (event = (event_T)0; (int)event < (int)NUM_EVENTS;
8375 event = (event_T)((int)event + 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00008376 if (do_autocmd_event(event, pat,
8377 nested, cmd, forceit, group) == FAIL)
8378 break;
8379 }
8380 else
8381 {
8382 while (*arg && !vim_iswhite(*arg))
8383 if (do_autocmd_event(event_name2nr(arg, &arg), pat,
8384 nested, cmd, forceit, group) == FAIL)
8385 break;
8386 }
8387
8388 if (need_free)
8389 vim_free(cmd);
8390 vim_free(envpat);
8391}
8392
8393/*
8394 * Find the group ID in a ":autocmd" or ":doautocmd" argument.
8395 * The "argp" argument is advanced to the following argument.
8396 *
8397 * Returns the group ID, AUGROUP_ERROR for error (out of memory).
8398 */
8399 static int
8400au_get_grouparg(argp)
8401 char_u **argp;
8402{
8403 char_u *group_name;
8404 char_u *p;
8405 char_u *arg = *argp;
8406 int group = AUGROUP_ALL;
8407
8408 p = skiptowhite(arg);
8409 if (p > arg)
8410 {
8411 group_name = vim_strnsave(arg, (int)(p - arg));
8412 if (group_name == NULL) /* out of memory */
8413 return AUGROUP_ERROR;
8414 group = au_find_group(group_name);
8415 if (group == AUGROUP_ERROR)
8416 group = AUGROUP_ALL; /* no match, use all groups */
8417 else
8418 *argp = skipwhite(p); /* match, skip over group name */
8419 vim_free(group_name);
8420 }
8421 return group;
8422}
8423
8424/*
8425 * do_autocmd() for one event.
8426 * If *pat == NUL do for all patterns.
8427 * If *cmd == NUL show entries.
8428 * If forceit == TRUE delete entries.
8429 * If group is not AUGROUP_ALL, only use this group.
8430 */
8431 static int
8432do_autocmd_event(event, pat, nested, cmd, forceit, group)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008433 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008434 char_u *pat;
8435 int nested;
8436 char_u *cmd;
8437 int forceit;
8438 int group;
8439{
8440 AutoPat *ap;
8441 AutoPat **prev_ap;
8442 AutoCmd *ac;
8443 AutoCmd **prev_ac;
8444 int brace_level;
8445 char_u *endpat;
8446 int findgroup;
8447 int allgroups;
8448 int patlen;
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00008449 int is_buflocal;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008450 int buflocal_nr;
8451 char_u buflocal_pat[25]; /* for "<buffer=X>" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008452
8453 if (group == AUGROUP_ALL)
8454 findgroup = current_augroup;
8455 else
8456 findgroup = group;
8457 allgroups = (group == AUGROUP_ALL && !forceit && *cmd == NUL);
8458
8459 /*
8460 * Show or delete all patterns for an event.
8461 */
8462 if (*pat == NUL)
8463 {
8464 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
8465 {
8466 if (forceit) /* delete the AutoPat, if it's in the current group */
8467 {
8468 if (ap->group == findgroup)
8469 au_remove_pat(ap);
8470 }
8471 else if (group == AUGROUP_ALL || ap->group == group)
8472 show_autocmd(ap, event);
8473 }
8474 }
8475
8476 /*
8477 * Loop through all the specified patterns.
8478 */
8479 for ( ; *pat; pat = (*endpat == ',' ? endpat + 1 : endpat))
8480 {
8481 /*
8482 * Find end of the pattern.
8483 * Watch out for a comma in braces, like "*.\{obj,o\}".
8484 */
8485 brace_level = 0;
8486 for (endpat = pat; *endpat && (*endpat != ',' || brace_level
8487 || endpat[-1] == '\\'); ++endpat)
8488 {
8489 if (*endpat == '{')
8490 brace_level++;
8491 else if (*endpat == '}')
8492 brace_level--;
8493 }
8494 if (pat == endpat) /* ignore single comma */
8495 continue;
8496 patlen = (int)(endpat - pat);
8497
8498 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008499 * detect special <buflocal[=X]> buffer-local patterns
8500 */
8501 is_buflocal = FALSE;
8502 buflocal_nr = 0;
8503
8504 if (patlen >= 7 && STRNCMP(pat, "<buffer", 7) == 0
8505 && pat[patlen - 1] == '>')
8506 {
8507 /* Error will be printed only for addition. printing and removing
8508 * will proceed silently. */
8509 is_buflocal = TRUE;
8510 if (patlen == 8)
8511 buflocal_nr = curbuf->b_fnum;
8512 else if (patlen > 9 && pat[7] == '=')
8513 {
8514 /* <buffer=abuf> */
8515 if (patlen == 13 && STRNICMP(pat, "<buffer=abuf>", 13))
8516 buflocal_nr = autocmd_bufnr;
8517 /* <buffer=123> */
8518 else if (skipdigits(pat + 8) == pat + patlen - 1)
8519 buflocal_nr = atoi((char *)pat + 8);
8520 }
8521 }
8522
8523 if (is_buflocal)
8524 {
8525 /* normalize pat into standard "<buffer>#N" form */
8526 sprintf((char *)buflocal_pat, "<buffer=%d>", buflocal_nr);
8527 pat = buflocal_pat; /* can modify pat and patlen */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00008528 patlen = (int)STRLEN(buflocal_pat); /* but not endpat */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008529 }
8530
8531 /*
Bram Moolenaar071d4272004-06-13 20:20:40 +00008532 * Find AutoPat entries with this pattern.
8533 */
8534 prev_ap = &first_autopat[(int)event];
8535 while ((ap = *prev_ap) != NULL)
8536 {
8537 if (ap->pat != NULL)
8538 {
8539 /* Accept a pattern when:
8540 * - a group was specified and it's that group, or a group was
8541 * not specified and it's the current group, or a group was
8542 * not specified and we are listing
8543 * - the length of the pattern matches
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008544 * - the pattern matches.
8545 * For <buffer[=X]>, this condition works because we normalize
8546 * all buffer-local patterns.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008547 */
8548 if ((allgroups || ap->group == findgroup)
8549 && ap->patlen == patlen
8550 && STRNCMP(pat, ap->pat, patlen) == 0)
8551 {
8552 /*
8553 * Remove existing autocommands.
8554 * If adding any new autocmd's for this AutoPat, don't
8555 * delete the pattern from the autopat list, append to
8556 * this list.
8557 */
8558 if (forceit)
8559 {
8560 if (*cmd != NUL && ap->next == NULL)
8561 {
8562 au_remove_cmds(ap);
8563 break;
8564 }
8565 au_remove_pat(ap);
8566 }
8567
8568 /*
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008569 * Show autocmd's for this autopat, or buflocals <buffer=X>
Bram Moolenaar071d4272004-06-13 20:20:40 +00008570 */
8571 else if (*cmd == NUL)
8572 show_autocmd(ap, event);
8573
8574 /*
8575 * Add autocmd to this autopat, if it's the last one.
8576 */
8577 else if (ap->next == NULL)
8578 break;
8579 }
8580 }
8581 prev_ap = &ap->next;
8582 }
8583
8584 /*
8585 * Add a new command.
8586 */
8587 if (*cmd != NUL)
8588 {
8589 /*
8590 * If the pattern we want to add a command to does appear at the
8591 * end of the list (or not is not in the list at all), add the
8592 * pattern at the end of the list.
8593 */
8594 if (ap == NULL)
8595 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008596 /* refuse to add buffer-local ap if buffer number is invalid */
8597 if (is_buflocal && (buflocal_nr == 0
8598 || buflist_findnr(buflocal_nr) == NULL))
8599 {
8600 EMSGN(_("E680: <buffer=%d>: invalid buffer number "),
8601 buflocal_nr);
8602 return FAIL;
8603 }
8604
Bram Moolenaar071d4272004-06-13 20:20:40 +00008605 ap = (AutoPat *)alloc((unsigned)sizeof(AutoPat));
8606 if (ap == NULL)
8607 return FAIL;
8608 ap->pat = vim_strnsave(pat, patlen);
8609 ap->patlen = patlen;
8610 if (ap->pat == NULL)
8611 {
8612 vim_free(ap);
8613 return FAIL;
8614 }
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008615
8616 if (is_buflocal)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008617 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008618 ap->buflocal_nr = buflocal_nr;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008619 ap->reg_prog = NULL;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008620 }
8621 else
8622 {
Bram Moolenaar748bf032005-02-02 23:04:36 +00008623 char_u *reg_pat;
8624
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008625 ap->buflocal_nr = 0;
Bram Moolenaar748bf032005-02-02 23:04:36 +00008626 reg_pat = file_pat_to_reg_pat(pat, endpat,
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008627 &ap->allow_dirs, TRUE);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008628 if (reg_pat != NULL)
8629 ap->reg_prog = vim_regcomp(reg_pat, RE_MAGIC);
Bram Moolenaar0a5fe212005-06-24 23:01:23 +00008630 vim_free(reg_pat);
Bram Moolenaar748bf032005-02-02 23:04:36 +00008631 if (reg_pat == NULL || ap->reg_prog == NULL)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00008632 {
8633 vim_free(ap->pat);
8634 vim_free(ap);
8635 return FAIL;
8636 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008637 }
8638 ap->cmds = NULL;
8639 *prev_ap = ap;
8640 ap->next = NULL;
8641 if (group == AUGROUP_ALL)
8642 ap->group = current_augroup;
8643 else
8644 ap->group = group;
8645 }
8646
8647 /*
8648 * Add the autocmd at the end of the AutoCmd list.
8649 */
8650 prev_ac = &(ap->cmds);
8651 while ((ac = *prev_ac) != NULL)
8652 prev_ac = &ac->next;
8653 ac = (AutoCmd *)alloc((unsigned)sizeof(AutoCmd));
8654 if (ac == NULL)
8655 return FAIL;
8656 ac->cmd = vim_strsave(cmd);
8657#ifdef FEAT_EVAL
8658 ac->scriptID = current_SID;
8659#endif
8660 if (ac->cmd == NULL)
8661 {
8662 vim_free(ac);
8663 return FAIL;
8664 }
8665 ac->next = NULL;
8666 *prev_ac = ac;
8667 ac->nested = nested;
8668 }
8669 }
8670
8671 au_cleanup(); /* may really delete removed patterns/commands now */
8672 return OK;
8673}
8674
8675/*
8676 * Implementation of ":doautocmd [group] event [fname]".
8677 * Return OK for success, FAIL for failure;
8678 */
8679 int
8680do_doautocmd(arg, do_msg)
8681 char_u *arg;
8682 int do_msg; /* give message for no matching autocmds? */
8683{
8684 char_u *fname;
8685 int nothing_done = TRUE;
8686 int group;
8687
8688 /*
8689 * Check for a legal group name. If not, use AUGROUP_ALL.
8690 */
8691 group = au_get_grouparg(&arg);
8692 if (arg == NULL) /* out of memory */
8693 return FAIL;
8694
8695 if (*arg == '*')
8696 {
8697 EMSG(_("E217: Can't execute autocommands for ALL events"));
8698 return FAIL;
8699 }
8700
8701 /*
8702 * Scan over the events.
8703 * If we find an illegal name, return here, don't do anything.
8704 */
8705 fname = find_end_event(arg, group != AUGROUP_ALL);
8706 if (fname == NULL)
8707 return FAIL;
8708
8709 fname = skipwhite(fname);
8710
8711 /*
8712 * Loop over the events.
8713 */
8714 while (*arg && !vim_iswhite(*arg))
8715 if (apply_autocmds_group(event_name2nr(arg, &arg),
8716 fname, NULL, TRUE, group, curbuf, NULL))
8717 nothing_done = FALSE;
8718
8719 if (nothing_done && do_msg)
8720 MSG(_("No matching autocommands"));
8721
8722#ifdef FEAT_EVAL
8723 return aborting() ? FAIL : OK;
8724#else
8725 return OK;
8726#endif
8727}
8728
8729/*
8730 * ":doautoall": execute autocommands for each loaded buffer.
8731 */
8732 void
8733ex_doautoall(eap)
8734 exarg_T *eap;
8735{
8736 int retval;
8737 aco_save_T aco;
8738 buf_T *buf;
8739
8740 /*
8741 * This is a bit tricky: For some commands curwin->w_buffer needs to be
8742 * equal to curbuf, but for some buffers there may not be a window.
8743 * So we change the buffer for the current window for a moment. This
8744 * gives problems when the autocommands make changes to the list of
8745 * buffers or windows...
8746 */
8747 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
8748 {
Bram Moolenaar3a847972008-07-08 09:36:58 +00008749 if (buf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008750 {
8751 /* find a window for this buffer and save some values */
8752 aucmd_prepbuf(&aco, buf);
8753
8754 /* execute the autocommands for this buffer */
8755 retval = do_doautocmd(eap->arg, FALSE);
Bram Moolenaareeefcc72007-05-01 21:21:21 +00008756
8757 /* Execute the modeline settings, but don't set window-local
8758 * options if we are using the current window for another buffer. */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008759 do_modelines(curwin == aucmd_win ? OPT_NOWIN : 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00008760
8761 /* restore the current window */
8762 aucmd_restbuf(&aco);
8763
8764 /* stop if there is some error or buffer was deleted */
8765 if (retval == FAIL || !buf_valid(buf))
8766 break;
8767 }
8768 }
8769
8770 check_cursor(); /* just in case lines got deleted */
8771}
8772
8773/*
8774 * Prepare for executing autocommands for (hidden) buffer "buf".
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008775 * Search for a visible window containing the current buffer. If there isn't
8776 * one then use "aucmd_win".
Bram Moolenaar071d4272004-06-13 20:20:40 +00008777 * Set "curbuf" and "curwin" to match "buf".
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008778 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008779 */
8780 void
8781aucmd_prepbuf(aco, buf)
8782 aco_save_T *aco; /* structure to save values in */
8783 buf_T *buf; /* new curbuf */
8784{
8785 win_T *win;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008786#ifdef FEAT_WINDOWS
8787 int save_ea;
8788#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00008789
8790 /* Find a window that is for the new buffer */
8791 if (buf == curbuf) /* be quick when buf is curbuf */
8792 win = curwin;
8793 else
8794#ifdef FEAT_WINDOWS
8795 for (win = firstwin; win != NULL; win = win->w_next)
8796 if (win->w_buffer == buf)
8797 break;
8798#else
8799 win = NULL;
8800#endif
8801
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008802 /* Allocate "aucmd_win" when needed. If this fails (out of memory) fall
8803 * back to using the current window. */
8804 if (win == NULL && aucmd_win == NULL)
8805 {
8806 win_alloc_aucmd_win();
8807 if (aucmd_win == NULL)
8808 win = curwin;
8809 }
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008810 if (win == NULL && aucmd_win_used)
8811 /* Strange recursive autocommand, fall back to using the current
8812 * window. Expect a few side effects... */
8813 win = curwin;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008814
8815 aco->save_curwin = curwin;
8816 aco->save_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008817 if (win != NULL)
8818 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008819 /* There is a window for "buf" in the current tab page, make it the
8820 * curwin. This is preferred, it has the least side effects (esp. if
8821 * "buf" is curbuf). */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008822 aco->use_aucmd_win = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008823 curwin = win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008824 }
8825 else
8826 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008827 /* There is no window for "buf", use "aucmd_win". To minimize the side
8828 * effects, insert it in a the current tab page.
8829 * Anything related to a window (e.g., setting folds) may have
8830 * unexpected results. */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008831 aco->use_aucmd_win = TRUE;
8832 aucmd_win_used = TRUE;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008833 aucmd_win->w_buffer = buf;
Bram Moolenaarcdddaa42010-06-07 23:07:44 +02008834 aucmd_win->w_s = &buf->b_s;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008835 ++buf->b_nwindows;
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008836 win_init_empty(aucmd_win); /* set cursor and topline to safe values */
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008837 vim_free(aucmd_win->w_localdir);
8838 aucmd_win->w_localdir = NULL;
8839
8840 /* Make sure w_localdir and globaldir are NULL to avoid a chdir() in
8841 * win_enter_ext(). */
8842 aucmd_win->w_localdir = NULL;
8843 aco->globaldir = globaldir;
8844 globaldir = NULL;
8845
Bram Moolenaar071d4272004-06-13 20:20:40 +00008846
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008847#ifdef FEAT_WINDOWS
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008848 /* Split the current window, put the aucmd_win in the upper half.
8849 * We don't want the BufEnter or WinEnter autocommands. */
8850 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008851 make_snapshot(SNAP_AUCMD_IDX);
8852 save_ea = p_ea;
8853 p_ea = FALSE;
8854 (void)win_split_ins(0, WSP_TOP, aucmd_win, 0);
8855 (void)win_comp_pos(); /* recompute window positions */
8856 p_ea = save_ea;
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008857 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008858#endif
Bram Moolenaarf061e0b2009-06-24 15:32:01 +00008859 curwin = aucmd_win;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008860 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008861 curbuf = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008862 aco->new_curwin = curwin;
8863 aco->new_curbuf = curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008864}
8865
8866/*
8867 * Cleanup after executing autocommands for a (hidden) buffer.
8868 * Restore the window as it was (if possible).
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00008869 * When FEAT_AUTOCMD is not defined another version is used, see below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00008870 */
8871 void
8872aucmd_restbuf(aco)
8873 aco_save_T *aco; /* structure holding saved values */
8874{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008875#ifdef FEAT_WINDOWS
8876 int dummy;
8877#endif
8878
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008879 if (aco->use_aucmd_win)
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008880 {
8881 --curbuf->b_nwindows;
8882#ifdef FEAT_WINDOWS
8883 /* Find "aucmd_win", it can't be closed, but it may be in another tab
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008884 * page. Do not trigger autocommands here. */
8885 block_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008886 if (curwin != aucmd_win)
8887 {
8888 tabpage_T *tp;
8889 win_T *wp;
8890
8891 FOR_ALL_TAB_WINDOWS(tp, wp)
8892 {
8893 if (wp == aucmd_win)
8894 {
8895 if (tp != curtab)
8896 goto_tabpage_tp(tp);
8897 win_goto(aucmd_win);
8898 break;
8899 }
8900 }
8901 }
8902
8903 /* Remove the window and frame from the tree of frames. */
8904 (void)winframe_remove(curwin, &dummy, NULL);
8905 win_remove(curwin, NULL);
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008906 aucmd_win_used = FALSE;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008907 last_status(FALSE); /* may need to remove last status line */
8908 restore_snapshot(SNAP_AUCMD_IDX, FALSE);
8909 (void)win_comp_pos(); /* recompute window positions */
Bram Moolenaar2bc76e62009-07-01 15:13:56 +00008910 unblock_autocmds();
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008911
8912 if (win_valid(aco->save_curwin))
8913 curwin = aco->save_curwin;
8914 else
8915 /* Hmm, original window disappeared. Just use the first one. */
8916 curwin = firstwin;
8917# ifdef FEAT_EVAL
8918 vars_clear(&aucmd_win->w_vars.dv_hashtab); /* free all w: variables */
Bram Moolenaar50daf402009-11-17 13:57:22 +00008919 hash_init(&aucmd_win->w_vars.dv_hashtab); /* re-use the hashtab */
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008920# endif
8921#else
8922 curwin = aco->save_curwin;
8923#endif
8924 curbuf = curwin->w_buffer;
8925
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008926 vim_free(globaldir);
8927 globaldir = aco->globaldir;
8928
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008929 /* the buffer contents may have changed */
8930 check_cursor();
8931 if (curwin->w_topline > curbuf->b_ml.ml_line_count)
8932 {
8933 curwin->w_topline = curbuf->b_ml.ml_line_count;
8934#ifdef FEAT_DIFF
8935 curwin->w_topfill = 0;
8936#endif
8937 }
8938#if defined(FEAT_GUI)
8939 /* Hide the scrollbars from the aucmd_win and update. */
8940 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_LEFT], FALSE);
8941 gui_mch_enable_scrollbar(&aucmd_win->w_scrollbars[SBAR_RIGHT], FALSE);
8942 gui_may_update_scrollbars();
8943#endif
8944 }
8945 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00008946 {
8947 /* restore curwin */
8948#ifdef FEAT_WINDOWS
8949 if (win_valid(aco->save_curwin))
8950#endif
8951 {
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008952 /* Restore the buffer which was previously edited by curwin, if
Bram Moolenaar6bef63c2009-07-29 10:10:29 +00008953 * it was changed, we are still the same window and the buffer is
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008954 * valid. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00008955 if (curwin == aco->new_curwin
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008956 && curbuf != aco->new_curbuf
8957 && buf_valid(aco->new_curbuf)
8958 && aco->new_curbuf->b_ml.ml_mfp != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00008959 {
8960 --curbuf->b_nwindows;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00008961 curbuf = aco->new_curbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008962 curwin->w_buffer = curbuf;
8963 ++curbuf->b_nwindows;
8964 }
8965
8966 curwin = aco->save_curwin;
8967 curbuf = curwin->w_buffer;
8968 }
8969 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00008970}
8971
8972static int autocmd_nested = FALSE;
8973
8974/*
8975 * Execute autocommands for "event" and file name "fname".
8976 * Return TRUE if some commands were executed.
8977 */
8978 int
8979apply_autocmds(event, fname, fname_io, force, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008980 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008981 char_u *fname; /* NULL or empty means use actual file name */
8982 char_u *fname_io; /* fname to use for <afile> on cmdline */
8983 int force; /* when TRUE, ignore autocmd_busy */
8984 buf_T *buf; /* buffer for <abuf> */
8985{
8986 return apply_autocmds_group(event, fname, fname_io, force,
8987 AUGROUP_ALL, buf, NULL);
8988}
8989
8990/*
8991 * Like apply_autocmds(), but with extra "eap" argument. This takes care of
8992 * setting v:filearg.
8993 */
8994 static int
8995apply_autocmds_exarg(event, fname, fname_io, force, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00008996 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00008997 char_u *fname;
8998 char_u *fname_io;
8999 int force;
9000 buf_T *buf;
9001 exarg_T *eap;
9002{
9003 return apply_autocmds_group(event, fname, fname_io, force,
9004 AUGROUP_ALL, buf, eap);
9005}
9006
9007/*
9008 * Like apply_autocmds(), but handles the caller's retval. If the script
9009 * processing is being aborted or if retval is FAIL when inside a try
9010 * conditional, no autocommands are executed. If otherwise the autocommands
9011 * cause the script to be aborted, retval is set to FAIL.
9012 */
9013 int
9014apply_autocmds_retval(event, fname, fname_io, force, buf, retval)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009015 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009016 char_u *fname; /* NULL or empty means use actual file name */
9017 char_u *fname_io; /* fname to use for <afile> on cmdline */
9018 int force; /* when TRUE, ignore autocmd_busy */
9019 buf_T *buf; /* buffer for <abuf> */
9020 int *retval; /* pointer to caller's retval */
9021{
9022 int did_cmd;
9023
Bram Moolenaar1e015462005-09-25 22:16:38 +00009024#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00009025 if (should_abort(*retval))
9026 return FALSE;
Bram Moolenaar1e015462005-09-25 22:16:38 +00009027#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009028
9029 did_cmd = apply_autocmds_group(event, fname, fname_io, force,
9030 AUGROUP_ALL, buf, NULL);
Bram Moolenaar1e015462005-09-25 22:16:38 +00009031 if (did_cmd
9032#ifdef FEAT_EVAL
9033 && aborting()
9034#endif
9035 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00009036 *retval = FAIL;
9037 return did_cmd;
9038}
9039
Bram Moolenaard35f9712005-12-18 22:02:33 +00009040/*
9041 * Return TRUE when there is a CursorHold autocommand defined.
9042 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009043 int
9044has_cursorhold()
9045{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009046 return (first_autopat[(int)(get_real_state() == NORMAL_BUSY
9047 ? EVENT_CURSORHOLD : EVENT_CURSORHOLDI)] != NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009048}
Bram Moolenaard35f9712005-12-18 22:02:33 +00009049
9050/*
9051 * Return TRUE if the CursorHold event can be triggered.
9052 */
9053 int
9054trigger_cursorhold()
9055{
Bram Moolenaar754b5602006-02-09 23:53:20 +00009056 int state;
9057
Bram Moolenaard29a9ee2006-09-14 09:07:34 +00009058 if (!did_cursorhold && has_cursorhold() && !Recording
9059#ifdef FEAT_INS_EXPAND
9060 && !ins_compl_active()
9061#endif
9062 )
Bram Moolenaar754b5602006-02-09 23:53:20 +00009063 {
9064 state = get_real_state();
9065 if (state == NORMAL_BUSY || (state & INSERT) != 0)
9066 return TRUE;
9067 }
9068 return FALSE;
Bram Moolenaard35f9712005-12-18 22:02:33 +00009069}
Bram Moolenaar754b5602006-02-09 23:53:20 +00009070
9071/*
9072 * Return TRUE when there is a CursorMoved autocommand defined.
9073 */
9074 int
9075has_cursormoved()
9076{
9077 return (first_autopat[(int)EVENT_CURSORMOVED] != NULL);
9078}
9079
9080/*
9081 * Return TRUE when there is a CursorMovedI autocommand defined.
9082 */
9083 int
9084has_cursormovedI()
9085{
9086 return (first_autopat[(int)EVENT_CURSORMOVEDI] != NULL);
9087}
Bram Moolenaar071d4272004-06-13 20:20:40 +00009088
9089 static int
9090apply_autocmds_group(event, fname, fname_io, force, group, buf, eap)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009091 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009092 char_u *fname; /* NULL or empty means use actual file name */
9093 char_u *fname_io; /* fname to use for <afile> on cmdline, NULL means
9094 use fname */
9095 int force; /* when TRUE, ignore autocmd_busy */
9096 int group; /* group ID, or AUGROUP_ALL */
9097 buf_T *buf; /* buffer for <abuf> */
9098 exarg_T *eap; /* command arguments */
9099{
9100 char_u *sfname = NULL; /* short file name */
9101 char_u *tail;
9102 int save_changed;
9103 buf_T *old_curbuf;
9104 int retval = FALSE;
9105 char_u *save_sourcing_name;
9106 linenr_T save_sourcing_lnum;
9107 char_u *save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009108 int save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009109 int save_autocmd_bufnr;
9110 char_u *save_autocmd_match;
9111 int save_autocmd_busy;
9112 int save_autocmd_nested;
9113 static int nesting = 0;
9114 AutoPatCmd patcmd;
9115 AutoPat *ap;
9116#ifdef FEAT_EVAL
9117 scid_T save_current_SID;
9118 void *save_funccalp;
9119 char_u *save_cmdarg;
9120 long save_cmdbang;
9121#endif
9122 static int filechangeshell_busy = FALSE;
Bram Moolenaar05159a02005-02-26 23:04:13 +00009123#ifdef FEAT_PROFILE
9124 proftime_T wait_time;
9125#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009126
9127 /*
9128 * Quickly return if there are no autocommands for this event or
9129 * autocommands are blocked.
9130 */
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009131 if (first_autopat[(int)event] == NULL || autocmd_blocked > 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009132 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009133
9134 /*
9135 * When autocommands are busy, new autocommands are only executed when
9136 * explicitly enabled with the "nested" flag.
9137 */
9138 if (autocmd_busy && !(force || autocmd_nested))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009139 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009140
9141#ifdef FEAT_EVAL
9142 /*
Bram Moolenaar7263a772007-05-10 17:35:54 +00009143 * Quickly return when immediately aborting on error, or when an interrupt
Bram Moolenaar071d4272004-06-13 20:20:40 +00009144 * occurred or an exception was thrown but not caught.
9145 */
9146 if (aborting())
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009147 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009148#endif
9149
9150 /*
9151 * FileChangedShell never nests, because it can create an endless loop.
9152 */
Bram Moolenaar56718732006-03-15 22:53:57 +00009153 if (filechangeshell_busy && (event == EVENT_FILECHANGEDSHELL
9154 || event == EVENT_FILECHANGEDSHELLPOST))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009155 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009156
9157 /*
9158 * Ignore events in 'eventignore'.
9159 */
9160 if (event_ignored(event))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009161 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009162
9163 /*
9164 * Allow nesting of autocommands, but restrict the depth, because it's
9165 * possible to create an endless loop.
9166 */
9167 if (nesting == 10)
9168 {
9169 EMSG(_("E218: autocommand nesting too deep"));
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009170 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009171 }
9172
9173 /*
9174 * Check if these autocommands are disabled. Used when doing ":all" or
9175 * ":ball".
9176 */
9177 if ( (autocmd_no_enter
9178 && (event == EVENT_WINENTER || event == EVENT_BUFENTER))
9179 || (autocmd_no_leave
9180 && (event == EVENT_WINLEAVE || event == EVENT_BUFLEAVE)))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009181 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009182
9183 /*
9184 * Save the autocmd_* variables and info about the current buffer.
9185 */
9186 save_autocmd_fname = autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009187 save_autocmd_fname_full = autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009188 save_autocmd_bufnr = autocmd_bufnr;
9189 save_autocmd_match = autocmd_match;
9190 save_autocmd_busy = autocmd_busy;
9191 save_autocmd_nested = autocmd_nested;
9192 save_changed = curbuf->b_changed;
9193 old_curbuf = curbuf;
9194
9195 /*
9196 * Set the file name to be used for <afile>.
Bram Moolenaara0174af2008-01-02 20:08:25 +00009197 * Make a copy to avoid that changing a buffer name or directory makes it
9198 * invalid.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009199 */
9200 if (fname_io == NULL)
9201 {
9202 if (fname != NULL && *fname != NUL)
9203 autocmd_fname = fname;
9204 else if (buf != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009205 autocmd_fname = buf->b_ffname;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009206 else
9207 autocmd_fname = NULL;
9208 }
9209 else
9210 autocmd_fname = fname_io;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009211 if (autocmd_fname != NULL)
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009212 autocmd_fname = vim_strsave(autocmd_fname);
9213 autocmd_fname_full = FALSE; /* call FullName_save() later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009214
9215 /*
9216 * Set the buffer number to be used for <abuf>.
9217 */
9218 if (buf == NULL)
9219 autocmd_bufnr = 0;
9220 else
9221 autocmd_bufnr = buf->b_fnum;
9222
9223 /*
9224 * When the file name is NULL or empty, use the file name of buffer "buf".
9225 * Always use the full path of the file name to match with, in case
9226 * "allow_dirs" is set.
9227 */
9228 if (fname == NULL || *fname == NUL)
9229 {
9230 if (buf == NULL)
9231 fname = NULL;
9232 else
9233 {
9234#ifdef FEAT_SYN_HL
9235 if (event == EVENT_SYNTAX)
9236 fname = buf->b_p_syn;
9237 else
9238#endif
9239 if (event == EVENT_FILETYPE)
9240 fname = buf->b_p_ft;
9241 else
9242 {
9243 if (buf->b_sfname != NULL)
9244 sfname = vim_strsave(buf->b_sfname);
9245 fname = buf->b_ffname;
9246 }
9247 }
9248 if (fname == NULL)
9249 fname = (char_u *)"";
9250 fname = vim_strsave(fname); /* make a copy, so we can change it */
9251 }
9252 else
9253 {
9254 sfname = vim_strsave(fname);
Bram Moolenaar5135d462009-04-29 16:03:38 +00009255 /* Don't try expanding FileType, Syntax, FuncUndefined, WindowID or
9256 * QuickFixCmd* */
Bram Moolenaar7c626922005-02-07 22:01:03 +00009257 if (event == EVENT_FILETYPE
9258 || event == EVENT_SYNTAX
Bram Moolenaar5135d462009-04-29 16:03:38 +00009259 || event == EVENT_FUNCUNDEFINED
Bram Moolenaar7c626922005-02-07 22:01:03 +00009260 || event == EVENT_REMOTEREPLY
Bram Moolenaarb8a7b562006-02-01 21:47:16 +00009261 || event == EVENT_SPELLFILEMISSING
Bram Moolenaar7c626922005-02-07 22:01:03 +00009262 || event == EVENT_QUICKFIXCMDPRE
9263 || event == EVENT_QUICKFIXCMDPOST)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009264 fname = vim_strsave(fname);
9265 else
9266 fname = FullName_save(fname, FALSE);
9267 }
9268 if (fname == NULL) /* out of memory */
9269 {
9270 vim_free(sfname);
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009271 retval = FALSE;
9272 goto BYPASS_AU;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009273 }
9274
9275#ifdef BACKSLASH_IN_FILENAME
9276 /*
9277 * Replace all backslashes with forward slashes. This makes the
9278 * autocommand patterns portable between Unix and MS-DOS.
9279 */
9280 if (sfname != NULL)
9281 forward_slash(sfname);
9282 forward_slash(fname);
9283#endif
9284
9285#ifdef VMS
9286 /* remove version for correct match */
9287 if (sfname != NULL)
9288 vms_remove_version(sfname);
9289 vms_remove_version(fname);
9290#endif
9291
9292 /*
9293 * Set the name to be used for <amatch>.
9294 */
9295 autocmd_match = fname;
9296
9297
9298 /* Don't redraw while doing auto commands. */
9299 ++RedrawingDisabled;
9300 save_sourcing_name = sourcing_name;
9301 sourcing_name = NULL; /* don't free this one */
9302 save_sourcing_lnum = sourcing_lnum;
9303 sourcing_lnum = 0; /* no line number here */
9304
9305#ifdef FEAT_EVAL
9306 save_current_SID = current_SID;
9307
Bram Moolenaar05159a02005-02-26 23:04:13 +00009308# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009309 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009310 prof_child_enter(&wait_time); /* doesn't count for the caller itself */
9311# endif
9312
Bram Moolenaar071d4272004-06-13 20:20:40 +00009313 /* Don't use local function variables, if called from a function */
9314 save_funccalp = save_funccal();
9315#endif
9316
9317 /*
9318 * When starting to execute autocommands, save the search patterns.
9319 */
9320 if (!autocmd_busy)
9321 {
9322 save_search_patterns();
9323 saveRedobuff();
9324 did_filetype = keep_filetype;
9325 }
9326
9327 /*
9328 * Note that we are applying autocmds. Some commands need to know.
9329 */
9330 autocmd_busy = TRUE;
9331 filechangeshell_busy = (event == EVENT_FILECHANGEDSHELL);
9332 ++nesting; /* see matching decrement below */
9333
9334 /* Remember that FileType was triggered. Used for did_filetype(). */
9335 if (event == EVENT_FILETYPE)
9336 did_filetype = TRUE;
9337
9338 tail = gettail(fname);
9339
9340 /* Find first autocommand that matches */
9341 patcmd.curpat = first_autopat[(int)event];
9342 patcmd.nextcmd = NULL;
9343 patcmd.group = group;
9344 patcmd.fname = fname;
9345 patcmd.sfname = sfname;
9346 patcmd.tail = tail;
9347 patcmd.event = event;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009348 patcmd.arg_bufnr = autocmd_bufnr;
9349 patcmd.next = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009350 auto_next_pat(&patcmd, FALSE);
9351
9352 /* found one, start executing the autocommands */
9353 if (patcmd.curpat != NULL)
9354 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009355 /* add to active_apc_list */
9356 patcmd.next = active_apc_list;
9357 active_apc_list = &patcmd;
9358
Bram Moolenaar071d4272004-06-13 20:20:40 +00009359#ifdef FEAT_EVAL
9360 /* set v:cmdarg (only when there is a matching pattern) */
9361 save_cmdbang = get_vim_var_nr(VV_CMDBANG);
9362 if (eap != NULL)
9363 {
9364 save_cmdarg = set_cmdarg(eap, NULL);
9365 set_vim_var_nr(VV_CMDBANG, (long)eap->forceit);
9366 }
9367 else
9368 save_cmdarg = NULL; /* avoid gcc warning */
9369#endif
9370 retval = TRUE;
9371 /* mark the last pattern, to avoid an endless loop when more patterns
9372 * are added when executing autocommands */
9373 for (ap = patcmd.curpat; ap->next != NULL; ap = ap->next)
9374 ap->last = FALSE;
9375 ap->last = TRUE;
9376 check_lnums(TRUE); /* make sure cursor and topline are valid */
9377 do_cmdline(NULL, getnextac, (void *)&patcmd,
9378 DOCMD_NOWAIT|DOCMD_VERBOSE|DOCMD_REPEAT);
9379#ifdef FEAT_EVAL
9380 if (eap != NULL)
9381 {
9382 (void)set_cmdarg(NULL, save_cmdarg);
9383 set_vim_var_nr(VV_CMDBANG, save_cmdbang);
9384 }
9385#endif
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009386 /* delete from active_apc_list */
9387 if (active_apc_list == &patcmd) /* just in case */
9388 active_apc_list = patcmd.next;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009389 }
9390
9391 --RedrawingDisabled;
9392 autocmd_busy = save_autocmd_busy;
9393 filechangeshell_busy = FALSE;
9394 autocmd_nested = save_autocmd_nested;
9395 vim_free(sourcing_name);
9396 sourcing_name = save_sourcing_name;
9397 sourcing_lnum = save_sourcing_lnum;
Bram Moolenaara0174af2008-01-02 20:08:25 +00009398 vim_free(autocmd_fname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009399 autocmd_fname = save_autocmd_fname;
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009400 autocmd_fname_full = save_autocmd_fname_full;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009401 autocmd_bufnr = save_autocmd_bufnr;
9402 autocmd_match = save_autocmd_match;
9403#ifdef FEAT_EVAL
9404 current_SID = save_current_SID;
9405 restore_funccal(save_funccalp);
Bram Moolenaar05159a02005-02-26 23:04:13 +00009406# ifdef FEAT_PROFILE
Bram Moolenaar371d5402006-03-20 21:47:49 +00009407 if (do_profiling == PROF_YES)
Bram Moolenaar05159a02005-02-26 23:04:13 +00009408 prof_child_exit(&wait_time);
9409# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00009410#endif
9411 vim_free(fname);
9412 vim_free(sfname);
9413 --nesting; /* see matching increment above */
9414
9415 /*
9416 * When stopping to execute autocommands, restore the search patterns and
9417 * the redo buffer.
9418 */
9419 if (!autocmd_busy)
9420 {
9421 restore_search_patterns();
9422 restoreRedobuff();
9423 did_filetype = FALSE;
9424 }
9425
9426 /*
9427 * Some events don't set or reset the Changed flag.
9428 * Check if still in the same buffer!
9429 */
9430 if (curbuf == old_curbuf
9431 && (event == EVENT_BUFREADPOST
9432 || event == EVENT_BUFWRITEPOST
9433 || event == EVENT_FILEAPPENDPOST
9434 || event == EVENT_VIMLEAVE
9435 || event == EVENT_VIMLEAVEPRE))
9436 {
9437#ifdef FEAT_TITLE
9438 if (curbuf->b_changed != save_changed)
9439 need_maketitle = TRUE;
9440#endif
9441 curbuf->b_changed = save_changed;
9442 }
9443
9444 au_cleanup(); /* may really delete removed patterns/commands now */
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009445
9446BYPASS_AU:
9447 /* When wiping out a buffer make sure all its buffer-local autocommands
9448 * are deleted. */
9449 if (event == EVENT_BUFWIPEOUT && buf != NULL)
9450 aubuflocal_remove(buf);
9451
Bram Moolenaar071d4272004-06-13 20:20:40 +00009452 return retval;
9453}
9454
Bram Moolenaar78ab3312007-09-29 12:16:41 +00009455# ifdef FEAT_EVAL
9456static char_u *old_termresponse = NULL;
9457# endif
9458
9459/*
9460 * Block triggering autocommands until unblock_autocmd() is called.
9461 * Can be used recursively, so long as it's symmetric.
9462 */
9463 void
9464block_autocmds()
9465{
9466# ifdef FEAT_EVAL
9467 /* Remember the value of v:termresponse. */
9468 if (autocmd_blocked == 0)
9469 old_termresponse = get_vim_var_str(VV_TERMRESPONSE);
9470# endif
9471 ++autocmd_blocked;
9472}
9473
9474 void
9475unblock_autocmds()
9476{
9477 --autocmd_blocked;
9478
9479# ifdef FEAT_EVAL
9480 /* When v:termresponse was set while autocommands were blocked, trigger
9481 * the autocommands now. Esp. useful when executing a shell command
9482 * during startup (vimdiff). */
9483 if (autocmd_blocked == 0
9484 && get_vim_var_str(VV_TERMRESPONSE) != old_termresponse)
9485 apply_autocmds(EVENT_TERMRESPONSE, NULL, NULL, FALSE, curbuf);
9486# endif
9487}
9488
Bram Moolenaar071d4272004-06-13 20:20:40 +00009489/*
9490 * Find next autocommand pattern that matches.
9491 */
9492 static void
9493auto_next_pat(apc, stop_at_last)
9494 AutoPatCmd *apc;
9495 int stop_at_last; /* stop when 'last' flag is set */
9496{
9497 AutoPat *ap;
9498 AutoCmd *cp;
9499 char_u *name;
9500 char *s;
9501
9502 vim_free(sourcing_name);
9503 sourcing_name = NULL;
9504
9505 for (ap = apc->curpat; ap != NULL && !got_int; ap = ap->next)
9506 {
9507 apc->curpat = NULL;
9508
Bram Moolenaarf6dad432008-09-18 19:29:58 +00009509 /* Only use a pattern when it has not been removed, has commands and
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009510 * the group matches. For buffer-local autocommands only check the
9511 * buffer number. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009512 if (ap->pat != NULL && ap->cmds != NULL
9513 && (apc->group == AUGROUP_ALL || apc->group == ap->group))
9514 {
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009515 /* execution-condition */
9516 if (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009517 ? (match_file_pat(NULL, ap->reg_prog, apc->fname,
9518 apc->sfname, apc->tail, ap->allow_dirs))
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009519 : ap->buflocal_nr == apc->arg_bufnr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009520 {
9521 name = event_nr2name(apc->event);
9522 s = _("%s Auto commands for \"%s\"");
9523 sourcing_name = alloc((unsigned)(STRLEN(s)
9524 + STRLEN(name) + ap->patlen + 1));
9525 if (sourcing_name != NULL)
9526 {
9527 sprintf((char *)sourcing_name, s,
9528 (char *)name, (char *)ap->pat);
9529 if (p_verbose >= 8)
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009530 {
9531 verbose_enter();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009532 smsg((char_u *)_("Executing %s"), sourcing_name);
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009533 verbose_leave();
9534 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009535 }
9536
9537 apc->curpat = ap;
9538 apc->nextcmd = ap->cmds;
9539 /* mark last command */
9540 for (cp = ap->cmds; cp->next != NULL; cp = cp->next)
9541 cp->last = FALSE;
9542 cp->last = TRUE;
9543 }
9544 line_breakcheck();
9545 if (apc->curpat != NULL) /* found a match */
9546 break;
9547 }
9548 if (stop_at_last && ap->last)
9549 break;
9550 }
9551}
9552
9553/*
9554 * Get next autocommand command.
9555 * Called by do_cmdline() to get the next line for ":if".
9556 * Returns allocated string, or NULL for end of autocommands.
9557 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009558 static char_u *
9559getnextac(c, cookie, indent)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009560 int c UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009561 void *cookie;
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009562 int indent UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009563{
9564 AutoPatCmd *acp = (AutoPatCmd *)cookie;
9565 char_u *retval;
9566 AutoCmd *ac;
9567
9568 /* Can be called again after returning the last line. */
9569 if (acp->curpat == NULL)
9570 return NULL;
9571
9572 /* repeat until we find an autocommand to execute */
9573 for (;;)
9574 {
9575 /* skip removed commands */
9576 while (acp->nextcmd != NULL && acp->nextcmd->cmd == NULL)
9577 if (acp->nextcmd->last)
9578 acp->nextcmd = NULL;
9579 else
9580 acp->nextcmd = acp->nextcmd->next;
9581
9582 if (acp->nextcmd != NULL)
9583 break;
9584
9585 /* at end of commands, find next pattern that matches */
9586 if (acp->curpat->last)
9587 acp->curpat = NULL;
9588 else
9589 acp->curpat = acp->curpat->next;
9590 if (acp->curpat != NULL)
9591 auto_next_pat(acp, TRUE);
9592 if (acp->curpat == NULL)
9593 return NULL;
9594 }
9595
9596 ac = acp->nextcmd;
9597
9598 if (p_verbose >= 9)
9599 {
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009600 verbose_enter_scroll();
Bram Moolenaar051b7822005-05-19 21:00:46 +00009601 smsg((char_u *)_("autocommand %s"), ac->cmd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009602 msg_puts((char_u *)"\n"); /* don't overwrite this either */
Bram Moolenaara04f10b2005-05-31 22:09:46 +00009603 verbose_leave_scroll();
Bram Moolenaar071d4272004-06-13 20:20:40 +00009604 }
9605 retval = vim_strsave(ac->cmd);
9606 autocmd_nested = ac->nested;
9607#ifdef FEAT_EVAL
9608 current_SID = ac->scriptID;
9609#endif
9610 if (ac->last)
9611 acp->nextcmd = NULL;
9612 else
9613 acp->nextcmd = ac->next;
9614 return retval;
9615}
9616
9617/*
9618 * Return TRUE if there is a matching autocommand for "fname".
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009619 * To account for buffer-local autocommands, function needs to know
9620 * in which buffer the file will be opened.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009621 */
9622 int
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009623has_autocmd(event, sfname, buf)
Bram Moolenaar754b5602006-02-09 23:53:20 +00009624 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009625 char_u *sfname;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009626 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009627{
9628 AutoPat *ap;
9629 char_u *fname;
9630 char_u *tail = gettail(sfname);
9631 int retval = FALSE;
9632
9633 fname = FullName_save(sfname, FALSE);
9634 if (fname == NULL)
9635 return FALSE;
9636
9637#ifdef BACKSLASH_IN_FILENAME
9638 /*
9639 * Replace all backslashes with forward slashes. This makes the
9640 * autocommand patterns portable between Unix and MS-DOS.
9641 */
9642 sfname = vim_strsave(sfname);
9643 if (sfname != NULL)
9644 forward_slash(sfname);
9645 forward_slash(fname);
9646#endif
9647
9648 for (ap = first_autopat[(int)event]; ap != NULL; ap = ap->next)
9649 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009650 && (ap->buflocal_nr == 0
Bram Moolenaar748bf032005-02-02 23:04:36 +00009651 ? match_file_pat(NULL, ap->reg_prog,
9652 fname, sfname, tail, ap->allow_dirs)
Bram Moolenaarc9b4b052006-04-30 18:54:39 +00009653 : buf != NULL && ap->buflocal_nr == buf->b_fnum
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009654 ))
Bram Moolenaar071d4272004-06-13 20:20:40 +00009655 {
9656 retval = TRUE;
9657 break;
9658 }
9659
9660 vim_free(fname);
9661#ifdef BACKSLASH_IN_FILENAME
9662 vim_free(sfname);
9663#endif
9664
9665 return retval;
9666}
9667
9668#if defined(FEAT_CMDL_COMPL) || defined(PROTO)
9669/*
9670 * Function given to ExpandGeneric() to obtain the list of autocommand group
9671 * names.
9672 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009673 char_u *
9674get_augroup_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009675 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009676 int idx;
9677{
9678 if (idx == augroups.ga_len) /* add "END" add the end */
9679 return (char_u *)"END";
9680 if (idx >= augroups.ga_len) /* end of list */
9681 return NULL;
9682 if (AUGROUP_NAME(idx) == NULL) /* skip deleted entries */
9683 return (char_u *)"";
9684 return AUGROUP_NAME(idx); /* return a name */
9685}
9686
9687static int include_groups = FALSE;
9688
9689 char_u *
9690set_context_in_autocmd(xp, arg, doautocmd)
9691 expand_T *xp;
9692 char_u *arg;
Bram Moolenaard812df62008-11-09 12:46:09 +00009693 int doautocmd; /* TRUE for :doauto*, FALSE for :autocmd */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009694{
9695 char_u *p;
9696 int group;
9697
9698 /* check for a group name, skip it if present */
9699 include_groups = FALSE;
9700 p = arg;
9701 group = au_get_grouparg(&arg);
9702 if (group == AUGROUP_ERROR)
9703 return NULL;
9704 /* If there only is a group name that's what we expand. */
9705 if (*arg == NUL && group != AUGROUP_ALL && !vim_iswhite(arg[-1]))
9706 {
9707 arg = p;
9708 group = AUGROUP_ALL;
9709 }
9710
9711 /* skip over event name */
9712 for (p = arg; *p != NUL && !vim_iswhite(*p); ++p)
9713 if (*p == ',')
9714 arg = p + 1;
9715 if (*p == NUL)
9716 {
9717 if (group == AUGROUP_ALL)
9718 include_groups = TRUE;
9719 xp->xp_context = EXPAND_EVENTS; /* expand event name */
9720 xp->xp_pattern = arg;
9721 return NULL;
9722 }
9723
9724 /* skip over pattern */
9725 arg = skipwhite(p);
9726 while (*arg && (!vim_iswhite(*arg) || arg[-1] == '\\'))
9727 arg++;
9728 if (*arg)
9729 return arg; /* expand (next) command */
9730
9731 if (doautocmd)
9732 xp->xp_context = EXPAND_FILES; /* expand file names */
9733 else
9734 xp->xp_context = EXPAND_NOTHING; /* pattern is not expanded */
9735 return NULL;
9736}
9737
9738/*
9739 * Function given to ExpandGeneric() to obtain the list of event names.
9740 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009741 char_u *
9742get_event_name(xp, idx)
Bram Moolenaaraf0167f2009-05-16 15:31:32 +00009743 expand_T *xp UNUSED;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009744 int idx;
9745{
9746 if (idx < augroups.ga_len) /* First list group names, if wanted */
9747 {
9748 if (!include_groups || AUGROUP_NAME(idx) == NULL)
9749 return (char_u *)""; /* skip deleted entries */
9750 return AUGROUP_NAME(idx); /* return a name */
9751 }
9752 return (char_u *)event_names[idx - augroups.ga_len].name;
9753}
9754
9755#endif /* FEAT_CMDL_COMPL */
9756
9757/*
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009758 * Return TRUE if autocmd is supported.
9759 */
9760 int
9761autocmd_supported(name)
9762 char_u *name;
9763{
9764 char_u *p;
9765
9766 return (event_name2nr(name, &p) != NUM_EVENTS);
9767}
9768
9769/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00009770 * Return TRUE if an autocommand is defined for a group, event and
9771 * pattern: The group can be omitted to accept any group. "event" and "pattern"
9772 * can be NULL to accept any event and pattern. "pattern" can be NULL to accept
9773 * any pattern. Buffer-local patterns <buffer> or <buffer=N> are accepted.
9774 * Used for:
9775 * exists("#Group") or
9776 * exists("#Group#Event") or
9777 * exists("#Group#Event#pat") or
9778 * exists("#Event") or
9779 * exists("#Event#pat")
Bram Moolenaar071d4272004-06-13 20:20:40 +00009780 */
9781 int
Bram Moolenaar195d6352005-12-19 22:08:24 +00009782au_exists(arg)
9783 char_u *arg;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009784{
Bram Moolenaar195d6352005-12-19 22:08:24 +00009785 char_u *arg_save;
9786 char_u *pattern = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009787 char_u *event_name;
9788 char_u *p;
Bram Moolenaar754b5602006-02-09 23:53:20 +00009789 event_T event;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009790 AutoPat *ap;
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009791 buf_T *buflocal_buf = NULL;
Bram Moolenaar195d6352005-12-19 22:08:24 +00009792 int group;
9793 int retval = FALSE;
9794
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009795 /* Make a copy so that we can change the '#' chars to a NUL. */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009796 arg_save = vim_strsave(arg);
9797 if (arg_save == NULL)
9798 return FALSE;
Bram Moolenaarf4cd3e82005-12-22 22:47:02 +00009799 p = vim_strchr(arg_save, '#');
Bram Moolenaar195d6352005-12-19 22:08:24 +00009800 if (p != NULL)
9801 *p++ = NUL;
9802
9803 /* First, look for an autocmd group name */
9804 group = au_find_group(arg_save);
9805 if (group == AUGROUP_ERROR)
9806 {
9807 /* Didn't match a group name, assume the first argument is an event. */
9808 group = AUGROUP_ALL;
9809 event_name = arg_save;
9810 }
9811 else
9812 {
9813 if (p == NULL)
9814 {
9815 /* "Group": group name is present and it's recognized */
9816 retval = TRUE;
9817 goto theend;
9818 }
9819
9820 /* Must be "Group#Event" or "Group#Event#pat". */
9821 event_name = p;
9822 p = vim_strchr(event_name, '#');
9823 if (p != NULL)
9824 *p++ = NUL; /* "Group#Event#pat" */
9825 }
9826
9827 pattern = p; /* "pattern" is NULL when there is no pattern */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009828
9829 /* find the index (enum) for the event name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009830 event = event_name2nr(event_name, &p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00009831
9832 /* return FALSE if the event name is not recognized */
Bram Moolenaar195d6352005-12-19 22:08:24 +00009833 if (event == NUM_EVENTS)
9834 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009835
9836 /* Find the first autocommand for this event.
9837 * If there isn't any, return FALSE;
9838 * If there is one and no pattern given, return TRUE; */
9839 ap = first_autopat[(int)event];
9840 if (ap == NULL)
Bram Moolenaar195d6352005-12-19 22:08:24 +00009841 goto theend;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009842
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009843 /* if pattern is "<buffer>", special handling is needed which uses curbuf */
9844 /* for pattern "<buffer=N>, fnamecmp() will work fine */
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009845 if (pattern != NULL && STRICMP(pattern, "<buffer>") == 0)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009846 buflocal_buf = curbuf;
9847
Bram Moolenaar071d4272004-06-13 20:20:40 +00009848 /* Check if there is an autocommand with the given pattern. */
9849 for ( ; ap != NULL; ap = ap->next)
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009850 /* only use a pattern when it has not been removed and has commands. */
9851 /* For buffer-local autocommands, fnamecmp() works fine. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009852 if (ap->pat != NULL && ap->cmds != NULL
Bram Moolenaar195d6352005-12-19 22:08:24 +00009853 && (group == AUGROUP_ALL || ap->group == group)
Bram Moolenaar5b7880d2009-09-11 15:24:31 +00009854 && (pattern == NULL
9855 || (buflocal_buf == NULL
9856 ? fnamecmp(ap->pat, pattern) == 0
9857 : ap->buflocal_nr == buflocal_buf->b_fnum)))
Bram Moolenaar195d6352005-12-19 22:08:24 +00009858 {
9859 retval = TRUE;
9860 break;
9861 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009862
Bram Moolenaar195d6352005-12-19 22:08:24 +00009863theend:
9864 vim_free(arg_save);
9865 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +00009866}
Bram Moolenaarb5bf5b82004-12-24 14:35:23 +00009867
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009868#else /* FEAT_AUTOCMD */
9869
9870/*
9871 * Prepare for executing commands for (hidden) buffer "buf".
9872 * This is the non-autocommand version, it simply saves "curbuf" and sets
9873 * "curbuf" and "curwin" to match "buf".
9874 */
9875 void
9876aucmd_prepbuf(aco, buf)
9877 aco_save_T *aco; /* structure to save values in */
9878 buf_T *buf; /* new curbuf */
9879{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009880 aco->save_curbuf = curbuf;
9881 --curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009882 curbuf = buf;
9883 curwin->w_buffer = buf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009884 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009885}
9886
9887/*
9888 * Restore after executing commands for a (hidden) buffer.
9889 * This is the non-autocommand version.
9890 */
9891 void
9892aucmd_restbuf(aco)
9893 aco_save_T *aco; /* structure holding saved values */
9894{
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009895 --curbuf->b_nwindows;
9896 curbuf = aco->save_curbuf;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009897 curwin->w_buffer = curbuf;
Bram Moolenaar746ebd32009-06-16 14:01:43 +00009898 ++curbuf->b_nwindows;
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009899}
9900
Bram Moolenaar071d4272004-06-13 20:20:40 +00009901#endif /* FEAT_AUTOCMD */
9902
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00009903
Bram Moolenaar071d4272004-06-13 20:20:40 +00009904#if defined(FEAT_AUTOCMD) || defined(FEAT_WILDIGN) || defined(PROTO)
9905/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00009906 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
9907 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
9908 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00009909 * Used for autocommands and 'wildignore'.
9910 * Returns TRUE if there is a match, FALSE otherwise.
9911 */
9912 int
Bram Moolenaar748bf032005-02-02 23:04:36 +00009913match_file_pat(pattern, prog, fname, sfname, tail, allow_dirs)
Bram Moolenaar071d4272004-06-13 20:20:40 +00009914 char_u *pattern; /* pattern to match with */
Bram Moolenaar748bf032005-02-02 23:04:36 +00009915 regprog_T *prog; /* pre-compiled regprog or NULL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00009916 char_u *fname; /* full path of file name */
9917 char_u *sfname; /* short file name or NULL */
9918 char_u *tail; /* tail of path */
9919 int allow_dirs; /* allow matching with dir */
9920{
9921 regmatch_T regmatch;
9922 int result = FALSE;
9923#ifdef FEAT_OSFILETYPE
9924 int no_pattern = FALSE; /* TRUE if check is filetype only */
9925 char_u *type_start;
9926 char_u c;
9927 int match = FALSE;
9928#endif
9929
9930#ifdef CASE_INSENSITIVE_FILENAME
9931 regmatch.rm_ic = TRUE; /* Always ignore case */
9932#else
9933 regmatch.rm_ic = FALSE; /* Don't ever ignore case */
9934#endif
9935#ifdef FEAT_OSFILETYPE
9936 if (*pattern == '<')
9937 {
9938 /* There is a filetype condition specified with this pattern.
9939 * Check the filetype matches first. If not, don't bother with the
9940 * pattern (set regprog to NULL).
9941 * Always use magic for the regexp.
9942 */
9943
9944 for (type_start = pattern + 1; (c = *pattern); pattern++)
9945 {
9946 if ((c == ';' || c == '>') && match == FALSE)
9947 {
9948 *pattern = NUL; /* Terminate the string */
9949 match = mch_check_filetype(fname, type_start);
9950 *pattern = c; /* Restore the terminator */
9951 type_start = pattern + 1;
9952 }
9953 if (c == '>')
9954 break;
9955 }
9956
9957 /* (c should never be NUL, but check anyway) */
9958 if (match == FALSE || c == NUL)
9959 regmatch.regprog = NULL; /* Doesn't match - don't check pat. */
9960 else if (*pattern == NUL)
9961 {
9962 regmatch.regprog = NULL; /* Vim will try to free regprog later */
9963 no_pattern = TRUE; /* Always matches - don't check pat. */
9964 }
9965 else
9966 regmatch.regprog = vim_regcomp(pattern + 1, RE_MAGIC);
9967 }
9968 else
9969#endif
Bram Moolenaar748bf032005-02-02 23:04:36 +00009970 {
9971 if (prog != NULL)
9972 regmatch.regprog = prog;
9973 else
9974 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
9975 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00009976
9977 /*
9978 * Try for a match with the pattern with:
9979 * 1. the full file name, when the pattern has a '/'.
9980 * 2. the short file name, when the pattern has a '/'.
9981 * 3. the tail of the file name, when the pattern has no '/'.
9982 */
9983 if (
9984#ifdef FEAT_OSFILETYPE
9985 /* If the check is for a filetype only and we don't care
9986 * about the path then skip all the regexp stuff.
9987 */
9988 no_pattern ||
9989#endif
9990 (regmatch.regprog != NULL
9991 && ((allow_dirs
9992 && (vim_regexec(&regmatch, fname, (colnr_T)0)
9993 || (sfname != NULL
9994 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
9995 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))))
9996 result = TRUE;
9997
Bram Moolenaar748bf032005-02-02 23:04:36 +00009998 if (prog == NULL)
9999 vim_free(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010000 return result;
10001}
10002#endif
10003
10004#if defined(FEAT_WILDIGN) || defined(PROTO)
10005/*
10006 * Return TRUE if a file matches with a pattern in "list".
10007 * "list" is a comma-separated list of patterns, like 'wildignore'.
10008 * "sfname" is the short file name or NULL, "ffname" the long file name.
10009 */
10010 int
10011match_file_list(list, sfname, ffname)
10012 char_u *list;
10013 char_u *sfname;
10014 char_u *ffname;
10015{
10016 char_u buf[100];
10017 char_u *tail;
10018 char_u *regpat;
10019 char allow_dirs;
10020 int match;
10021 char_u *p;
10022
10023 tail = gettail(sfname);
10024
10025 /* try all patterns in 'wildignore' */
10026 p = list;
10027 while (*p)
10028 {
10029 copy_option_part(&p, buf, 100, ",");
10030 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
10031 if (regpat == NULL)
10032 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +000010033 match = match_file_pat(regpat, NULL, ffname, sfname,
10034 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +000010035 vim_free(regpat);
10036 if (match)
10037 return TRUE;
10038 }
10039 return FALSE;
10040}
10041#endif
10042
10043/*
10044 * Convert the given pattern "pat" which has shell style wildcards in it, into
10045 * a regular expression, and return the result in allocated memory. If there
10046 * is a directory path separator to be matched, then TRUE is put in
10047 * allow_dirs, otherwise FALSE is put there -- webb.
10048 * Handle backslashes before special characters, like "\*" and "\ ".
10049 *
10050 * If FEAT_OSFILETYPE defined then pass initial <type> through unchanged. Eg:
10051 * '<html>myfile' becomes '<html>^myfile$' -- leonard.
10052 *
10053 * Returns NULL when out of memory.
10054 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010055 char_u *
10056file_pat_to_reg_pat(pat, pat_end, allow_dirs, no_bslash)
10057 char_u *pat;
10058 char_u *pat_end; /* first char after pattern or NULL */
10059 char *allow_dirs; /* Result passed back out in here */
Bram Moolenaar78a15312009-05-15 19:33:18 +000010060 int no_bslash UNUSED; /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010061{
10062 int size;
10063 char_u *endp;
10064 char_u *reg_pat;
10065 char_u *p;
10066 int i;
10067 int nested = 0;
10068 int add_dollar = TRUE;
10069#ifdef FEAT_OSFILETYPE
10070 int check_length = 0;
10071#endif
10072
10073 if (allow_dirs != NULL)
10074 *allow_dirs = FALSE;
10075 if (pat_end == NULL)
10076 pat_end = pat + STRLEN(pat);
10077
10078#ifdef FEAT_OSFILETYPE
10079 /* Find out how much of the string is the filetype check */
10080 if (*pat == '<')
10081 {
10082 /* Count chars until the next '>' */
10083 for (p = pat + 1; p < pat_end && *p != '>'; p++)
10084 ;
10085 if (p < pat_end)
10086 {
10087 /* Pattern is of the form <.*>.* */
10088 check_length = p - pat + 1;
10089 if (p + 1 >= pat_end)
10090 {
10091 /* The 'pattern' is a filetype check ONLY */
10092 reg_pat = (char_u *)alloc(check_length + 1);
10093 if (reg_pat != NULL)
10094 {
10095 mch_memmove(reg_pat, pat, (size_t)check_length);
10096 reg_pat[check_length] = NUL;
10097 }
10098 return reg_pat;
10099 }
10100 }
10101 /* else: there was no closing '>' - assume it was a normal pattern */
10102
10103 }
10104 pat += check_length;
10105 size = 2 + check_length;
10106#else
10107 size = 2; /* '^' at start, '$' at end */
10108#endif
10109
10110 for (p = pat; p < pat_end; p++)
10111 {
10112 switch (*p)
10113 {
10114 case '*':
10115 case '.':
10116 case ',':
10117 case '{':
10118 case '}':
10119 case '~':
10120 size += 2; /* extra backslash */
10121 break;
10122#ifdef BACKSLASH_IN_FILENAME
10123 case '\\':
10124 case '/':
10125 size += 4; /* could become "[\/]" */
10126 break;
10127#endif
10128 default:
10129 size++;
10130# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010131 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010132 {
10133 ++p;
10134 ++size;
10135 }
10136# endif
10137 break;
10138 }
10139 }
10140 reg_pat = alloc(size + 1);
10141 if (reg_pat == NULL)
10142 return NULL;
10143
10144#ifdef FEAT_OSFILETYPE
10145 /* Copy the type check in to the start. */
10146 if (check_length)
10147 mch_memmove(reg_pat, pat - check_length, (size_t)check_length);
10148 i = check_length;
10149#else
10150 i = 0;
10151#endif
10152
10153 if (pat[0] == '*')
10154 while (pat[0] == '*' && pat < pat_end - 1)
10155 pat++;
10156 else
10157 reg_pat[i++] = '^';
10158 endp = pat_end - 1;
10159 if (*endp == '*')
10160 {
10161 while (endp - pat > 0 && *endp == '*')
10162 endp--;
10163 add_dollar = FALSE;
10164 }
10165 for (p = pat; *p && nested >= 0 && p <= endp; p++)
10166 {
10167 switch (*p)
10168 {
10169 case '*':
10170 reg_pat[i++] = '.';
10171 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +000010172 while (p[1] == '*') /* "**" matches like "*" */
10173 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010174 break;
10175 case '.':
10176#ifdef RISCOS
10177 if (allow_dirs != NULL)
10178 *allow_dirs = TRUE;
10179 /* FALLTHROUGH */
10180#endif
10181 case '~':
10182 reg_pat[i++] = '\\';
10183 reg_pat[i++] = *p;
10184 break;
10185 case '?':
10186#ifdef RISCOS
10187 case '#':
10188#endif
10189 reg_pat[i++] = '.';
10190 break;
10191 case '\\':
10192 if (p[1] == NUL)
10193 break;
10194#ifdef BACKSLASH_IN_FILENAME
10195 if (!no_bslash)
10196 {
10197 /* translate:
10198 * "\x" to "\\x" e.g., "dir\file"
10199 * "\*" to "\\.*" e.g., "dir\*.c"
10200 * "\?" to "\\." e.g., "dir\??.c"
10201 * "\+" to "\+" e.g., "fileX\+.c"
10202 */
10203 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
10204 && p[1] != '+')
10205 {
10206 reg_pat[i++] = '[';
10207 reg_pat[i++] = '\\';
10208 reg_pat[i++] = '/';
10209 reg_pat[i++] = ']';
10210 if (allow_dirs != NULL)
10211 *allow_dirs = TRUE;
10212 break;
10213 }
10214 }
10215#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010216 /* Undo escaping from ExpandEscape():
10217 * foo\?bar -> foo?bar
10218 * foo\%bar -> foo%bar
10219 * foo\,bar -> foo,bar
10220 * foo\ bar -> foo bar
10221 * Don't unescape \, * and others that are also special in a
10222 * regexp. */
Bram Moolenaar071d4272004-06-13 20:20:40 +000010223 if (*++p == '?'
10224#ifdef BACKSLASH_IN_FILENAME
10225 && no_bslash
10226#endif
10227 )
10228 reg_pat[i++] = '?';
10229 else
Bram Moolenaar8cd213c2010-06-01 21:57:09 +020010230 if (*p == ',' || *p == '%' || *p == '#' || *p == ' ')
10231 reg_pat[i++] = *p;
Bram Moolenaar071d4272004-06-13 20:20:40 +000010232 else
10233 {
10234 if (allow_dirs != NULL && vim_ispathsep(*p)
10235#ifdef BACKSLASH_IN_FILENAME
10236 && (!no_bslash || *p != '\\')
10237#endif
10238 )
10239 *allow_dirs = TRUE;
10240 reg_pat[i++] = '\\';
10241 reg_pat[i++] = *p;
10242 }
10243 break;
10244#ifdef BACKSLASH_IN_FILENAME
10245 case '/':
10246 reg_pat[i++] = '[';
10247 reg_pat[i++] = '\\';
10248 reg_pat[i++] = '/';
10249 reg_pat[i++] = ']';
10250 if (allow_dirs != NULL)
10251 *allow_dirs = TRUE;
10252 break;
10253#endif
10254 case '{':
10255 reg_pat[i++] = '\\';
10256 reg_pat[i++] = '(';
10257 nested++;
10258 break;
10259 case '}':
10260 reg_pat[i++] = '\\';
10261 reg_pat[i++] = ')';
10262 --nested;
10263 break;
10264 case ',':
10265 if (nested)
10266 {
10267 reg_pat[i++] = '\\';
10268 reg_pat[i++] = '|';
10269 }
10270 else
10271 reg_pat[i++] = ',';
10272 break;
10273 default:
10274# ifdef FEAT_MBYTE
Bram Moolenaar0fa313a2005-08-10 21:07:57 +000010275 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +000010276 reg_pat[i++] = *p++;
10277 else
10278# endif
10279 if (allow_dirs != NULL && vim_ispathsep(*p))
10280 *allow_dirs = TRUE;
10281 reg_pat[i++] = *p;
10282 break;
10283 }
10284 }
10285 if (add_dollar)
10286 reg_pat[i++] = '$';
10287 reg_pat[i] = NUL;
10288 if (nested != 0)
10289 {
10290 if (nested < 0)
10291 EMSG(_("E219: Missing {."));
10292 else
10293 EMSG(_("E220: Missing }."));
10294 vim_free(reg_pat);
10295 reg_pat = NULL;
10296 }
10297 return reg_pat;
10298}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +010010299
10300#if defined(EINTR) || defined(PROTO)
10301/*
10302 * Version of read() that retries when interrupted by EINTR (possibly
10303 * by a SIGWINCH).
10304 */
10305 long
10306read_eintr(fd, buf, bufsize)
10307 int fd;
10308 void *buf;
10309 size_t bufsize;
10310{
10311 long ret;
10312
10313 for (;;)
10314 {
10315 ret = vim_read(fd, buf, bufsize);
10316 if (ret >= 0 || errno != EINTR)
10317 break;
10318 }
10319 return ret;
10320}
10321
10322/*
10323 * Version of write() that retries when interrupted by EINTR (possibly
10324 * by a SIGWINCH).
10325 */
10326 long
10327write_eintr(fd, buf, bufsize)
10328 int fd;
10329 void *buf;
10330 size_t bufsize;
10331{
10332 long ret = 0;
10333 long wlen;
10334
10335 /* Repeat the write() so long it didn't fail, other than being interrupted
10336 * by a signal. */
10337 while (ret < (long)bufsize)
10338 {
10339 wlen = vim_write(fd, buf + ret, bufsize - ret);
10340 if (wlen < 0)
10341 {
10342 if (errno != EINTR)
10343 break;
10344 }
10345 else
10346 ret += wlen;
10347 }
10348 return ret;
10349}
10350#endif