blob: 96207ab9ca3daf317a76e56e10329ce5c1624b8b [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
20#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
21# include <utime.h> /* for struct utimbuf */
22#endif
23
24#define BUFSIZE 8192 /* size of normal write buffer */
25#define SMBUFSIZE 256 /* size of emergency write buffer */
26
Bram Moolenaar071d4272004-06-13 20:20:40 +000027/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000028#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000029
Bram Moolenaard25c16e2016-01-29 22:13:30 +010030static char_u *next_fenc(char_u **pp);
Bram Moolenaar13505972019-01-24 15:04:48 +010031#ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010032static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000033#endif
34#ifdef FEAT_VIMINFO
Bram Moolenaard25c16e2016-01-29 22:13:30 +010035static void check_marks_read(void);
Bram Moolenaar071d4272004-06-13 20:20:40 +000036#endif
37#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020038static char_u *check_for_cryptkey(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 +000039#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010040static int set_rw_fname(char_u *fname, char_u *sfname);
41static int msg_add_fileformat(int eol_type);
42static void msg_add_eol(void);
Bram Moolenaar8767f522016-07-01 17:17:39 +020043static int check_mtime(buf_T *buf, stat_T *s);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010044static int time_differs(long t1, long t2);
Bram Moolenaar071d4272004-06-13 20:20:40 +000045
Bram Moolenaar13505972019-01-24 15:04:48 +010046#define HAS_BW_FLAGS
47#define FIO_LATIN1 0x01 /* convert Latin1 */
48#define FIO_UTF8 0x02 /* convert UTF-8 */
49#define FIO_UCS2 0x04 /* convert UCS-2 */
50#define FIO_UCS4 0x08 /* convert UCS-4 */
51#define FIO_UTF16 0x10 /* convert UTF-16 */
Bram Moolenaar4f974752019-02-17 17:44:42 +010052#ifdef MSWIN
Bram Moolenaar13505972019-01-24 15:04:48 +010053# define FIO_CODEPAGE 0x20 /* convert MS-Windows codepage */
54# define FIO_PUT_CP(x) (((x) & 0xffff) << 16) /* put codepage in top word */
55# define FIO_GET_CP(x) (((x)>>16) & 0xffff) /* get codepage from top word */
Bram Moolenaar071d4272004-06-13 20:20:40 +000056#endif
Bram Moolenaar13505972019-01-24 15:04:48 +010057#ifdef MACOS_CONVERT
58# define FIO_MACROMAN 0x20 /* convert MacRoman */
59#endif
60#define FIO_ENDIAN_L 0x80 /* little endian */
61#define FIO_ENCRYPTED 0x1000 /* encrypt written bytes */
62#define FIO_NOCONVERT 0x2000 /* skip encoding conversion */
63#define FIO_UCSBOM 0x4000 /* check for BOM at start of file */
64#define FIO_ALL -1 /* allow all formats */
Bram Moolenaar071d4272004-06-13 20:20:40 +000065
66/* When converting, a read() or write() may leave some bytes to be converted
67 * for the next call. The value is guessed... */
68#define CONV_RESTLEN 30
69
70/* We have to guess how much a sequence of bytes may expand when converting
71 * with iconv() to be able to allocate a buffer. */
72#define ICONV_MULT 8
73
74/*
75 * Structure to pass arguments from buf_write() to buf_write_bytes().
76 */
77struct bw_info
78{
79 int bw_fd; /* file descriptor */
80 char_u *bw_buf; /* buffer with data to be written */
Bram Moolenaard089d9b2007-09-30 12:02:55 +000081 int bw_len; /* length of data */
Bram Moolenaar071d4272004-06-13 20:20:40 +000082#ifdef HAS_BW_FLAGS
83 int bw_flags; /* FIO_ flags */
84#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +020085#ifdef FEAT_CRYPT
86 buf_T *bw_buffer; /* buffer being written */
87#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000088 char_u bw_rest[CONV_RESTLEN]; /* not converted bytes */
89 int bw_restlen; /* nr of bytes in bw_rest[] */
90 int bw_first; /* first write call */
91 char_u *bw_conv_buf; /* buffer for writing converted chars */
Bram Moolenaar18a4ba22019-05-24 19:39:03 +020092 size_t bw_conv_buflen; /* size of bw_conv_buf */
Bram Moolenaar071d4272004-06-13 20:20:40 +000093 int bw_conv_error; /* set for conversion error */
Bram Moolenaar32b485f2009-07-29 16:06:27 +000094 linenr_T bw_conv_error_lnum; /* first line with error or zero */
95 linenr_T bw_start_lnum; /* line number at start of buffer */
Bram Moolenaar13505972019-01-24 15:04:48 +010096#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +000097 iconv_t bw_iconv_fd; /* descriptor for iconv() or -1 */
Bram Moolenaar071d4272004-06-13 20:20:40 +000098#endif
99};
100
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100101static int buf_write_bytes(struct bw_info *ip);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000102
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100103static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
104static int ucs2bytes(unsigned c, char_u **pp, int flags);
105static int need_conversion(char_u *fenc);
106static int get_fio_flags(char_u *ptr);
107static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
108static int make_bom(char_u *buf, char_u *name);
Bram Moolenaar4f974752019-02-17 17:44:42 +0100109#ifdef MSWIN
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100110static int get_win_fio_flags(char_u *ptr);
Bram Moolenaar13505972019-01-24 15:04:48 +0100111#endif
112#ifdef MACOS_CONVERT
Bram Moolenaard25c16e2016-01-29 22:13:30 +0100113static int get_mac_fio_flags(char_u *ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000114#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000115static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000116
Bram Moolenaar071d4272004-06-13 20:20:40 +0000117 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100118filemess(
119 buf_T *buf,
120 char_u *name,
121 char_u *s,
122 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000123{
124 int msg_scroll_save;
125
126 if (msg_silent != 0)
127 return;
128 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
129 /* If it's extremely long, truncate it. */
130 if (STRLEN(IObuff) > IOSIZE - 80)
131 IObuff[IOSIZE - 80] = NUL;
132 STRCAT(IObuff, s);
133 /*
134 * For the first message may have to start a new line.
135 * For further ones overwrite the previous one, reset msg_scroll before
136 * calling filemess().
137 */
138 msg_scroll_save = msg_scroll;
139 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
140 msg_scroll = FALSE;
141 if (!msg_scroll) /* wait a bit when overwriting an error msg */
142 check_for_delay(FALSE);
143 msg_start();
144 msg_scroll = msg_scroll_save;
145 msg_scrolled_ign = TRUE;
146 /* may truncate the message to avoid a hit-return prompt */
147 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
148 msg_clr_eos();
149 out_flush();
150 msg_scrolled_ign = FALSE;
151}
152
153/*
154 * Read lines from file "fname" into the buffer after line "from".
155 *
156 * 1. We allocate blocks with lalloc, as big as possible.
157 * 2. Each block is filled with characters from the file with a single read().
158 * 3. The lines are inserted in the buffer with ml_append().
159 *
160 * (caller must check that fname != NULL, unless READ_STDIN is used)
161 *
162 * "lines_to_skip" is the number of lines that must be skipped
163 * "lines_to_read" is the number of lines that are appended
164 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
165 *
166 * flags:
167 * READ_NEW starting to edit a new buffer
168 * READ_FILTER reading filter output
169 * READ_STDIN read from stdin instead of a file
170 * READ_BUFFER read from curbuf instead of a file (converting after reading
171 * stdin)
172 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200173 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200174 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000175 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100176 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000177 */
178 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100179readfile(
180 char_u *fname,
181 char_u *sfname,
182 linenr_T from,
183 linenr_T lines_to_skip,
184 linenr_T lines_to_read,
185 exarg_T *eap, /* can be NULL! */
186 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000187{
188 int fd = 0;
189 int newfile = (flags & READ_NEW);
190 int check_readonly;
191 int filtering = (flags & READ_FILTER);
192 int read_stdin = (flags & READ_STDIN);
193 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200194 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000195 int set_options = newfile || read_buffer
196 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000197 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
198 colnr_T read_buf_col = 0; /* next char to read from this line */
199 char_u c;
200 linenr_T lnum = from;
201 char_u *ptr = NULL; /* pointer into read buffer */
202 char_u *buffer = NULL; /* read buffer */
203 char_u *new_buffer = NULL; /* init to shut up gcc */
204 char_u *line_start = NULL; /* init to shut up gcc */
205 int wasempty; /* buffer was empty before reading */
206 colnr_T len;
207 long size = 0;
208 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200209 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000210 int skip_read = FALSE;
211#ifdef FEAT_CRYPT
212 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200213 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000214#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200215#ifdef FEAT_PERSISTENT_UNDO
216 context_sha256_T sha_ctx;
217 int read_undo_file = FALSE;
218#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000219 int split = 0; /* number of split lines */
220#define UNKNOWN 0x0fffffff /* file size is unknown */
221 linenr_T linecnt;
222 int error = FALSE; /* errors encountered */
223 int ff_error = EOL_UNKNOWN; /* file format with errors */
224 long linerest = 0; /* remaining chars in line */
225#ifdef UNIX
226 int perm = 0;
227 int swap_mode = -1; /* protection bits for swap file */
228#else
229 int perm;
230#endif
231 int fileformat = 0; /* end-of-line format */
232 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200233 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000234 int file_readonly;
235 linenr_T skip_count = 0;
236 linenr_T read_count = 0;
237 int msg_save = msg_scroll;
238 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
239 * last read was missing the eol */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100240 int try_mac;
241 int try_dos;
242 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000243 int file_rewind = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000244 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000245 linenr_T conv_error = 0; /* line nr with conversion error */
246 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000247 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
248 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000249 int bad_char_behavior = BAD_REPLACE;
250 /* BAD_KEEP, BAD_DROP or character to
251 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000252 char_u *tmpname = NULL; /* name of 'charconvert' output file */
253 int fio_flags = 0;
254 char_u *fenc; /* fileencoding to use */
255 int fenc_alloced; /* fenc_next is in allocated memory */
256 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
257 int advance_fenc = FALSE;
258 long real_size = 0;
Bram Moolenaar13505972019-01-24 15:04:48 +0100259#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000260 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
Bram Moolenaar13505972019-01-24 15:04:48 +0100261# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000262 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
263 'charconvert' next */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000264# endif
Bram Moolenaar13505972019-01-24 15:04:48 +0100265#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000266 int converted = FALSE; /* TRUE if conversion done */
267 int notconverted = FALSE; /* TRUE if conversion wanted but it
268 wasn't possible */
269 char_u conv_rest[CONV_RESTLEN];
270 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200271 buf_T *old_curbuf;
272 char_u *old_b_ffname;
273 char_u *old_b_fname;
274 int using_b_ffname;
275 int using_b_fname;
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200276
Bram Moolenaarc3691332016-04-20 12:49:49 +0200277 au_did_filetype = FALSE; /* reset before triggering any autocommands */
Bram Moolenaarc3691332016-04-20 12:49:49 +0200278
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100279 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000280
281 /*
282 * If there is no file name yet, use the one for the read file.
283 * BF_NOTEDITED is set to reflect this.
284 * Don't do this for a read from a filter.
285 * Only do this when 'cpoptions' contains the 'f' flag.
286 */
287 if (curbuf->b_ffname == NULL
288 && !filtering
289 && fname != NULL
290 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
291 && !(flags & READ_DUMMY))
292 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000293 if (set_rw_fname(fname, sfname) == FAIL)
294 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000295 }
296
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200297 /* Remember the initial values of curbuf, curbuf->b_ffname and
298 * curbuf->b_fname to detect whether they are altered as a result of
299 * executing nasty autocommands. Also check if "fname" and "sfname"
300 * point to one of these values. */
301 old_curbuf = curbuf;
302 old_b_ffname = curbuf->b_ffname;
303 old_b_fname = curbuf->b_fname;
304 using_b_ffname = (fname == curbuf->b_ffname)
305 || (sfname == curbuf->b_ffname);
306 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200307
Bram Moolenaardf177f62005-02-22 08:39:57 +0000308 /* After reading a file the cursor line changes but we don't want to
309 * display the line. */
310 ex_no_reprint = TRUE;
311
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000312 /* don't display the file info for another buffer now */
313 need_fileinfo = FALSE;
314
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315 /*
316 * For Unix: Use the short file name whenever possible.
317 * Avoids problems with networks and when directory names are changed.
318 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
319 * another directory, which we don't detect.
320 */
321 if (sfname == NULL)
322 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200323#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324 fname = sfname;
325#endif
326
Bram Moolenaar071d4272004-06-13 20:20:40 +0000327 /*
328 * The BufReadCmd and FileReadCmd events intercept the reading process by
329 * executing the associated commands instead.
330 */
331 if (!filtering && !read_stdin && !read_buffer)
332 {
333 pos_T pos;
334
335 pos = curbuf->b_op_start;
336
337 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
338 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
339 curbuf->b_op_start.col = 0;
340
341 if (newfile)
342 {
343 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
344 FALSE, curbuf, eap))
345#ifdef FEAT_EVAL
346 return aborting() ? FAIL : OK;
347#else
348 return OK;
349#endif
350 }
351 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
352 FALSE, NULL, eap))
353#ifdef FEAT_EVAL
354 return aborting() ? FAIL : OK;
355#else
356 return OK;
357#endif
358
359 curbuf->b_op_start = pos;
360 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000361
362 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
363 msg_scroll = FALSE; /* overwrite previous file message */
364 else
365 msg_scroll = TRUE; /* don't overwrite previous file message */
366
367 /*
368 * If the name ends in a path separator, we can't open it. Check here,
369 * because reading the file may actually work, but then creating the swap
370 * file may destroy it! Reported on MS-DOS and Win 95.
371 * If the name is too long we might crash further on, quit here.
372 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000373 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000374 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000375 p = fname + STRLEN(fname);
376 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000377 {
378 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
379 msg_end();
380 msg_scroll = msg_save;
381 return FAIL;
382 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000383 }
384
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200385 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000386 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200387#ifdef UNIX
388 /*
389 * On Unix it is possible to read a directory, so we have to
390 * check for it before the mch_open().
391 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000392 perm = mch_getperm(fname);
393 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000394 && !S_ISFIFO(perm) /* ... or fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000395 && !S_ISSOCK(perm) /* ... or socket */
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000396# ifdef OPEN_CHR_FILES
397 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
398 /* ... or a character special file named /dev/fd/<n> */
399# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000400 )
401 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100402 int retval = FAIL;
403
Bram Moolenaar071d4272004-06-13 20:20:40 +0000404 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100405 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100407 retval = NOTDONE;
408 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 else
410 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
411 msg_end();
412 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100413 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000414 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200415#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100416#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000417 /*
418 * MS-Windows allows opening a device, but we will probably get stuck
419 * trying to read it.
420 */
421 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
422 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000423 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000424 msg_end();
425 msg_scroll = msg_save;
426 return FAIL;
427 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000428#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200429 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000430
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200431 /* Set default or forced 'fileformat' and 'binary'. */
432 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000433
434 /*
435 * When opening a new file we take the readonly flag from the file.
436 * Default is r/w, can be set to r/o below.
437 * Don't reset it when in readonly mode
438 * Only set/reset b_p_ro when BF_CHECK_RO is set.
439 */
440 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000441 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000442 curbuf->b_p_ro = FALSE;
443
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200444 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000445 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200446 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000447 if (mch_stat((char *)fname, &st) >= 0)
448 {
449 buf_store_time(curbuf, &st, fname);
450 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000451#ifdef UNIX
452 /*
453 * Use the protection bits of the original file for the swap file.
454 * This makes it possible for others to read the name of the
455 * edited file from the swapfile, but only if they can read the
456 * edited file.
457 * Remove the "write" and "execute" bits for group and others
458 * (they must not write the swapfile).
459 * Add the "read" and "write" bits for the user, otherwise we may
460 * not be able to write to the file ourselves.
461 * Setting the bits is done below, after creating the swap file.
462 */
463 swap_mode = (st.st_mode & 0644) | 0600;
464#endif
465#ifdef FEAT_CW_EDITOR
466 /* Get the FSSpec on MacOS
467 * TODO: Update it properly when the buffer name changes
468 */
469 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
470#endif
471#ifdef VMS
472 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000473 curbuf->b_fab_rat = st.st_fab_rat;
474 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000475#endif
476 }
477 else
478 {
479 curbuf->b_mtime = 0;
480 curbuf->b_mtime_read = 0;
481 curbuf->b_orig_size = 0;
482 curbuf->b_orig_mode = 0;
483 }
484
485 /* Reset the "new file" flag. It will be set again below when the
486 * file doesn't exist. */
487 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
488 }
489
490/*
491 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100492 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000493 */
494 file_readonly = FALSE;
495 if (read_stdin)
496 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100497#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000498 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
499 setmode(0, O_BINARY);
500#endif
501 }
502 else if (!read_buffer)
503 {
504#ifdef USE_MCH_ACCESS
505 if (
506# ifdef UNIX
507 !(perm & 0222) ||
508# endif
509 mch_access((char *)fname, W_OK))
510 file_readonly = TRUE;
511 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
512#else
513 if (!newfile
514 || readonlymode
515 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
516 {
517 file_readonly = TRUE;
518 /* try to open ro */
519 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
520 }
521#endif
522 }
523
524 if (fd < 0) /* cannot open at all */
525 {
526#ifndef UNIX
527 int isdir_f;
528#endif
529 msg_scroll = msg_save;
530#ifndef UNIX
531 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100532 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000533 */
534 isdir_f = (mch_isdir(fname));
535 perm = mch_getperm(fname); /* check if the file exists */
536 if (isdir_f)
537 {
538 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
539 curbuf->b_p_ro = TRUE; /* must use "w!" now */
540 }
541 else
542#endif
543 if (newfile)
544 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200545 if (perm < 0
546#ifdef ENOENT
547 && errno == ENOENT
548#endif
549 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000550 {
551 /*
552 * Set the 'new-file' flag, so that when the file has
553 * been created by someone else, a ":w" will complain.
554 */
555 curbuf->b_flags |= BF_NEW;
556
557 /* Create a swap file now, so that other Vims are warned
558 * that we are editing this file. Don't do this for a
559 * "nofile" or "nowrite" buffer type. */
560#ifdef FEAT_QUICKFIX
561 if (!bt_dontwrite(curbuf))
562#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000563 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000564 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000565 /* SwapExists autocommand may mess things up */
566 if (curbuf != old_curbuf
567 || (using_b_ffname
568 && (old_b_ffname != curbuf->b_ffname))
569 || (using_b_fname
570 && (old_b_fname != curbuf->b_fname)))
571 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100572 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000573 return FAIL;
574 }
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000575 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000576 if (dir_of_file_exists(fname))
577 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
578 else
579 filemess(curbuf, sfname,
580 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000581#ifdef FEAT_VIMINFO
582 /* Even though this is a new file, it might have been
583 * edited before and deleted. Get the old marks. */
584 check_marks_read();
585#endif
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200586 /* Set forced 'fileencoding'. */
587 if (eap != NULL)
588 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000589 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
590 FALSE, curbuf, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000591 /* remember the current fileformat */
592 save_file_ff(curbuf);
593
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +0100594#if defined(FEAT_EVAL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595 if (aborting()) /* autocmds may abort script processing */
596 return FAIL;
597#endif
598 return OK; /* a new file is not an error */
599 }
600 else
601 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000602 filemess(curbuf, sfname, (char_u *)(
603# ifdef EFBIG
604 (errno == EFBIG) ? _("[File too big]") :
605# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200606# ifdef EOVERFLOW
607 (errno == EOVERFLOW) ? _("[File too big]") :
608# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000609 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000610 curbuf->b_p_ro = TRUE; /* must use "w!" now */
611 }
612 }
613
614 return FAIL;
615 }
616
617 /*
618 * Only set the 'ro' flag for readonly files the first time they are
619 * loaded. Help files always get readonly mode
620 */
621 if ((check_readonly && file_readonly) || curbuf->b_help)
622 curbuf->b_p_ro = TRUE;
623
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000624 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000625 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000626 /* Don't change 'eol' if reading from buffer as it will already be
627 * correctly set when reading stdin. */
628 if (!read_buffer)
629 {
630 curbuf->b_p_eol = TRUE;
631 curbuf->b_start_eol = TRUE;
632 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000633 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000634 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000635 }
636
637 /* Create a swap file now, so that other Vims are warned that we are
638 * editing this file.
639 * Don't do this for a "nofile" or "nowrite" buffer type. */
640#ifdef FEAT_QUICKFIX
641 if (!bt_dontwrite(curbuf))
642#endif
643 {
644 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000645 if (!read_stdin && (curbuf != old_curbuf
646 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
647 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
648 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100649 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000650 if (!read_buffer)
651 close(fd);
652 return FAIL;
653 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654#ifdef UNIX
655 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000656 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
657 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100658 {
659 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
660
661 /*
662 * If the group-read bit is set but not the world-read bit, then
663 * the group must be equal to the group of the original file. If
664 * we can't make that happen then reset the group-read bit. This
665 * avoids making the swap file readable to more users when the
666 * primary group of the user is too permissive.
667 */
668 if ((swap_mode & 044) == 040)
669 {
670 stat_T swap_st;
671
672 if (mch_stat((char *)swap_fname, &swap_st) >= 0
673 && st.st_gid != swap_st.st_gid
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200674# ifdef HAVE_FCHOWN
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100675 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200676 == -1
Bram Moolenaar1f131ae2018-05-21 13:39:40 +0200677# endif
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200678 )
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100679 swap_mode &= 0600;
680 }
681
682 (void)mch_setperm(swap_fname, (long)swap_mode);
683 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684#endif
685 }
686
Bram Moolenaar67cf86b2019-04-28 22:25:38 +0200687 // If "Quit" selected at ATTENTION dialog, don't load the file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000688 if (swap_exists_action == SEA_QUIT)
689 {
690 if (!read_buffer && !read_stdin)
691 close(fd);
692 return FAIL;
693 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000694
695 ++no_wait_return; /* don't wait for return yet */
696
697 /*
698 * Set '[ mark to the line above where the lines go (line 1 if zero).
699 */
700 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
701 curbuf->b_op_start.col = 0;
702
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100703 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
704 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
705 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
706
Bram Moolenaar071d4272004-06-13 20:20:40 +0000707 if (!read_buffer)
708 {
709 int m = msg_scroll;
710 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000711
712 /*
713 * The file must be closed again, the autocommands may want to change
714 * the file before reading it.
715 */
716 if (!read_stdin)
717 close(fd); /* ignore errors */
718
719 /*
720 * The output from the autocommands should not overwrite anything and
721 * should not be overwritten: Set msg_scroll, restore its value if no
722 * output was done.
723 */
724 msg_scroll = TRUE;
725 if (filtering)
726 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
727 FALSE, curbuf, eap);
728 else if (read_stdin)
729 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
730 FALSE, curbuf, eap);
731 else if (newfile)
732 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
733 FALSE, curbuf, eap);
734 else
735 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
736 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100737 /* autocommands may have changed it */
738 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
739 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
740 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
741
Bram Moolenaar071d4272004-06-13 20:20:40 +0000742 if (msg_scrolled == n)
743 msg_scroll = m;
744
745#ifdef FEAT_EVAL
746 if (aborting()) /* autocmds may abort script processing */
747 {
748 --no_wait_return;
749 msg_scroll = msg_save;
750 curbuf->b_p_ro = TRUE; /* must use "w!" now */
751 return FAIL;
752 }
753#endif
754 /*
755 * Don't allow the autocommands to change the current buffer.
756 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000757 *
758 * Don't allow the autocommands to change the buffer name either
759 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000760 */
761 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000762 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
763 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000764 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
765 {
766 --no_wait_return;
767 msg_scroll = msg_save;
768 if (fd < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100769 emsg(_("E200: *ReadPre autocommands made the file unreadable"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000770 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100771 emsg(_("E201: *ReadPre autocommands must not change current buffer"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000772 curbuf->b_p_ro = TRUE; /* must use "w!" now */
773 return FAIL;
774 }
775 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000776
777 /* Autocommands may add lines to the file, need to check if it is empty */
778 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
779
780 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
781 {
782 /*
783 * Show the user that we are busy reading the input. Sometimes this
784 * may take a while. When reading from stdin another program may
785 * still be running, don't move the cursor to the last line, unless
786 * always using the GUI.
787 */
788 if (read_stdin)
789 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100790 if (!is_not_a_term())
791 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792#ifndef ALWAYS_USE_GUI
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200793# ifdef VIMDLL
794 if (!gui.in_use)
795# endif
796 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000797#endif
798#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100799 /* Also write a message in the GUI window, if there is one. */
800 if (gui.in_use && !gui.dying && !gui.starting)
801 {
802 p = (char_u *)_("Reading from stdin...");
803 gui_write(p, (int)STRLEN(p));
804 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100806 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000807 }
808 else if (!read_buffer)
809 filemess(curbuf, sfname, (char_u *)"", 0);
810 }
811
812 msg_scroll = FALSE; /* overwrite the file message */
813
814 /*
815 * Set linecnt now, before the "retry" caused by a wrong guess for
816 * fileformat, and after the autocommands, which may change them.
817 */
818 linecnt = curbuf->b_ml.ml_line_count;
819
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000820 /* "++bad=" argument. */
821 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000822 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000823 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000824 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000825 curbuf->b_bad_char = eap->bad_char;
826 }
827 else
828 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000829
Bram Moolenaar071d4272004-06-13 20:20:40 +0000830 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000831 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000832 */
833 if (eap != NULL && eap->force_enc != 0)
834 {
835 fenc = enc_canonize(eap->cmd + eap->force_enc);
836 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000837 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000838 }
839 else if (curbuf->b_p_bin)
840 {
841 fenc = (char_u *)""; /* binary: don't convert */
842 fenc_alloced = FALSE;
843 }
844 else if (curbuf->b_help)
845 {
846 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000847 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000848
849 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
850 * fails it must be latin1.
851 * Always do this when 'encoding' is "utf-8". Otherwise only do
852 * this when needed to avoid [converted] remarks all the time.
853 * It is needed when the first line contains non-ASCII characters.
854 * That is only in *.??x files. */
855 fenc = (char_u *)"latin1";
856 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000857 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000858 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000859 fc = fname[STRLEN(fname) - 1];
860 if (TOLOWER_ASC(fc) == 'x')
861 {
862 /* Read the first line (and a bit more). Immediately rewind to
863 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100864 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200865 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000866 for (p = firstline; p < firstline + len; ++p)
867 if (*p >= 0x80)
868 {
869 c = TRUE;
870 break;
871 }
872 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000873 }
874
875 if (c)
876 {
877 fenc_next = fenc;
878 fenc = (char_u *)"utf-8";
879
880 /* When the file is utf-8 but a character doesn't fit in
881 * 'encoding' don't retry. In help text editing utf-8 bytes
882 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000883 if (!enc_utf8)
884 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000885 }
886 fenc_alloced = FALSE;
887 }
888 else if (*p_fencs == NUL)
889 {
890 fenc = curbuf->b_p_fenc; /* use format from buffer */
891 fenc_alloced = FALSE;
892 }
893 else
894 {
895 fenc_next = p_fencs; /* try items in 'fileencodings' */
896 fenc = next_fenc(&fenc_next);
897 fenc_alloced = TRUE;
898 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000899
900 /*
901 * Jump back here to retry reading the file in different ways.
902 * Reasons to retry:
903 * - encoding conversion failed: try another one from "fenc_next"
904 * - BOM detected and fenc was set, need to setup conversion
905 * - "fileformat" check failed: try another
906 *
907 * Variables set for special retry actions:
908 * "file_rewind" Rewind the file to start reading it again.
909 * "advance_fenc" Advance "fenc" using "fenc_next".
910 * "skip_read" Re-use already read bytes (BOM detected).
911 * "did_iconv" iconv() conversion failed, try 'charconvert'.
912 * "keep_fileformat" Don't reset "fileformat".
913 *
914 * Other status indicators:
915 * "tmpname" When != NULL did conversion with 'charconvert'.
916 * Output file has to be deleted afterwards.
917 * "iconv_fd" When != -1 did conversion with iconv().
918 */
919retry:
920
921 if (file_rewind)
922 {
923 if (read_buffer)
924 {
925 read_buf_lnum = 1;
926 read_buf_col = 0;
927 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200928 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929 {
930 /* Can't rewind the file, give up. */
931 error = TRUE;
932 goto failed;
933 }
934 /* Delete the previously read lines. */
935 while (lnum > from)
936 ml_delete(lnum--, FALSE);
937 file_rewind = FALSE;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000938 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000939 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000940 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000941 curbuf->b_start_bomb = FALSE;
942 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000943 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000944 }
945
946 /*
947 * When retrying with another "fenc" and the first time "fileformat"
948 * will be reset.
949 */
950 if (keep_fileformat)
951 keep_fileformat = FALSE;
952 else
953 {
954 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000955 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000956 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000957 try_unix = try_dos = try_mac = FALSE;
958 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000959 else if (curbuf->b_p_bin)
960 fileformat = EOL_UNIX; /* binary: use Unix format */
961 else if (*p_ffs == NUL)
962 fileformat = get_fileformat(curbuf);/* use format from buffer */
963 else
964 fileformat = EOL_UNKNOWN; /* detect from file */
965 }
966
Bram Moolenaar13505972019-01-24 15:04:48 +0100967#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968 if (iconv_fd != (iconv_t)-1)
969 {
970 /* aborted conversion with iconv(), close the descriptor */
971 iconv_close(iconv_fd);
972 iconv_fd = (iconv_t)-1;
973 }
Bram Moolenaar13505972019-01-24 15:04:48 +0100974#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000975
976 if (advance_fenc)
977 {
978 /*
979 * Try the next entry in 'fileencodings'.
980 */
981 advance_fenc = FALSE;
982
983 if (eap != NULL && eap->force_enc != 0)
984 {
985 /* Conversion given with "++cc=" wasn't possible, read
986 * without conversion. */
987 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000988 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989 if (fenc_alloced)
990 vim_free(fenc);
991 fenc = (char_u *)"";
992 fenc_alloced = FALSE;
993 }
994 else
995 {
996 if (fenc_alloced)
997 vim_free(fenc);
998 if (fenc_next != NULL)
999 {
1000 fenc = next_fenc(&fenc_next);
1001 fenc_alloced = (fenc_next != NULL);
1002 }
1003 else
1004 {
1005 fenc = (char_u *)"";
1006 fenc_alloced = FALSE;
1007 }
1008 }
1009 if (tmpname != NULL)
1010 {
1011 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01001012 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 }
1014 }
1015
1016 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001017 * Conversion may be required when the encoding of the file is different
1018 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001019 */
1020 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00001021 converted = need_conversion(fenc);
1022 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023 {
1024
1025 /* "ucs-bom" means we need to check the first bytes of the file
1026 * for a BOM. */
1027 if (STRCMP(fenc, ENC_UCSBOM) == 0)
1028 fio_flags = FIO_UCSBOM;
1029
1030 /*
1031 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
1032 * done. This is handled below after read(). Prepare the
1033 * fio_flags to avoid having to parse the string each time.
1034 * Also check for Unicode to Latin1 conversion, because iconv()
1035 * appears not to handle this correctly. This works just like
1036 * conversion to UTF-8 except how the resulting character is put in
1037 * the buffer.
1038 */
1039 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1040 fio_flags = get_fio_flags(fenc);
1041
Bram Moolenaar4f974752019-02-17 17:44:42 +01001042#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043 /*
1044 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1045 * is handled with MultiByteToWideChar().
1046 */
1047 if (fio_flags == 0)
1048 fio_flags = get_win_fio_flags(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01001049#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001050
Bram Moolenaar13505972019-01-24 15:04:48 +01001051#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001052 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
1053 if (fio_flags == 0)
1054 fio_flags = get_mac_fio_flags(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01001055#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001056
Bram Moolenaar13505972019-01-24 15:04:48 +01001057#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058 /*
1059 * Try using iconv() if we can't convert internally.
1060 */
1061 if (fio_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001062# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001063 && !did_iconv
Bram Moolenaar13505972019-01-24 15:04:48 +01001064# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001065 )
1066 iconv_fd = (iconv_t)my_iconv_open(
1067 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01001068#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001069
Bram Moolenaar13505972019-01-24 15:04:48 +01001070#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001071 /*
1072 * Use the 'charconvert' expression when conversion is required
1073 * and we can't do it internally or with iconv().
1074 */
1075 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001076 && !read_fifo
Bram Moolenaar13505972019-01-24 15:04:48 +01001077# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001078 && iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001079# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001080 )
1081 {
Bram Moolenaar13505972019-01-24 15:04:48 +01001082# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001083 did_iconv = FALSE;
Bram Moolenaar13505972019-01-24 15:04:48 +01001084# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001085 /* Skip conversion when it's already done (retry for wrong
1086 * "fileformat"). */
1087 if (tmpname == NULL)
1088 {
1089 tmpname = readfile_charconvert(fname, fenc, &fd);
1090 if (tmpname == NULL)
1091 {
1092 /* Conversion failed. Try another one. */
1093 advance_fenc = TRUE;
1094 if (fd < 0)
1095 {
1096 /* Re-opening the original file failed! */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001097 emsg(_("E202: Conversion made file unreadable!"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001098 error = TRUE;
1099 goto failed;
1100 }
1101 goto retry;
1102 }
1103 }
1104 }
1105 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001106#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001107 {
1108 if (fio_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001109#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001110 && iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001111#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001112 )
1113 {
1114 /* Conversion wanted but we can't.
1115 * Try the next conversion in 'fileencodings' */
1116 advance_fenc = TRUE;
1117 goto retry;
1118 }
1119 }
1120 }
1121
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001122 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001123 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001124 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001125 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001126
1127 if (!skip_read)
1128 {
1129 linerest = 0;
1130 filesize = 0;
1131 skip_count = lines_to_skip;
1132 read_count = lines_to_read;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001133 conv_restlen = 0;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001134#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001135 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1136 && curbuf->b_ffname != NULL
1137 && curbuf->b_p_udf
1138 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001139 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001140 && !read_stdin
1141 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001142 if (read_undo_file)
1143 sha256_start(&sha_ctx);
1144#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001145#ifdef FEAT_CRYPT
1146 if (curbuf->b_cryptstate != NULL)
1147 {
1148 /* Need to free the state, but keep the key, don't want to ask for
1149 * it again. */
1150 crypt_free_state(curbuf->b_cryptstate);
1151 curbuf->b_cryptstate = NULL;
1152 }
1153#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001154 }
1155
1156 while (!error && !got_int)
1157 {
1158 /*
1159 * We allocate as much space for the file as we can get, plus
1160 * space for the old line plus room for one terminating NUL.
1161 * The amount is limited by the fact that read() only can read
1162 * upto max_unsigned characters (and other things).
1163 */
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001164 if (!skip_read)
1165 {
Bram Moolenaar30276f22019-01-24 17:59:39 +01001166#if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001167 size = SSIZE_MAX; /* use max I/O size, 52K */
Bram Moolenaar30276f22019-01-24 17:59:39 +01001168#else
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001169 /* Use buffer >= 64K. Add linerest to double the size if the
1170 * line gets very long, to avoid a lot of copying. But don't
1171 * read more than 1 Mbyte at a time, so we can be interrupted.
1172 */
1173 size = 0x10000L + linerest;
1174 if (size > 0x100000L)
1175 size = 0x100000L;
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001176#endif
1177 }
1178
1179 /* Protect against the argument of lalloc() going negative. */
Bram Moolenaar30276f22019-01-24 17:59:39 +01001180 if (size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181 {
1182 ++split;
1183 *ptr = NL; /* split line by inserting a NL */
1184 size = 1;
1185 }
1186 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001187 {
1188 if (!skip_read)
1189 {
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001190 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001191 {
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02001192 if ((new_buffer = lalloc(size + linerest + 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001193 FALSE)) != NULL)
1194 break;
1195 }
1196 if (new_buffer == NULL)
1197 {
1198 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1199 error = TRUE;
1200 break;
1201 }
1202 if (linerest) /* copy characters from the previous buffer */
1203 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1204 vim_free(buffer);
1205 buffer = new_buffer;
1206 ptr = buffer + linerest;
1207 line_start = buffer;
1208
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209 /* May need room to translate into.
1210 * For iconv() we don't really know the required space, use a
1211 * factor ICONV_MULT.
1212 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1213 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1214 * become up to 4 bytes, size must be multiple of 2
1215 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1216 * multiple of 2
1217 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1218 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001219 real_size = (int)size;
Bram Moolenaar13505972019-01-24 15:04:48 +01001220#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001221 if (iconv_fd != (iconv_t)-1)
1222 size = size / ICONV_MULT;
1223 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001224#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001225 if (fio_flags & FIO_LATIN1)
1226 size = size / 2;
1227 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1228 size = (size * 2 / 3) & ~1;
1229 else if (fio_flags & FIO_UCS4)
1230 size = (size * 2 / 3) & ~3;
1231 else if (fio_flags == FIO_UCSBOM)
1232 size = size / ICONV_MULT; /* worst case */
Bram Moolenaar4f974752019-02-17 17:44:42 +01001233#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 else if (fio_flags & FIO_CODEPAGE)
1235 size = size / ICONV_MULT; /* also worst case */
Bram Moolenaar13505972019-01-24 15:04:48 +01001236#endif
1237#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001238 else if (fio_flags & FIO_MACROMAN)
1239 size = size / ICONV_MULT; /* also worst case */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001240#endif
1241
Bram Moolenaar071d4272004-06-13 20:20:40 +00001242 if (conv_restlen > 0)
1243 {
1244 /* Insert unconverted bytes from previous line. */
1245 mch_memmove(ptr, conv_rest, conv_restlen);
1246 ptr += conv_restlen;
1247 size -= conv_restlen;
1248 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001249
1250 if (read_buffer)
1251 {
1252 /*
1253 * Read bytes from curbuf. Used for converting text read
1254 * from stdin.
1255 */
1256 if (read_buf_lnum > from)
1257 size = 0;
1258 else
1259 {
1260 int n, ni;
1261 long tlen;
1262
1263 tlen = 0;
1264 for (;;)
1265 {
1266 p = ml_get(read_buf_lnum) + read_buf_col;
1267 n = (int)STRLEN(p);
1268 if ((int)tlen + n + 1 > size)
1269 {
1270 /* Filled up to "size", append partial line.
1271 * Change NL to NUL to reverse the effect done
1272 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001273 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001274 for (ni = 0; ni < n; ++ni)
1275 {
1276 if (p[ni] == NL)
1277 ptr[tlen++] = NUL;
1278 else
1279 ptr[tlen++] = p[ni];
1280 }
1281 read_buf_col += n;
1282 break;
1283 }
1284 else
1285 {
1286 /* Append whole line and new-line. Change NL
1287 * to NUL to reverse the effect done below. */
1288 for (ni = 0; ni < n; ++ni)
1289 {
1290 if (p[ni] == NL)
1291 ptr[tlen++] = NUL;
1292 else
1293 ptr[tlen++] = p[ni];
1294 }
1295 ptr[tlen++] = NL;
1296 read_buf_col = 0;
1297 if (++read_buf_lnum > from)
1298 {
1299 /* When the last line didn't have an
1300 * end-of-line don't add it now either. */
1301 if (!curbuf->b_p_eol)
1302 --tlen;
1303 size = tlen;
1304 break;
1305 }
1306 }
1307 }
1308 }
1309 }
1310 else
1311 {
1312 /*
1313 * Read bytes from the file.
1314 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001315 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001316 }
1317
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001318#ifdef FEAT_CRYPT
1319 /*
1320 * At start of file: Check for magic number of encryption.
1321 */
1322 if (filesize == 0 && size > 0)
1323 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1324 &filesize, newfile, sfname,
1325 &did_ask_for_key);
1326 /*
1327 * Decrypt the read bytes. This is done before checking for
1328 * EOF because the crypt layer may be buffering.
1329 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001330 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1331 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001332 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001333# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001334 if (crypt_works_inplace(curbuf->b_cryptstate))
1335 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001336# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001337 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
Bram Moolenaar987411d2019-01-18 22:48:34 +01001338# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001339 }
1340 else
1341 {
1342 char_u *newptr = NULL;
1343 int decrypted_size;
1344
1345 decrypted_size = crypt_decode_alloc(
1346 curbuf->b_cryptstate, ptr, size, &newptr);
1347
1348 /* If the crypt layer is buffering, not producing
1349 * anything yet, need to read more. */
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +02001350 if (decrypted_size == 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001351 continue;
1352
1353 if (linerest == 0)
1354 {
1355 /* Simple case: reuse returned buffer (may be
1356 * NULL, checked later). */
1357 new_buffer = newptr;
1358 }
1359 else
1360 {
1361 long_u new_size;
1362
1363 /* Need new buffer to add bytes carried over. */
1364 new_size = (long_u)(decrypted_size + linerest + 1);
1365 new_buffer = lalloc(new_size, FALSE);
1366 if (new_buffer == NULL)
1367 {
1368 do_outofmem_msg(new_size);
1369 error = TRUE;
1370 break;
1371 }
1372
1373 mch_memmove(new_buffer, buffer, linerest);
1374 if (newptr != NULL)
1375 mch_memmove(new_buffer + linerest, newptr,
1376 decrypted_size);
1377 }
1378
1379 if (new_buffer != NULL)
1380 {
1381 vim_free(buffer);
1382 buffer = new_buffer;
1383 new_buffer = NULL;
1384 line_start = buffer;
1385 ptr = buffer + linerest;
1386 }
1387 size = decrypted_size;
1388 }
Bram Moolenaar987411d2019-01-18 22:48:34 +01001389# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001390 }
1391#endif
1392
Bram Moolenaar071d4272004-06-13 20:20:40 +00001393 if (size <= 0)
1394 {
1395 if (size < 0) /* read error */
1396 error = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001397 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001398 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001399 /*
1400 * Reached end-of-file but some trailing bytes could
1401 * not be converted. Truncated file?
1402 */
1403
1404 /* When we did a conversion report an error. */
1405 if (fio_flags != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001406#ifdef USE_ICONV
Bram Moolenaarf453d352008-06-04 17:37:34 +00001407 || iconv_fd != (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001408#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001409 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001410 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001411 if (can_retry)
1412 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001413 if (conv_error == 0)
1414 conv_error = curbuf->b_ml.ml_line_count
1415 - linecnt + 1;
1416 }
1417 /* Remember the first linenr with an illegal byte */
1418 else if (illegal_byte == 0)
1419 illegal_byte = curbuf->b_ml.ml_line_count
1420 - linecnt + 1;
1421 if (bad_char_behavior == BAD_DROP)
1422 {
1423 *(ptr - conv_restlen) = NUL;
1424 conv_restlen = 0;
1425 }
1426 else
1427 {
1428 /* Replace the trailing bytes with the replacement
1429 * character if we were converting; if we weren't,
1430 * leave the UTF8 checking code to do it, as it
1431 * works slightly differently. */
1432 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001433#ifdef USE_ICONV
Bram Moolenaarf453d352008-06-04 17:37:34 +00001434 || iconv_fd != (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001435#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001436 ))
1437 {
1438 while (conv_restlen > 0)
1439 {
1440 *(--ptr) = bad_char_behavior;
1441 --conv_restlen;
1442 }
1443 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001444 fio_flags = 0; /* don't convert this */
Bram Moolenaar13505972019-01-24 15:04:48 +01001445#ifdef USE_ICONV
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001446 if (iconv_fd != (iconv_t)-1)
1447 {
1448 iconv_close(iconv_fd);
1449 iconv_fd = (iconv_t)-1;
1450 }
Bram Moolenaar13505972019-01-24 15:04:48 +01001451#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001452 }
1453 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001454 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001455 }
1456 skip_read = FALSE;
1457
Bram Moolenaar071d4272004-06-13 20:20:40 +00001458 /*
1459 * At start of file (or after crypt magic number): Check for BOM.
1460 * Also check for a BOM for other Unicode encodings, but not after
1461 * converting with 'charconvert' or when a BOM has already been
1462 * found.
1463 */
1464 if ((filesize == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001465#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001466 || (cryptkey != NULL
1467 && filesize == crypt_get_header_len(
1468 crypt_get_method_nr(curbuf)))
Bram Moolenaar13505972019-01-24 15:04:48 +01001469#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470 )
1471 && (fio_flags == FIO_UCSBOM
1472 || (!curbuf->b_p_bomb
1473 && tmpname == NULL
1474 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1475 {
1476 char_u *ccname;
1477 int blen;
1478
1479 /* no BOM detection in a short file or in binary mode */
1480 if (size < 2 || curbuf->b_p_bin)
1481 ccname = NULL;
1482 else
1483 ccname = check_for_bom(ptr, size, &blen,
1484 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1485 if (ccname != NULL)
1486 {
1487 /* Remove BOM from the text */
1488 filesize += blen;
1489 size -= blen;
1490 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001491 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001492 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001493 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001494 curbuf->b_start_bomb = TRUE;
1495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496 }
1497
1498 if (fio_flags == FIO_UCSBOM)
1499 {
1500 if (ccname == NULL)
1501 {
1502 /* No BOM detected: retry with next encoding. */
1503 advance_fenc = TRUE;
1504 }
1505 else
1506 {
1507 /* BOM detected: set "fenc" and jump back */
1508 if (fenc_alloced)
1509 vim_free(fenc);
1510 fenc = ccname;
1511 fenc_alloced = FALSE;
1512 }
1513 /* retry reading without getting new bytes or rewinding */
1514 skip_read = TRUE;
1515 goto retry;
1516 }
1517 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001518
1519 /* Include not converted bytes. */
1520 ptr -= conv_restlen;
1521 size += conv_restlen;
1522 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 /*
1524 * Break here for a read error or end-of-file.
1525 */
1526 if (size <= 0)
1527 break;
1528
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529
Bram Moolenaar13505972019-01-24 15:04:48 +01001530#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001531 if (iconv_fd != (iconv_t)-1)
1532 {
1533 /*
1534 * Attempt conversion of the read bytes to 'encoding' using
1535 * iconv().
1536 */
1537 const char *fromp;
1538 char *top;
1539 size_t from_size;
1540 size_t to_size;
1541
1542 fromp = (char *)ptr;
1543 from_size = size;
1544 ptr += size;
1545 top = (char *)ptr;
1546 to_size = real_size - size;
1547
1548 /*
1549 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001550 * another conversion. Except for when there is no
1551 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001552 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001553 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1554 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001555 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1556 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001557 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001558 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001559 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001560 if (conv_error == 0)
1561 conv_error = readfile_linenr(linecnt,
1562 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001563
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001564 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001565 ++fromp;
1566 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001567 if (bad_char_behavior == BAD_KEEP)
1568 {
1569 *top++ = *(fromp - 1);
1570 --to_size;
1571 }
1572 else if (bad_char_behavior != BAD_DROP)
1573 {
1574 *top++ = bad_char_behavior;
1575 --to_size;
1576 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001577 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001578
1579 if (from_size > 0)
1580 {
1581 /* Some remaining characters, keep them for the next
1582 * round. */
1583 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1584 conv_restlen = (int)from_size;
1585 }
1586
1587 /* move the linerest to before the converted characters */
1588 line_start = ptr - linerest;
1589 mch_memmove(line_start, buffer, (size_t)linerest);
1590 size = (long)((char_u *)top - ptr);
1591 }
Bram Moolenaar13505972019-01-24 15:04:48 +01001592#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001593
Bram Moolenaar4f974752019-02-17 17:44:42 +01001594#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001595 if (fio_flags & FIO_CODEPAGE)
1596 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001597 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001598 WCHAR ucs2buf[3];
1599 int ucs2len;
1600 int codepage = FIO_GET_CP(fio_flags);
1601 int bytelen;
1602 int found_bad;
1603 char replstr[2];
1604
Bram Moolenaar071d4272004-06-13 20:20:40 +00001605 /*
1606 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001607 * a codepage, using standard MS-Windows functions. This
1608 * requires two steps:
1609 * 1. convert from 'fileencoding' to ucs-2
1610 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001611 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001612 * Because there may be illegal bytes AND an incomplete byte
1613 * sequence at the end, we may have to do the conversion one
1614 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001615 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001616
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001617 /* Replacement string for WideCharToMultiByte(). */
1618 if (bad_char_behavior > 0)
1619 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001620 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001621 replstr[0] = '?';
1622 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001623
1624 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001625 * Move the bytes to the end of the buffer, so that we have
1626 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001627 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001628 src = ptr + real_size - size;
1629 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001630
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001631 /*
1632 * Do the conversion.
1633 */
1634 dst = ptr;
1635 size = size;
1636 while (size > 0)
1637 {
1638 found_bad = FALSE;
1639
1640# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1641 if (codepage == CP_UTF8)
1642 {
1643 /* Handle CP_UTF8 input ourselves to be able to handle
1644 * trailing bytes properly.
1645 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001646 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001647 if (bytelen > size)
1648 {
1649 /* Only got some bytes of a character. Normally
1650 * it's put in "conv_rest", but if it's too long
1651 * deal with it as if they were illegal bytes. */
1652 if (bytelen <= CONV_RESTLEN)
1653 break;
1654
1655 /* weird overlong byte sequence */
1656 bytelen = size;
1657 found_bad = TRUE;
1658 }
1659 else
1660 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001661 int u8c = utf_ptr2char(src);
1662
Bram Moolenaar86e01082005-12-29 22:45:34 +00001663 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001664 found_bad = TRUE;
1665 ucs2buf[0] = u8c;
1666 ucs2len = 1;
1667 }
1668 }
1669 else
1670# endif
1671 {
1672 /* We don't know how long the byte sequence is, try
1673 * from one to three bytes. */
1674 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1675 ++bytelen)
1676 {
1677 ucs2len = MultiByteToWideChar(codepage,
1678 MB_ERR_INVALID_CHARS,
1679 (LPCSTR)src, bytelen,
1680 ucs2buf, 3);
1681 if (ucs2len > 0)
1682 break;
1683 }
1684 if (ucs2len == 0)
1685 {
1686 /* If we have only one byte then it's probably an
1687 * incomplete byte sequence. Otherwise discard
1688 * one byte as a bad character. */
1689 if (size == 1)
1690 break;
1691 found_bad = TRUE;
1692 bytelen = 1;
1693 }
1694 }
1695
1696 if (!found_bad)
1697 {
1698 int i;
1699
1700 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1701 if (enc_utf8)
1702 {
1703 /* From UCS-2 to UTF-8. Cannot fail. */
1704 for (i = 0; i < ucs2len; ++i)
1705 dst += utf_char2bytes(ucs2buf[i], dst);
1706 }
1707 else
1708 {
1709 BOOL bad = FALSE;
1710 int dstlen;
1711
1712 /* From UCS-2 to "enc_codepage". If the
1713 * conversion uses the default character "?",
1714 * the data doesn't fit in this encoding. */
1715 dstlen = WideCharToMultiByte(enc_codepage, 0,
1716 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001717 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001718 replstr, &bad);
1719 if (bad)
1720 found_bad = TRUE;
1721 else
1722 dst += dstlen;
1723 }
1724 }
1725
1726 if (found_bad)
1727 {
1728 /* Deal with bytes we can't convert. */
1729 if (can_retry)
1730 goto rewind_retry;
1731 if (conv_error == 0)
1732 conv_error = readfile_linenr(linecnt, ptr, dst);
1733 if (bad_char_behavior != BAD_DROP)
1734 {
1735 if (bad_char_behavior == BAD_KEEP)
1736 {
1737 mch_memmove(dst, src, bytelen);
1738 dst += bytelen;
1739 }
1740 else
1741 *dst++ = bad_char_behavior;
1742 }
1743 }
1744
1745 src += bytelen;
1746 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001747 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001748
1749 if (size > 0)
1750 {
1751 /* An incomplete byte sequence remaining. */
1752 mch_memmove(conv_rest, src, size);
1753 conv_restlen = size;
1754 }
1755
1756 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001757 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001758 }
1759 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001760#endif
1761#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001762 if (fio_flags & FIO_MACROMAN)
1763 {
1764 /*
1765 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001766 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001767 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001768 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001769 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001770 }
1771 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001772#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001773 if (fio_flags != 0)
1774 {
1775 int u8c;
1776 char_u *dest;
1777 char_u *tail = NULL;
1778
1779 /*
1780 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1781 * "enc_utf8" not set: Convert Unicode to Latin1.
1782 * Go from end to start through the buffer, because the number
1783 * of bytes may increase.
1784 * "dest" points to after where the UTF-8 bytes go, "p" points
1785 * to after the next character to convert.
1786 */
1787 dest = ptr + real_size;
1788 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1789 {
1790 p = ptr + size;
1791 if (fio_flags == FIO_UTF8)
1792 {
1793 /* Check for a trailing incomplete UTF-8 sequence */
1794 tail = ptr + size - 1;
1795 while (tail > ptr && (*tail & 0xc0) == 0x80)
1796 --tail;
1797 if (tail + utf_byte2len(*tail) <= ptr + size)
1798 tail = NULL;
1799 else
1800 p = tail;
1801 }
1802 }
1803 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1804 {
1805 /* Check for a trailing byte */
1806 p = ptr + (size & ~1);
1807 if (size & 1)
1808 tail = p;
1809 if ((fio_flags & FIO_UTF16) && p > ptr)
1810 {
1811 /* Check for a trailing leading word */
1812 if (fio_flags & FIO_ENDIAN_L)
1813 {
1814 u8c = (*--p << 8);
1815 u8c += *--p;
1816 }
1817 else
1818 {
1819 u8c = *--p;
1820 u8c += (*--p << 8);
1821 }
1822 if (u8c >= 0xd800 && u8c <= 0xdbff)
1823 tail = p;
1824 else
1825 p += 2;
1826 }
1827 }
1828 else /* FIO_UCS4 */
1829 {
1830 /* Check for trailing 1, 2 or 3 bytes */
1831 p = ptr + (size & ~3);
1832 if (size & 3)
1833 tail = p;
1834 }
1835
1836 /* If there is a trailing incomplete sequence move it to
1837 * conv_rest[]. */
1838 if (tail != NULL)
1839 {
1840 conv_restlen = (int)((ptr + size) - tail);
1841 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1842 size -= conv_restlen;
1843 }
1844
1845
1846 while (p > ptr)
1847 {
1848 if (fio_flags & FIO_LATIN1)
1849 u8c = *--p;
1850 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1851 {
1852 if (fio_flags & FIO_ENDIAN_L)
1853 {
1854 u8c = (*--p << 8);
1855 u8c += *--p;
1856 }
1857 else
1858 {
1859 u8c = *--p;
1860 u8c += (*--p << 8);
1861 }
1862 if ((fio_flags & FIO_UTF16)
1863 && u8c >= 0xdc00 && u8c <= 0xdfff)
1864 {
1865 int u16c;
1866
1867 if (p == ptr)
1868 {
1869 /* Missing leading word. */
1870 if (can_retry)
1871 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001872 if (conv_error == 0)
1873 conv_error = readfile_linenr(linecnt,
1874 ptr, p);
1875 if (bad_char_behavior == BAD_DROP)
1876 continue;
1877 if (bad_char_behavior != BAD_KEEP)
1878 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001879 }
1880
1881 /* found second word of double-word, get the first
1882 * word and compute the resulting character */
1883 if (fio_flags & FIO_ENDIAN_L)
1884 {
1885 u16c = (*--p << 8);
1886 u16c += *--p;
1887 }
1888 else
1889 {
1890 u16c = *--p;
1891 u16c += (*--p << 8);
1892 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001893 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1894 + (u8c & 0x3ff);
1895
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896 /* Check if the word is indeed a leading word. */
1897 if (u16c < 0xd800 || u16c > 0xdbff)
1898 {
1899 if (can_retry)
1900 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001901 if (conv_error == 0)
1902 conv_error = readfile_linenr(linecnt,
1903 ptr, p);
1904 if (bad_char_behavior == BAD_DROP)
1905 continue;
1906 if (bad_char_behavior != BAD_KEEP)
1907 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001909 }
1910 }
1911 else if (fio_flags & FIO_UCS4)
1912 {
1913 if (fio_flags & FIO_ENDIAN_L)
1914 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001915 u8c = (unsigned)*--p << 24;
1916 u8c += (unsigned)*--p << 16;
1917 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001918 u8c += *--p;
1919 }
1920 else /* big endian */
1921 {
1922 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001923 u8c += (unsigned)*--p << 8;
1924 u8c += (unsigned)*--p << 16;
1925 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001926 }
1927 }
1928 else /* UTF-8 */
1929 {
1930 if (*--p < 0x80)
1931 u8c = *p;
1932 else
1933 {
1934 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001935 p -= len;
1936 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001937 if (len == 0)
1938 {
1939 /* Not a valid UTF-8 character, retry with
1940 * another fenc when possible, otherwise just
1941 * report the error. */
1942 if (can_retry)
1943 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001944 if (conv_error == 0)
1945 conv_error = readfile_linenr(linecnt,
1946 ptr, p);
1947 if (bad_char_behavior == BAD_DROP)
1948 continue;
1949 if (bad_char_behavior != BAD_KEEP)
1950 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001951 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001952 }
1953 }
1954 if (enc_utf8) /* produce UTF-8 */
1955 {
1956 dest -= utf_char2len(u8c);
1957 (void)utf_char2bytes(u8c, dest);
1958 }
1959 else /* produce Latin1 */
1960 {
1961 --dest;
1962 if (u8c >= 0x100)
1963 {
1964 /* character doesn't fit in latin1, retry with
1965 * another fenc when possible, otherwise just
1966 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001967 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001968 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001969 if (conv_error == 0)
1970 conv_error = readfile_linenr(linecnt, ptr, p);
1971 if (bad_char_behavior == BAD_DROP)
1972 ++dest;
1973 else if (bad_char_behavior == BAD_KEEP)
1974 *dest = u8c;
1975 else if (eap != NULL && eap->bad_char != 0)
1976 *dest = bad_char_behavior;
1977 else
1978 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 }
1980 else
1981 *dest = u8c;
1982 }
1983 }
1984
1985 /* move the linerest to before the converted characters */
1986 line_start = dest - linerest;
1987 mch_memmove(line_start, buffer, (size_t)linerest);
1988 size = (long)((ptr + real_size) - dest);
1989 ptr = dest;
1990 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001991 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001993 int incomplete_tail = FALSE;
1994
1995 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1996 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001997 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001998 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001999 int l;
2000
2001 if (todo <= 0)
2002 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002003 if (*p >= 0x80)
2004 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002005 /* A length of 1 means it's an illegal byte. Accept
2006 * an incomplete character at the end though, the next
2007 * read() will get the next bytes, we'll check it
2008 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002009 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00002010 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002011 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002012 /* Avoid retrying with a different encoding when
2013 * a truncated file is more likely, or attempting
2014 * to read the rest of an incomplete sequence when
2015 * we have already done so. */
2016 if (p > ptr || filesize > 0)
2017 incomplete_tail = TRUE;
2018 /* Incomplete byte sequence, move it to conv_rest[]
2019 * and try to read the rest of it, unless we've
2020 * already done so. */
2021 if (p > ptr)
2022 {
2023 conv_restlen = todo;
2024 mch_memmove(conv_rest, p, conv_restlen);
2025 size -= conv_restlen;
2026 break;
2027 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002028 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002029 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002030 {
2031 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00002032 * do that, unless at EOF where a truncated
2033 * file is more likely than a conversion error. */
2034 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002035 break;
Bram Moolenaar13505972019-01-24 15:04:48 +01002036#ifdef USE_ICONV
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002037 /* When we did a conversion report an error. */
2038 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2039 conv_error = readfile_linenr(linecnt, ptr, p);
Bram Moolenaar13505972019-01-24 15:04:48 +01002040#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00002041 /* Remember the first linenr with an illegal byte */
2042 if (conv_error == 0 && illegal_byte == 0)
2043 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002044
2045 /* Drop, keep or replace the bad byte. */
2046 if (bad_char_behavior == BAD_DROP)
2047 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002048 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002049 --p;
2050 --size;
2051 }
2052 else if (bad_char_behavior != BAD_KEEP)
2053 *p = bad_char_behavior;
2054 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002055 else
2056 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002057 }
2058 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002059 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002060 {
2061 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002063 /* Retry reading with another conversion. */
Bram Moolenaar13505972019-01-24 15:04:48 +01002064#if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002065 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
2066 /* iconv() failed, try 'charconvert' */
2067 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002068 else
Bram Moolenaar13505972019-01-24 15:04:48 +01002069#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002070 /* use next item from 'fileencodings' */
2071 advance_fenc = TRUE;
2072 file_rewind = TRUE;
2073 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002074 }
2075 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002076
2077 /* count the number of characters (after conversion!) */
2078 filesize += size;
2079
2080 /*
2081 * when reading the first part of a file: guess EOL type
2082 */
2083 if (fileformat == EOL_UNKNOWN)
2084 {
2085 /* First try finding a NL, for Dos and Unix */
2086 if (try_dos || try_unix)
2087 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002088 /* Reset the carriage return counter. */
2089 if (try_mac)
2090 try_mac = 1;
2091
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 for (p = ptr; p < ptr + size; ++p)
2093 {
2094 if (*p == NL)
2095 {
2096 if (!try_unix
2097 || (try_dos && p > ptr && p[-1] == CAR))
2098 fileformat = EOL_DOS;
2099 else
2100 fileformat = EOL_UNIX;
2101 break;
2102 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002103 else if (*p == CAR && try_mac)
2104 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002105 }
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 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002128 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2129 /* Looking for CR but found no end-of-line markers at
2130 * all: use the default format. */
2131 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002132 }
2133
2134 /* No NL found: may use Mac format */
2135 if (fileformat == EOL_UNKNOWN && try_mac)
2136 fileformat = EOL_MAC;
2137
2138 /* Still nothing found? Use first format in 'ffs' */
2139 if (fileformat == EOL_UNKNOWN)
2140 fileformat = default_fileformat();
2141
2142 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002143 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002144 set_fileformat(fileformat, OPT_LOCAL);
2145 }
2146 }
2147
2148 /*
2149 * This loop is executed once for every character read.
2150 * Keep it fast!
2151 */
2152 if (fileformat == EOL_MAC)
2153 {
2154 --ptr;
2155 while (++ptr, --size >= 0)
2156 {
2157 /* catch most common case first */
2158 if ((c = *ptr) != NUL && c != CAR && c != NL)
2159 continue;
2160 if (c == NUL)
2161 *ptr = NL; /* NULs are replaced by newlines! */
2162 else if (c == NL)
2163 *ptr = CAR; /* NLs are replaced by CRs! */
2164 else
2165 {
2166 if (skip_count == 0)
2167 {
2168 *ptr = NUL; /* end of line */
2169 len = (colnr_T) (ptr - line_start + 1);
2170 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2171 {
2172 error = TRUE;
2173 break;
2174 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002175#ifdef FEAT_PERSISTENT_UNDO
2176 if (read_undo_file)
2177 sha256_update(&sha_ctx, line_start, len);
2178#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002179 ++lnum;
2180 if (--read_count == 0)
2181 {
2182 error = TRUE; /* break loop */
2183 line_start = ptr; /* nothing left to write */
2184 break;
2185 }
2186 }
2187 else
2188 --skip_count;
2189 line_start = ptr + 1;
2190 }
2191 }
2192 }
2193 else
2194 {
2195 --ptr;
2196 while (++ptr, --size >= 0)
2197 {
2198 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2199 continue;
2200 if (c == NUL)
2201 *ptr = NL; /* NULs are replaced by newlines! */
2202 else
2203 {
2204 if (skip_count == 0)
2205 {
2206 *ptr = NUL; /* end of line */
2207 len = (colnr_T)(ptr - line_start + 1);
2208 if (fileformat == EOL_DOS)
2209 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002210 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002211 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002212 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002213 ptr[-1] = NUL;
2214 --len;
2215 }
2216 /*
2217 * Reading in Dos format, but no CR-LF found!
2218 * When 'fileformats' includes "unix", delete all
2219 * the lines read so far and start all over again.
2220 * Otherwise give an error message later.
2221 */
2222 else if (ff_error != EOL_DOS)
2223 {
2224 if ( try_unix
2225 && !read_stdin
2226 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002227 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2228 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002229 {
2230 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002231 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002232 set_fileformat(EOL_UNIX, OPT_LOCAL);
2233 file_rewind = TRUE;
2234 keep_fileformat = TRUE;
2235 goto retry;
2236 }
2237 ff_error = EOL_DOS;
2238 }
2239 }
2240 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2241 {
2242 error = TRUE;
2243 break;
2244 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002245#ifdef FEAT_PERSISTENT_UNDO
2246 if (read_undo_file)
2247 sha256_update(&sha_ctx, line_start, len);
2248#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002249 ++lnum;
2250 if (--read_count == 0)
2251 {
2252 error = TRUE; /* break loop */
2253 line_start = ptr; /* nothing left to write */
2254 break;
2255 }
2256 }
2257 else
2258 --skip_count;
2259 line_start = ptr + 1;
2260 }
2261 }
2262 }
2263 linerest = (long)(ptr - line_start);
2264 ui_breakcheck();
2265 }
2266
2267failed:
2268 /* not an error, max. number of lines reached */
2269 if (error && read_count == 0)
2270 error = FALSE;
2271
2272 /*
2273 * If we get EOF in the middle of a line, note the fact and
2274 * complete the line ourselves.
2275 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2276 */
2277 if (!error
2278 && !got_int
2279 && linerest != 0
2280 && !(!curbuf->b_p_bin
2281 && fileformat == EOL_DOS
2282 && *line_start == Ctrl_Z
2283 && ptr == line_start + 1))
2284 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002285 /* remember for when writing */
2286 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 curbuf->b_p_eol = FALSE;
2288 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002289 len = (colnr_T)(ptr - line_start + 1);
2290 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291 error = TRUE;
2292 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002293 {
2294#ifdef FEAT_PERSISTENT_UNDO
2295 if (read_undo_file)
2296 sha256_update(&sha_ctx, line_start, len);
2297#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002298 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002299 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002300 }
2301
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002302 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002303 save_file_ff(curbuf); /* remember the current file format */
2304
2305#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002306 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002307 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002308 crypt_free_state(curbuf->b_cryptstate);
2309 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002310 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002311 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2312 crypt_free_key(cryptkey);
2313 /* Don't set cryptkey to NULL, it's used below as a flag that
2314 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002315#endif
2316
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002317 /* If editing a new file: set 'fenc' for the current buffer.
2318 * Also for ":read ++edit file". */
2319 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002320 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002321 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002322 if (fenc_alloced)
2323 vim_free(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01002324#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00002325 if (iconv_fd != (iconv_t)-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002326 iconv_close(iconv_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327#endif
2328
2329 if (!read_buffer && !read_stdin)
2330 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002331#ifdef HAVE_FD_CLOEXEC
2332 else
2333 {
2334 int fdflags = fcntl(fd, F_GETFD);
2335 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002336 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002337 }
2338#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002339 vim_free(buffer);
2340
2341#ifdef HAVE_DUP
2342 if (read_stdin)
2343 {
2344 /* Use stderr for stdin, makes shell commands work. */
2345 close(0);
Bram Moolenaar42335f52018-09-13 15:33:43 +02002346 vim_ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002347 }
2348#endif
2349
Bram Moolenaar071d4272004-06-13 20:20:40 +00002350 if (tmpname != NULL)
2351 {
2352 mch_remove(tmpname); /* delete converted file */
2353 vim_free(tmpname);
2354 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002355 --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
Bram Moolenaard569bb02018-08-11 13:57:20 +02002429 if (S_ISFIFO(perm)) /* fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 {
2431 STRCAT(IObuff, _("[fifo]"));
2432 c = TRUE;
2433 }
Bram Moolenaard569bb02018-08-11 13:57:20 +02002434 if (S_ISSOCK(perm)) /* or socket */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002435 {
2436 STRCAT(IObuff, _("[socket]"));
2437 c = TRUE;
2438 }
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002439# ifdef OPEN_CHR_FILES
2440 if (S_ISCHR(perm)) /* or character special */
2441 {
2442 STRCAT(IObuff, _("[character special]"));
2443 c = TRUE;
2444 }
2445# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002446#endif
2447 if (curbuf->b_p_ro)
2448 {
2449 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2450 c = TRUE;
2451 }
2452 if (read_no_eol_lnum)
2453 {
2454 msg_add_eol();
2455 c = TRUE;
2456 }
2457 if (ff_error == EOL_DOS)
2458 {
2459 STRCAT(IObuff, _("[CR missing]"));
2460 c = TRUE;
2461 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002462 if (split)
2463 {
2464 STRCAT(IObuff, _("[long lines split]"));
2465 c = TRUE;
2466 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002467 if (notconverted)
2468 {
2469 STRCAT(IObuff, _("[NOT converted]"));
2470 c = TRUE;
2471 }
2472 else if (converted)
2473 {
2474 STRCAT(IObuff, _("[converted]"));
2475 c = TRUE;
2476 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002477#ifdef FEAT_CRYPT
2478 if (cryptkey != NULL)
2479 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002480 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002481 c = TRUE;
2482 }
2483#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002484 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002486 sprintf((char *)IObuff + STRLEN(IObuff),
2487 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002488 c = TRUE;
2489 }
2490 else if (illegal_byte > 0)
2491 {
2492 sprintf((char *)IObuff + STRLEN(IObuff),
2493 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2494 c = TRUE;
2495 }
Bram Moolenaar13505972019-01-24 15:04:48 +01002496 else if (error)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 {
2498 STRCAT(IObuff, _("[READ ERRORS]"));
2499 c = TRUE;
2500 }
2501 if (msg_add_fileformat(fileformat))
2502 c = TRUE;
2503#ifdef FEAT_CRYPT
2504 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002505 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002506 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 else
2508#endif
2509 msg_add_lines(c, (long)linecnt, filesize);
2510
Bram Moolenaard23a8232018-02-10 18:45:26 +01002511 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 msg_scrolled_ign = TRUE;
2513#ifdef ALWAYS_USE_GUI
2514 /* Don't show the message when reading stdin, it would end up in a
2515 * message box (which might be shown when exiting!) */
2516 if (read_stdin || read_buffer)
2517 p = msg_may_trunc(FALSE, IObuff);
2518 else
2519#endif
Bram Moolenaar32526b32019-01-19 17:43:09 +01002520 p = (char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002521 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002522 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002523 /* Need to repeat the message after redrawing when:
2524 * - When reading from stdin (the screen will be cleared next).
2525 * - When restart_edit is set (otherwise there will be a delay
2526 * before redrawing).
2527 * - When the screen was scrolled but there is no wait-return
2528 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002529 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002530 msg_scrolled_ign = FALSE;
2531 }
2532
2533 /* with errors writing the file requires ":w!" */
2534 if (newfile && (error
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002535 || conv_error != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01002536 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002537 curbuf->b_p_ro = TRUE;
2538
2539 u_clearline(); /* cannot use "U" command after adding lines */
2540
2541 /*
2542 * In Ex mode: cursor at last new line.
2543 * Otherwise: cursor at first new line.
2544 */
2545 if (exmode_active)
2546 curwin->w_cursor.lnum = from + linecnt;
2547 else
2548 curwin->w_cursor.lnum = from + 1;
2549 check_cursor_lnum();
2550 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2551
2552 /*
2553 * Set '[ and '] marks to the newly read lines.
2554 */
2555 curbuf->b_op_start.lnum = from + 1;
2556 curbuf->b_op_start.col = 0;
2557 curbuf->b_op_end.lnum = from + linecnt;
2558 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002559
Bram Moolenaar4f974752019-02-17 17:44:42 +01002560#ifdef MSWIN
Bram Moolenaar03f48552006-02-28 23:52:23 +00002561 /*
2562 * Work around a weird problem: When a file has two links (only
2563 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002564 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002565 * It's correct again after reading the file, thus reset the timestamp
2566 * here.
2567 */
2568 if (newfile && !read_stdin && !read_buffer
2569 && mch_stat((char *)fname, &st) >= 0)
2570 {
2571 buf_store_time(curbuf, &st, fname);
2572 curbuf->b_mtime_read = curbuf->b_mtime;
2573 }
2574#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002575 }
2576 msg_scroll = msg_save;
2577
2578#ifdef FEAT_VIMINFO
2579 /*
2580 * Get the marks before executing autocommands, so they can be used there.
2581 */
2582 check_marks_read();
2583#endif
2584
Bram Moolenaar071d4272004-06-13 20:20:40 +00002585 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002586 * We remember if the last line of the read didn't have
2587 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2588 * or writing the read again with 'binary' on. The latter is required
2589 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002590 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002591 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002592
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002593 /* When reloading a buffer put the cursor at the first line that is
2594 * different. */
2595 if (flags & READ_KEEP_UNDO)
2596 u_find_first_changed();
2597
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002598#ifdef FEAT_PERSISTENT_UNDO
2599 /*
2600 * When opening a new file locate undo info and read it.
2601 */
2602 if (read_undo_file)
2603 {
2604 char_u hash[UNDO_HASH_SIZE];
2605
2606 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002607 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002608 }
2609#endif
2610
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002611 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612 {
2613 int m = msg_scroll;
2614 int n = msg_scrolled;
2615
2616 /* Save the fileformat now, otherwise the buffer will be considered
2617 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002618 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619 save_file_ff(curbuf);
2620
2621 /*
2622 * The output from the autocommands should not overwrite anything and
2623 * should not be overwritten: Set msg_scroll, restore its value if no
2624 * output was done.
2625 */
2626 msg_scroll = TRUE;
2627 if (filtering)
2628 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2629 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002630 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002631 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002632 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2633 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002634 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2635 /*
2636 * EVENT_FILETYPE was not triggered but the buffer already has a
2637 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2638 */
2639 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2640 TRUE, curbuf);
2641 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 else
2643 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2644 FALSE, NULL, eap);
2645 if (msg_scrolled == n)
2646 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002647# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002648 if (aborting()) /* autocmds may abort script processing */
2649 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002650# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002651 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002652
2653 if (recoverymode && error)
2654 return FAIL;
2655 return OK;
2656}
2657
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002658#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002659/*
2660 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2661 * which is the name of files used for process substitution output by
2662 * some shells on some operating systems, e.g., bash on SunOS.
2663 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2664 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002665 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002666is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002667{
2668 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2669 && VIM_ISDIGIT(fname[8])
2670 && *skipdigits(fname + 9) == NUL
2671 && (fname[9] != NUL
2672 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2673}
2674#endif
2675
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002676/*
2677 * From the current line count and characters read after that, estimate the
2678 * line number where we are now.
2679 * Used for error messages that include a line number.
2680 */
2681 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002682readfile_linenr(
2683 linenr_T linecnt, /* line count before reading more bytes */
2684 char_u *p, /* start of more bytes read */
2685 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002686{
2687 char_u *s;
2688 linenr_T lnum;
2689
2690 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2691 for (s = p; s < endp; ++s)
2692 if (*s == '\n')
2693 ++lnum;
2694 return lnum;
2695}
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002696
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002698 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2699 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002700 * Returns OK or FAIL.
2701 */
2702 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002703prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002704{
Bram Moolenaar13505972019-01-24 15:04:48 +01002705 eap->cmd = alloc(15 + (unsigned)STRLEN(buf->b_p_fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002706 if (eap->cmd == NULL)
2707 return FAIL;
2708
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002709 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2710 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002711 eap->bad_char = buf->b_bad_char;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002712 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002713
2714 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002715 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002716 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002717 return OK;
2718}
2719
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002720/*
2721 * Set default or forced 'fileformat' and 'binary'.
2722 */
2723 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002724set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002725{
2726 /* set default 'fileformat' */
2727 if (set_options)
2728 {
2729 if (eap != NULL && eap->force_ff != 0)
2730 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2731 else if (*p_ffs != NUL)
2732 set_fileformat(default_fileformat(), OPT_LOCAL);
2733 }
2734
2735 /* set or reset 'binary' */
2736 if (eap != NULL && eap->force_bin != 0)
2737 {
2738 int oldval = curbuf->b_p_bin;
2739
2740 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2741 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2742 }
2743}
2744
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002745/*
2746 * Set forced 'fileencoding'.
2747 */
2748 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002749set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002750{
2751 if (eap->force_enc != 0)
2752 {
2753 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2754
2755 if (fenc != NULL)
2756 set_string_option_direct((char_u *)"fenc", -1,
2757 fenc, OPT_FREE|OPT_LOCAL, 0);
2758 vim_free(fenc);
2759 }
2760}
2761
Bram Moolenaar071d4272004-06-13 20:20:40 +00002762/*
2763 * Find next fileencoding to use from 'fileencodings'.
2764 * "pp" points to fenc_next. It's advanced to the next item.
2765 * When there are no more items, an empty string is returned and *pp is set to
2766 * NULL.
2767 * When *pp is not set to NULL, the result is in allocated memory.
2768 */
2769 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002770next_fenc(char_u **pp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002771{
2772 char_u *p;
2773 char_u *r;
2774
2775 if (**pp == NUL)
2776 {
2777 *pp = NULL;
2778 return (char_u *)"";
2779 }
2780 p = vim_strchr(*pp, ',');
2781 if (p == NULL)
2782 {
2783 r = enc_canonize(*pp);
2784 *pp += STRLEN(*pp);
2785 }
2786 else
2787 {
2788 r = vim_strnsave(*pp, (int)(p - *pp));
2789 *pp = p + 1;
2790 if (r != NULL)
2791 {
2792 p = enc_canonize(r);
2793 vim_free(r);
2794 r = p;
2795 }
2796 }
2797 if (r == NULL) /* out of memory */
2798 {
2799 r = (char_u *)"";
2800 *pp = NULL;
2801 }
2802 return r;
2803}
2804
Bram Moolenaar13505972019-01-24 15:04:48 +01002805#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806/*
2807 * Convert a file with the 'charconvert' expression.
2808 * This closes the file which is to be read, converts it and opens the
2809 * resulting file for reading.
2810 * Returns name of the resulting converted file (the caller should delete it
2811 * after reading it).
2812 * Returns NULL if the conversion failed ("*fdp" is not set) .
2813 */
2814 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002815readfile_charconvert(
2816 char_u *fname, /* name of input file */
2817 char_u *fenc, /* converted from */
2818 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002819{
2820 char_u *tmpname;
Bram Moolenaar32526b32019-01-19 17:43:09 +01002821 char *errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002823 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824 if (tmpname == NULL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002825 errmsg = _("Can't find temp file for conversion");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002826 else
2827 {
2828 close(*fdp); /* close the input file, ignore errors */
2829 *fdp = -1;
2830 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2831 fname, tmpname) == FAIL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002832 errmsg = _("Conversion with 'charconvert' failed");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002833 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2834 O_RDONLY | O_EXTRA, 0)) < 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002835 errmsg = _("can't read output of 'charconvert'");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002836 }
2837
2838 if (errmsg != NULL)
2839 {
2840 /* Don't use emsg(), it breaks mappings, the retry with
2841 * another type of conversion might still work. */
Bram Moolenaar32526b32019-01-19 17:43:09 +01002842 msg(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002843 if (tmpname != NULL)
2844 {
2845 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002846 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002847 }
2848 }
2849
2850 /* If the input file is closed, open it (caller should check for error). */
2851 if (*fdp < 0)
2852 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2853
2854 return tmpname;
2855}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002856#endif
2857
Bram Moolenaar13505972019-01-24 15:04:48 +01002858
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859#ifdef FEAT_VIMINFO
2860/*
2861 * Read marks for the current buffer from the viminfo file, when we support
2862 * buffer marks and the buffer has a name.
2863 */
2864 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002865check_marks_read(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002866{
2867 if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0
2868 && curbuf->b_ffname != NULL)
Bram Moolenaard812df62008-11-09 12:46:09 +00002869 read_viminfo(NULL, VIF_WANT_MARKS);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002870
2871 /* Always set b_marks_read; needed when 'viminfo' is changed to include
2872 * the ' parameter after opening a buffer. */
2873 curbuf->b_marks_read = TRUE;
2874}
2875#endif
2876
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002877#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002878/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002879 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002880 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2881 * *filesizep are updated.
2882 * Return the (new) encryption key, NULL for no encryption.
2883 */
2884 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002885check_for_cryptkey(
2886 char_u *cryptkey, /* previous encryption key or NULL */
2887 char_u *ptr, /* pointer to read bytes */
2888 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002889 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002890 int newfile, /* editing a new buffer */
2891 char_u *fname, /* file name to display */
2892 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002893{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002894 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002895 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002896
2897 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002898 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002899 /* Mark the buffer as read-only until the decryption has taken place.
2900 * Avoids accidentally overwriting the file with garbage. */
2901 curbuf->b_p_ro = TRUE;
2902
Bram Moolenaar2be79502014-08-13 21:58:28 +02002903 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002904 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002905 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002906 {
2907 if (*curbuf->b_p_key)
2908 cryptkey = curbuf->b_p_key;
2909 else
2910 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002911 /* When newfile is TRUE, store the typed key in the 'key'
2912 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002913 * Don't ask for the key again when first time Enter was hit.
2914 * Happens when retrying to detect encoding. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002915 smsg(_(need_key_msg), fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002916 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002917 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002918 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002919 *did_ask = TRUE;
2920
Bram Moolenaar071d4272004-06-13 20:20:40 +00002921 /* check if empty key entered */
2922 if (cryptkey != NULL && *cryptkey == NUL)
2923 {
2924 if (cryptkey != curbuf->b_p_key)
2925 vim_free(cryptkey);
2926 cryptkey = NULL;
2927 }
2928 }
2929 }
2930
2931 if (cryptkey != NULL)
2932 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002933 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002934
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002935 curbuf->b_cryptstate = crypt_create_from_header(
2936 method, cryptkey, ptr);
2937 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002938
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002939 /* Remove cryptmethod specific header from the text. */
2940 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02002941 if (*sizep <= header_len)
2942 /* invalid header, buffer can't be encrypted */
2943 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002944 *filesizep += header_len;
2945 *sizep -= header_len;
2946 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
2947
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002948 /* Restore the read-only flag. */
2949 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002950 }
2951 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002952 /* When starting to edit a new file which does not have encryption, clear
2953 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002954 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002955 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2956
2957 return cryptkey;
2958}
Bram Moolenaar80794b12010-06-13 05:20:42 +02002959#endif /* FEAT_CRYPT */
2960
Bram Moolenaar071d4272004-06-13 20:20:40 +00002961#ifdef UNIX
2962 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002963set_file_time(
2964 char_u *fname,
2965 time_t atime, /* access time */
2966 time_t mtime) /* modification time */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002967{
2968# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
2969 struct utimbuf buf;
2970
2971 buf.actime = atime;
2972 buf.modtime = mtime;
2973 (void)utime((char *)fname, &buf);
2974# else
2975# if defined(HAVE_UTIMES)
2976 struct timeval tvp[2];
2977
2978 tvp[0].tv_sec = atime;
2979 tvp[0].tv_usec = 0;
2980 tvp[1].tv_sec = mtime;
2981 tvp[1].tv_usec = 0;
2982# ifdef NeXT
2983 (void)utimes((char *)fname, tvp);
2984# else
2985 (void)utimes((char *)fname, (const struct timeval *)&tvp);
2986# endif
2987# endif
2988# endif
2989}
2990#endif /* UNIX */
2991
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002992#if defined(VMS) && !defined(MIN)
2993/* Older DECC compiler for VAX doesn't define MIN() */
2994# define MIN(a, b) ((a) < (b) ? (a) : (b))
2995#endif
2996
Bram Moolenaar071d4272004-06-13 20:20:40 +00002997/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00002998 * Return TRUE if a file appears to be read-only from the file permissions.
2999 */
3000 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003001check_file_readonly(
3002 char_u *fname, /* full path to file */
3003 int perm) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003004{
3005#ifndef USE_MCH_ACCESS
3006 int fd = 0;
3007#endif
3008
3009 return (
3010#ifdef USE_MCH_ACCESS
3011# ifdef UNIX
3012 (perm & 0222) == 0 ||
3013# endif
3014 mch_access((char *)fname, W_OK)
3015#else
3016 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
3017 ? TRUE : (close(fd), FALSE)
3018#endif
3019 );
3020}
3021
3022
3023/*
Bram Moolenaar292ad192005-12-11 21:29:51 +00003024 * buf_write() - write to file "fname" lines "start" through "end"
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 *
3026 * We do our own buffering here because fwrite() is so slow.
3027 *
Bram Moolenaar292ad192005-12-11 21:29:51 +00003028 * If "forceit" is true, we don't care for errors when attempting backups.
3029 * In case of an error everything possible is done to restore the original
Bram Moolenaare37d50a2008-08-06 17:06:04 +00003030 * file. But when "forceit" is TRUE, we risk losing it.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003031 *
3032 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
3033 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003034 *
3035 * This function must NOT use NameBuff (because it's called by autowrite()).
3036 *
3037 * return FAIL for failure, OK otherwise
3038 */
3039 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003040buf_write(
3041 buf_T *buf,
3042 char_u *fname,
3043 char_u *sfname,
3044 linenr_T start,
3045 linenr_T end,
3046 exarg_T *eap, /* for forced 'ff' and 'fenc', can be
Bram Moolenaar071d4272004-06-13 20:20:40 +00003047 NULL! */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003048 int append, /* append to the file */
3049 int forceit,
3050 int reset_changed,
3051 int filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003052{
3053 int fd;
3054 char_u *backup = NULL;
3055 int backup_copy = FALSE; /* copy the original file? */
3056 int dobackup;
3057 char_u *ffname;
3058 char_u *wfname = NULL; /* name of file to write to */
3059 char_u *s;
3060 char_u *ptr;
3061 char_u c;
3062 int len;
3063 linenr_T lnum;
3064 long nchars;
3065 char_u *errmsg = NULL;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003066 int errmsg_allocated = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067 char_u *errnum = NULL;
3068 char_u *buffer;
3069 char_u smallbuf[SMBUFSIZE];
3070 char_u *backup_ext;
3071 int bufsize;
3072 long perm; /* file permissions */
3073 int retval = OK;
3074 int newfile = FALSE; /* TRUE if file doesn't exist yet */
3075 int msg_save = msg_scroll;
3076 int overwriting; /* TRUE if writing over original */
3077 int no_eol = FALSE; /* no end-of-line written */
3078 int device = FALSE; /* writing to a device */
Bram Moolenaar8767f522016-07-01 17:17:39 +02003079 stat_T st_old;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003080 int prev_got_int = got_int;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02003081 int checking_conversion;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003082 int file_readonly = FALSE; /* overwritten file is read-only */
3083 static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
Bram Moolenaara06ecab2016-07-16 14:47:36 +02003084#if defined(UNIX) /*XXX fix me sometime? */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003085 int made_writable = FALSE; /* 'w' bit has been set */
3086#endif
3087 /* writing everything */
3088 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003089 linenr_T old_line_count = buf->b_ml.ml_line_count;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003090 int attr;
3091 int fileformat;
3092 int write_bin;
3093 struct bw_info write_info; /* info for buf_write_bytes() */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094 int converted = FALSE;
3095 int notconverted = FALSE;
3096 char_u *fenc; /* effective 'fileencoding' */
3097 char_u *fenc_tofree = NULL; /* allocated "fenc" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098#ifdef HAS_BW_FLAGS
3099 int wb_flags = 0;
3100#endif
3101#ifdef HAVE_ACL
3102 vim_acl_T acl = NULL; /* ACL copied from original file to
3103 backup or new file */
3104#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +02003105#ifdef FEAT_PERSISTENT_UNDO
3106 int write_undo_file = FALSE;
3107 context_sha256_T sha_ctx;
3108#endif
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003109 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003110
3111 if (fname == NULL || *fname == NUL) /* safety check */
3112 return FAIL;
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003113 if (buf->b_ml.ml_mfp == NULL)
3114 {
3115 /* This can happen during startup when there is a stray "w" in the
3116 * vimrc file. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003117 emsg(_(e_emptybuf));
Bram Moolenaar70d60e92009-12-31 13:53:33 +00003118 return FAIL;
3119 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003120
3121 /*
3122 * Disallow writing from .exrc and .vimrc in current directory for
3123 * security reasons.
3124 */
3125 if (check_secure())
3126 return FAIL;
3127
3128 /* Avoid a crash for a long name. */
3129 if (STRLEN(fname) >= MAXPATHL)
3130 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003131 emsg(_(e_longname));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003132 return FAIL;
3133 }
3134
Bram Moolenaar071d4272004-06-13 20:20:40 +00003135 /* must init bw_conv_buf and bw_iconv_fd before jumping to "fail" */
3136 write_info.bw_conv_buf = NULL;
3137 write_info.bw_conv_error = FALSE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00003138 write_info.bw_conv_error_lnum = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003139 write_info.bw_restlen = 0;
Bram Moolenaar13505972019-01-24 15:04:48 +01003140#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00003141 write_info.bw_iconv_fd = (iconv_t)-1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003142#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02003143#ifdef FEAT_CRYPT
3144 write_info.bw_buffer = buf;
3145#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003146
Bram Moolenaardf177f62005-02-22 08:39:57 +00003147 /* After writing a file changedtick changes but we don't want to display
3148 * the line. */
3149 ex_no_reprint = TRUE;
3150
Bram Moolenaar071d4272004-06-13 20:20:40 +00003151 /*
3152 * If there is no file name yet, use the one for the written file.
3153 * BF_NOTEDITED is set to reflect this (in case the write fails).
3154 * Don't do this when the write is for a filter command.
Bram Moolenaar292ad192005-12-11 21:29:51 +00003155 * Don't do this when appending.
3156 * Only do this when 'cpoptions' contains the 'F' flag.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157 */
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003158 if (buf->b_ffname == NULL
3159 && reset_changed
Bram Moolenaar071d4272004-06-13 20:20:40 +00003160 && whole
3161 && buf == curbuf
Bram Moolenaar402d2fe2005-04-15 21:00:38 +00003162#ifdef FEAT_QUICKFIX
3163 && !bt_nofile(buf)
3164#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165 && !filtering
Bram Moolenaar292ad192005-12-11 21:29:51 +00003166 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003167 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
3168 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003169 if (set_rw_fname(fname, sfname) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003170 return FAIL;
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003171 buf = curbuf; /* just in case autocmds made "buf" invalid */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003172 }
3173
3174 if (sfname == NULL)
3175 sfname = fname;
3176 /*
3177 * For Unix: Use the short file name whenever possible.
3178 * Avoids problems with networks and when directory names are changed.
3179 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
3180 * another directory, which we don't detect
3181 */
3182 ffname = fname; /* remember full fname */
3183#ifdef UNIX
3184 fname = sfname;
3185#endif
3186
3187 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
3188 overwriting = TRUE;
3189 else
3190 overwriting = FALSE;
3191
3192 if (exiting)
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003193 settmode(TMODE_COOK); /* when exiting allow typeahead now */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003194
3195 ++no_wait_return; /* don't wait for return yet */
3196
3197 /*
3198 * Set '[ and '] marks to the lines to be written.
3199 */
3200 buf->b_op_start.lnum = start;
3201 buf->b_op_start.col = 0;
3202 buf->b_op_end.lnum = end;
3203 buf->b_op_end.col = 0;
3204
Bram Moolenaar071d4272004-06-13 20:20:40 +00003205 {
3206 aco_save_T aco;
3207 int buf_ffname = FALSE;
3208 int buf_sfname = FALSE;
3209 int buf_fname_f = FALSE;
3210 int buf_fname_s = FALSE;
3211 int did_cmd = FALSE;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003212 int nofile_err = FALSE;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003213 int empty_memline = (buf->b_ml.ml_mfp == NULL);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003214 bufref_T bufref;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003215
3216 /*
Bram Moolenaar84a05ac2013-05-06 04:24:17 +02003217 * Apply PRE autocommands.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003218 * Set curbuf to the buffer to be written.
3219 * Careful: The autocommands may call buf_write() recursively!
3220 */
3221 if (ffname == buf->b_ffname)
3222 buf_ffname = TRUE;
3223 if (sfname == buf->b_sfname)
3224 buf_sfname = TRUE;
3225 if (fname == buf->b_ffname)
3226 buf_fname_f = TRUE;
3227 if (fname == buf->b_sfname)
3228 buf_fname_s = TRUE;
3229
3230 /* set curwin/curbuf to buf and save a few things */
3231 aucmd_prepbuf(&aco, buf);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003232 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003233
3234 if (append)
3235 {
3236 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
3237 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003238 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003239#ifdef FEAT_QUICKFIX
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00003240 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003241 nofile_err = TRUE;
3242 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003243#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003244 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003245 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003246 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003247 }
3248 else if (filtering)
3249 {
3250 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
3251 NULL, sfname, FALSE, curbuf, eap);
3252 }
3253 else if (reset_changed && whole)
3254 {
Bram Moolenaar39fc42e2011-09-02 11:56:20 +02003255 int was_changed = curbufIsChanged();
3256
3257 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
3258 sfname, sfname, FALSE, curbuf, eap);
3259 if (did_cmd)
3260 {
3261 if (was_changed && !curbufIsChanged())
3262 {
3263 /* Written everything correctly and BufWriteCmd has reset
3264 * 'modified': Correct the undo information so that an
3265 * undo now sets 'modified'. */
3266 u_unchanged(curbuf);
3267 u_update_save_nr(curbuf);
3268 }
3269 }
3270 else
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003271 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003272#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003273 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003274 nofile_err = TRUE;
3275 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003276#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003277 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003278 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003279 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 }
3281 else
3282 {
3283 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
3284 sfname, sfname, FALSE, curbuf, eap)))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003285 {
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003286#ifdef FEAT_QUICKFIX
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003287 if (overwriting && bt_nofile(curbuf))
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003288 nofile_err = TRUE;
3289 else
Bram Moolenaarb1b715d2006-01-21 22:09:43 +00003290#endif
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003291 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003292 sfname, sfname, FALSE, curbuf, eap);
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003293 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294 }
3295
3296 /* restore curwin/curbuf and a few other things */
3297 aucmd_restbuf(&aco);
3298
3299 /*
3300 * In three situations we return here and don't write the file:
3301 * 1. the autocommands deleted or unloaded the buffer.
3302 * 2. The autocommands abort script processing.
3303 * 3. If one of the "Cmd" autocommands was executed.
3304 */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003305 if (!bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003306 buf = NULL;
Bram Moolenaar7c626922005-02-07 22:01:03 +00003307 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
Bram Moolenaar1e015462005-09-25 22:16:38 +00003308 || did_cmd || nofile_err
3309#ifdef FEAT_EVAL
3310 || aborting()
3311#endif
3312 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003313 {
3314 --no_wait_return;
3315 msg_scroll = msg_save;
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003316 if (nofile_err)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003317 emsg(_("E676: No matching autocommands for acwrite buffer"));
Bram Moolenaar21cf8232004-07-16 20:18:37 +00003318
Bram Moolenaar1e015462005-09-25 22:16:38 +00003319 if (nofile_err
3320#ifdef FEAT_EVAL
3321 || aborting()
3322#endif
3323 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003324 /* An aborting error, interrupt or exception in the
3325 * autocommands. */
3326 return FAIL;
3327 if (did_cmd)
3328 {
3329 if (buf == NULL)
3330 /* The buffer was deleted. We assume it was written
3331 * (can't retry anyway). */
3332 return OK;
3333 if (overwriting)
3334 {
3335 /* Assume the buffer was written, update the timestamp. */
3336 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00003337 if (append)
3338 buf->b_flags &= ~BF_NEW;
3339 else
3340 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003341 }
Bram Moolenaar292ad192005-12-11 21:29:51 +00003342 if (reset_changed && buf->b_changed && !append
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003343 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344 /* Buffer still changed, the autocommands didn't work
3345 * properly. */
3346 return FAIL;
3347 return OK;
3348 }
3349#ifdef FEAT_EVAL
3350 if (!aborting())
3351#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003352 emsg(_("E203: Autocommands deleted or unloaded buffer to be written"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003353 return FAIL;
3354 }
3355
3356 /*
3357 * The autocommands may have changed the number of lines in the file.
3358 * When writing the whole file, adjust the end.
3359 * When writing part of the file, assume that the autocommands only
3360 * changed the number of lines that are to be written (tricky!).
3361 */
3362 if (buf->b_ml.ml_line_count != old_line_count)
3363 {
3364 if (whole) /* write all */
3365 end = buf->b_ml.ml_line_count;
3366 else if (buf->b_ml.ml_line_count > old_line_count) /* more lines */
3367 end += buf->b_ml.ml_line_count - old_line_count;
3368 else /* less lines */
3369 {
3370 end -= old_line_count - buf->b_ml.ml_line_count;
3371 if (end < start)
3372 {
3373 --no_wait_return;
3374 msg_scroll = msg_save;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003375 emsg(_("E204: Autocommand changed number of lines in unexpected way"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00003376 return FAIL;
3377 }
3378 }
3379 }
3380
3381 /*
3382 * The autocommands may have changed the name of the buffer, which may
3383 * be kept in fname, ffname and sfname.
3384 */
3385 if (buf_ffname)
3386 ffname = buf->b_ffname;
3387 if (buf_sfname)
3388 sfname = buf->b_sfname;
3389 if (buf_fname_f)
3390 fname = buf->b_ffname;
3391 if (buf_fname_s)
3392 fname = buf->b_sfname;
3393 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003394
3395#ifdef FEAT_NETBEANS_INTG
Bram Moolenaarb26e6322010-05-22 21:34:09 +02003396 if (netbeans_active() && isNetbeansBuffer(buf))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003397 {
3398 if (whole)
3399 {
3400 /*
3401 * b_changed can be 0 after an undo, but we still need to write
3402 * the buffer to NetBeans.
3403 */
3404 if (buf->b_changed || isNetbeansModified(buf))
3405 {
Bram Moolenaar009b2592004-10-24 19:18:58 +00003406 --no_wait_return; /* may wait for return now */
3407 msg_scroll = msg_save;
3408 netbeans_save_buffer(buf); /* no error checking... */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003409 return retval;
3410 }
3411 else
3412 {
3413 errnum = (char_u *)"E656: ";
Bram Moolenaared0e7452008-06-27 19:17:34 +00003414 errmsg = (char_u *)_("NetBeans disallows writes of unmodified buffers");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003415 buffer = NULL;
3416 goto fail;
3417 }
3418 }
3419 else
3420 {
3421 errnum = (char_u *)"E657: ";
3422 errmsg = (char_u *)_("Partial writes disallowed for NetBeans buffers");
3423 buffer = NULL;
3424 goto fail;
3425 }
3426 }
3427#endif
3428
3429 if (shortmess(SHM_OVER) && !exiting)
3430 msg_scroll = FALSE; /* overwrite previous file message */
3431 else
3432 msg_scroll = TRUE; /* don't overwrite previous file message */
3433 if (!filtering)
3434 filemess(buf,
3435#ifndef UNIX
3436 sfname,
3437#else
3438 fname,
3439#endif
3440 (char_u *)"", 0); /* show that we are busy */
3441 msg_scroll = FALSE; /* always overwrite the file message now */
3442
3443 buffer = alloc(BUFSIZE);
3444 if (buffer == NULL) /* can't allocate big buffer, use small
3445 * one (to be able to write when out of
3446 * memory) */
3447 {
3448 buffer = smallbuf;
3449 bufsize = SMBUFSIZE;
3450 }
3451 else
3452 bufsize = BUFSIZE;
3453
3454 /*
3455 * Get information about original file (if there is one).
3456 */
Bram Moolenaar53076832015-12-31 19:53:21 +01003457#if defined(UNIX)
Bram Moolenaar6f192452007-11-08 19:49:02 +00003458 st_old.st_dev = 0;
3459 st_old.st_ino = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460 perm = -1;
3461 if (mch_stat((char *)fname, &st_old) < 0)
3462 newfile = TRUE;
3463 else
3464 {
3465 perm = st_old.st_mode;
3466 if (!S_ISREG(st_old.st_mode)) /* not a file */
3467 {
3468 if (S_ISDIR(st_old.st_mode))
3469 {
3470 errnum = (char_u *)"E502: ";
3471 errmsg = (char_u *)_("is a directory");
3472 goto fail;
3473 }
3474 if (mch_nodetype(fname) != NODE_WRITABLE)
3475 {
3476 errnum = (char_u *)"E503: ";
3477 errmsg = (char_u *)_("is not a file or writable device");
3478 goto fail;
3479 }
3480 /* It's a device of some kind (or a fifo) which we can write to
3481 * but for which we can't make a backup. */
3482 device = TRUE;
3483 newfile = TRUE;
3484 perm = -1;
3485 }
3486 }
3487#else /* !UNIX */
3488 /*
3489 * Check for a writable device name.
3490 */
3491 c = mch_nodetype(fname);
3492 if (c == NODE_OTHER)
3493 {
3494 errnum = (char_u *)"E503: ";
3495 errmsg = (char_u *)_("is not a file or writable device");
3496 goto fail;
3497 }
3498 if (c == NODE_WRITABLE)
3499 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003500# if defined(MSWIN)
Bram Moolenaar043545e2006-10-10 16:44:07 +00003501 /* MS-Windows allows opening a device, but we will probably get stuck
3502 * trying to write to it. */
3503 if (!p_odev)
3504 {
3505 errnum = (char_u *)"E796: ";
3506 errmsg = (char_u *)_("writing to device disabled with 'opendevice' option");
3507 goto fail;
3508 }
3509# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003510 device = TRUE;
3511 newfile = TRUE;
3512 perm = -1;
3513 }
3514 else
3515 {
3516 perm = mch_getperm(fname);
3517 if (perm < 0)
3518 newfile = TRUE;
3519 else if (mch_isdir(fname))
3520 {
3521 errnum = (char_u *)"E502: ";
3522 errmsg = (char_u *)_("is a directory");
3523 goto fail;
3524 }
3525 if (overwriting)
3526 (void)mch_stat((char *)fname, &st_old);
3527 }
3528#endif /* !UNIX */
3529
3530 if (!device && !newfile)
3531 {
3532 /*
3533 * Check if the file is really writable (when renaming the file to
3534 * make a backup we won't discover it later).
3535 */
Bram Moolenaar5386a122007-06-28 20:02:32 +00003536 file_readonly = check_file_readonly(fname, (int)perm);
3537
Bram Moolenaar071d4272004-06-13 20:20:40 +00003538 if (!forceit && file_readonly)
3539 {
3540 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3541 {
3542 errnum = (char_u *)"E504: ";
3543 errmsg = (char_u *)_(err_readonly);
3544 }
3545 else
3546 {
3547 errnum = (char_u *)"E505: ";
3548 errmsg = (char_u *)_("is read-only (add ! to override)");
3549 }
3550 goto fail;
3551 }
3552
3553 /*
3554 * Check if the timestamp hasn't changed since reading the file.
3555 */
3556 if (overwriting)
3557 {
3558 retval = check_mtime(buf, &st_old);
3559 if (retval == FAIL)
3560 goto fail;
3561 }
3562 }
3563
3564#ifdef HAVE_ACL
3565 /*
3566 * For systems that support ACL: get the ACL from the original file.
3567 */
3568 if (!newfile)
3569 acl = mch_get_acl(fname);
3570#endif
3571
3572 /*
3573 * If 'backupskip' is not empty, don't make a backup for some files.
3574 */
3575 dobackup = (p_wb || p_bk || *p_pm != NUL);
3576#ifdef FEAT_WILDIGN
3577 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
3578 dobackup = FALSE;
3579#endif
3580
3581 /*
3582 * Save the value of got_int and reset it. We don't want a previous
3583 * interruption cancel writing, only hitting CTRL-C while writing should
3584 * abort it.
3585 */
3586 prev_got_int = got_int;
3587 got_int = FALSE;
3588
3589 /* Mark the buffer as 'being saved' to prevent changed buffer warnings */
3590 buf->b_saving = TRUE;
3591
3592 /*
3593 * If we are not appending or filtering, the file exists, and the
3594 * 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
3595 * When 'patchmode' is set also make a backup when appending.
3596 *
3597 * Do not make any backup, if 'writebackup' and 'backup' are both switched
3598 * off. This helps when editing large files on almost-full disks.
3599 */
3600 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
3601 {
Bram Moolenaar4f974752019-02-17 17:44:42 +01003602#if defined(UNIX) || defined(MSWIN)
Bram Moolenaar8767f522016-07-01 17:17:39 +02003603 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003604#endif
3605
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003606 if ((bkc & BKC_YES) || append) /* "yes" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003607 backup_copy = TRUE;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003608#if defined(UNIX) || defined(MSWIN)
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003609 else if ((bkc & BKC_AUTO)) /* "auto" */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003610 {
3611 int i;
3612
3613# ifdef UNIX
3614 /*
3615 * Don't rename the file when:
3616 * - it's a hard link
3617 * - it's a symbolic link
3618 * - we don't have write permission in the directory
3619 * - we can't set the owner/group of the new file
3620 */
3621 if (st_old.st_nlink > 1
3622 || mch_lstat((char *)fname, &st) < 0
3623 || st.st_dev != st_old.st_dev
Bram Moolenaara5792f52005-11-23 21:25:05 +00003624 || st.st_ino != st_old.st_ino
3625# ifndef HAVE_FCHOWN
3626 || st.st_uid != st_old.st_uid
3627 || st.st_gid != st_old.st_gid
3628# endif
3629 )
Bram Moolenaar071d4272004-06-13 20:20:40 +00003630 backup_copy = TRUE;
3631 else
Bram Moolenaar03f48552006-02-28 23:52:23 +00003632# else
Bram Moolenaar4f974752019-02-17 17:44:42 +01003633# ifdef MSWIN
Bram Moolenaar03f48552006-02-28 23:52:23 +00003634 /* On NTFS file systems hard links are possible. */
3635 if (mch_is_linked(fname))
3636 backup_copy = TRUE;
3637 else
3638# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003639# endif
3640 {
3641 /*
3642 * Check if we can create a file and set the owner/group to
3643 * the ones from the original file.
3644 * First find a file name that doesn't exist yet (use some
3645 * arbitrary numbers).
3646 */
3647 STRCPY(IObuff, fname);
3648 for (i = 4913; ; i += 123)
3649 {
3650 sprintf((char *)gettail(IObuff), "%d", i);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003651 if (mch_lstat((char *)IObuff, &st) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003652 break;
3653 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00003654 fd = mch_open((char *)IObuff,
3655 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003656 if (fd < 0) /* can't write in directory */
3657 backup_copy = TRUE;
3658 else
3659 {
3660# ifdef UNIX
Bram Moolenaara5792f52005-11-23 21:25:05 +00003661# ifdef HAVE_FCHOWN
Bram Moolenaar42335f52018-09-13 15:33:43 +02003662 vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
Bram Moolenaara5792f52005-11-23 21:25:05 +00003663# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 if (mch_stat((char *)IObuff, &st) < 0
3665 || st.st_uid != st_old.st_uid
3666 || st.st_gid != st_old.st_gid
Bram Moolenaar78a15312009-05-15 19:33:18 +00003667 || (long)st.st_mode != perm)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668 backup_copy = TRUE;
3669# endif
Bram Moolenaar98358622005-11-28 22:58:23 +00003670 /* Close the file before removing it, on MS-Windows we
3671 * can't delete an open file. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003672 close(fd);
Bram Moolenaar98358622005-11-28 22:58:23 +00003673 mch_remove(IObuff);
Bram Moolenaar3479c5d2010-08-08 18:46:06 +02003674# ifdef MSWIN
3675 /* MS-Windows may trigger a virus scanner to open the
3676 * file, we can't delete it then. Keep trying for half a
3677 * second. */
3678 {
3679 int try;
3680
3681 for (try = 0; try < 10; ++try)
3682 {
3683 if (mch_lstat((char *)IObuff, &st) < 0)
3684 break;
3685 ui_delay(50L, TRUE); /* wait 50 msec */
3686 mch_remove(IObuff);
3687 }
3688 }
3689# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003690 }
3691 }
3692 }
3693
Bram Moolenaar071d4272004-06-13 20:20:40 +00003694 /*
3695 * Break symlinks and/or hardlinks if we've been asked to.
3696 */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003697 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003698 {
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003699# ifdef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003700 int lstat_res;
3701
3702 lstat_res = mch_lstat((char *)fname, &st);
3703
3704 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003705 if ((bkc & BKC_BREAKSYMLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706 && lstat_res == 0
3707 && st.st_ino != st_old.st_ino)
3708 backup_copy = FALSE;
3709
3710 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003711 if ((bkc & BKC_BREAKHARDLINK)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003712 && st_old.st_nlink > 1
3713 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
3714 backup_copy = FALSE;
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003715# else
Bram Moolenaar4f974752019-02-17 17:44:42 +01003716# if defined(MSWIN)
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003717 /* Symlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003718 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003719 backup_copy = FALSE;
3720
3721 /* Hardlinks. */
Bram Moolenaarb8ee25a2014-09-23 15:45:08 +02003722 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
Bram Moolenaar12b559e2013-06-12 22:41:37 +02003723 backup_copy = FALSE;
3724# endif
3725# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003726 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003727
3728#endif
3729
3730 /* make sure we have a valid backup extension to use */
3731 if (*p_bex == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003732 backup_ext = (char_u *)".bak";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003733 else
3734 backup_ext = p_bex;
3735
3736 if (backup_copy
3737 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
3738 {
3739 int bfd;
3740 char_u *copybuf, *wp;
3741 int some_error = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +02003742 stat_T st_new;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003743 char_u *dirp;
3744 char_u *rootname;
Bram Moolenaar4f974752019-02-17 17:44:42 +01003745#if defined(UNIX) || defined(MSWIN)
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003746 char_u *p;
3747#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003748#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003749 int did_set_shortname;
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003750 mode_t umask_save;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003751#endif
3752
3753 copybuf = alloc(BUFSIZE + 1);
3754 if (copybuf == NULL)
3755 {
3756 some_error = TRUE; /* out of memory */
3757 goto nobackup;
3758 }
3759
3760 /*
3761 * Try to make the backup in each directory in the 'bdir' option.
3762 *
3763 * Unix semantics has it, that we may have a writable file,
3764 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
3765 * - the directory is not writable,
3766 * - the file may be a symbolic link,
3767 * - the file may belong to another user/group, etc.
3768 *
3769 * For these reasons, the existing writable file must be truncated
3770 * and reused. Creation of a backup COPY will be attempted.
3771 */
3772 dirp = p_bdir;
3773 while (*dirp)
3774 {
3775#ifdef UNIX
3776 st_new.st_ino = 0;
3777 st_new.st_dev = 0;
3778 st_new.st_gid = 0;
3779#endif
3780
3781 /*
3782 * Isolate one directory name, using an entry in 'bdir'.
3783 */
3784 (void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003785
Bram Moolenaar4f974752019-02-17 17:44:42 +01003786#if defined(UNIX) || defined(MSWIN)
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003787 p = copybuf + STRLEN(copybuf);
3788 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
3789 // Ends with '//', use full path
3790 if ((p = make_percent_swname(copybuf, fname)) != NULL)
3791 {
3792 backup = modname(p, backup_ext, FALSE);
3793 vim_free(p);
3794 }
3795#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003796 rootname = get_file_in_dir(fname, copybuf);
3797 if (rootname == NULL)
3798 {
3799 some_error = TRUE; /* out of memory */
3800 goto nobackup;
3801 }
3802
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003803#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003804 did_set_shortname = FALSE;
3805#endif
3806
3807 /*
3808 * May try twice if 'shortname' not set.
3809 */
3810 for (;;)
3811 {
3812 /*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003813 * Make the backup file name.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003814 */
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003815 if (backup == NULL)
3816 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 rootname, backup_ext, FALSE);
3818 if (backup == NULL)
3819 {
3820 vim_free(rootname);
3821 some_error = TRUE; /* out of memory */
3822 goto nobackup;
3823 }
3824
3825 /*
3826 * Check if backup file already exists.
3827 */
3828 if (mch_stat((char *)backup, &st_new) >= 0)
3829 {
3830#ifdef UNIX
3831 /*
3832 * Check if backup file is same as original file.
3833 * May happen when modname() gave the same file back.
3834 * E.g. silly link, or file name-length reached.
3835 * If we don't check here, we either ruin the file
3836 * when copying or erase it after writing. jw.
3837 */
3838 if (st_new.st_dev == st_old.st_dev
3839 && st_new.st_ino == st_old.st_ino)
3840 {
Bram Moolenaard23a8232018-02-10 18:45:26 +01003841 VIM_CLEAR(backup); /* no backup file to delete */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003842 /*
3843 * may try again with 'shortname' set
3844 */
3845 if (!(buf->b_shortname || buf->b_p_sn))
3846 {
3847 buf->b_shortname = TRUE;
3848 did_set_shortname = TRUE;
3849 continue;
3850 }
3851 /* setting shortname didn't help */
3852 if (did_set_shortname)
3853 buf->b_shortname = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 break;
3855 }
3856#endif
3857
3858 /*
3859 * If we are not going to keep the backup file, don't
3860 * delete an existing one, try to use another name.
3861 * Change one character, just before the extension.
3862 */
3863 if (!p_bk)
3864 {
3865 wp = backup + STRLEN(backup) - 1
3866 - STRLEN(backup_ext);
3867 if (wp < backup) /* empty file name ??? */
3868 wp = backup;
3869 *wp = 'z';
3870 while (*wp > 'a'
3871 && mch_stat((char *)backup, &st_new) >= 0)
3872 --*wp;
3873 /* They all exist??? Must be something wrong. */
3874 if (*wp == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01003875 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003876 }
3877 }
3878 break;
3879 }
3880 vim_free(rootname);
3881
3882 /*
3883 * Try to create the backup file
3884 */
3885 if (backup != NULL)
3886 {
3887 /* remove old backup, if present */
3888 mch_remove(backup);
3889 /* Open with O_EXCL to avoid the file being created while
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003890 * we were sleeping (symlink hacker attack?). Reset umask
3891 * if possible to avoid mch_setperm() below. */
3892#ifdef UNIX
3893 umask_save = umask(0);
3894#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003895 bfd = mch_open((char *)backup,
Bram Moolenaara5792f52005-11-23 21:25:05 +00003896 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
3897 perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003898#ifdef UNIX
3899 (void)umask(umask_save);
3900#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003901 if (bfd < 0)
Bram Moolenaard23a8232018-02-10 18:45:26 +01003902 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003903 else
3904 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003905 /* Set file protection same as original file, but
3906 * strip s-bit. Only needed if umask() wasn't used
3907 * above. */
3908#ifndef UNIX
Bram Moolenaar071d4272004-06-13 20:20:40 +00003909 (void)mch_setperm(backup, perm & 0777);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01003910#else
Bram Moolenaar071d4272004-06-13 20:20:40 +00003911 /*
3912 * Try to set the group of the backup same as the
3913 * original file. If this fails, set the protection
3914 * bits for the group same as the protection bits for
3915 * others.
3916 */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003917 if (st_new.st_gid != st_old.st_gid
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918# ifdef HAVE_FCHOWN /* sequent-ptx lacks fchown() */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003919 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
Bram Moolenaar071d4272004-06-13 20:20:40 +00003920# endif
3921 )
3922 mch_setperm(backup,
3923 (perm & 0707) | ((perm & 07) << 3));
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003924# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003925 mch_copy_sec(fname, backup);
3926# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003927#endif
3928
3929 /*
3930 * copy the file.
3931 */
3932 write_info.bw_fd = bfd;
3933 write_info.bw_buf = copybuf;
3934#ifdef HAS_BW_FLAGS
3935 write_info.bw_flags = FIO_NOCONVERT;
3936#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003937 while ((write_info.bw_len = read_eintr(fd, copybuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00003938 BUFSIZE)) > 0)
3939 {
3940 if (buf_write_bytes(&write_info) == FAIL)
3941 {
3942 errmsg = (char_u *)_("E506: Can't write to backup file (add ! to override)");
3943 break;
3944 }
3945 ui_breakcheck();
3946 if (got_int)
3947 {
3948 errmsg = (char_u *)_(e_interr);
3949 break;
3950 }
3951 }
3952
3953 if (close(bfd) < 0 && errmsg == NULL)
3954 errmsg = (char_u *)_("E507: Close error for backup file (add ! to override)");
3955 if (write_info.bw_len < 0)
3956 errmsg = (char_u *)_("E508: Can't read file for backup (add ! to override)");
3957#ifdef UNIX
3958 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
3959#endif
3960#ifdef HAVE_ACL
3961 mch_set_acl(backup, acl);
3962#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003963#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00003964 mch_copy_sec(fname, backup);
3965#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003966 break;
3967 }
3968 }
3969 }
3970 nobackup:
3971 close(fd); /* ignore errors for closing read file */
3972 vim_free(copybuf);
3973
3974 if (backup == NULL && errmsg == NULL)
3975 errmsg = (char_u *)_("E509: Cannot create backup file (add ! to override)");
3976 /* ignore errors when forceit is TRUE */
3977 if ((some_error || errmsg != NULL) && !forceit)
3978 {
3979 retval = FAIL;
3980 goto fail;
3981 }
3982 errmsg = NULL;
3983 }
3984 else
3985 {
3986 char_u *dirp;
3987 char_u *p;
3988 char_u *rootname;
3989
3990 /*
3991 * Make a backup by renaming the original file.
3992 */
3993 /*
3994 * If 'cpoptions' includes the "W" flag, we don't want to
3995 * overwrite a read-only file. But rename may be possible
3996 * anyway, thus we need an extra check here.
3997 */
3998 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
3999 {
4000 errnum = (char_u *)"E504: ";
4001 errmsg = (char_u *)_(err_readonly);
4002 goto fail;
4003 }
4004
4005 /*
4006 *
4007 * Form the backup file name - change path/fo.o.h to
4008 * path/fo.o.h.bak Try all directories in 'backupdir', first one
4009 * that works is used.
4010 */
4011 dirp = p_bdir;
4012 while (*dirp)
4013 {
4014 /*
4015 * Isolate one directory name and make the backup file name.
4016 */
4017 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004018
Bram Moolenaar4f974752019-02-17 17:44:42 +01004019#if defined(UNIX) || defined(MSWIN)
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004020 p = IObuff + STRLEN(IObuff);
4021 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
4022 // path ends with '//', use full path
4023 if ((p = make_percent_swname(IObuff, fname)) != NULL)
4024 {
4025 backup = modname(p, backup_ext, FALSE);
4026 vim_free(p);
4027 }
4028#endif
4029 if (backup == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004030 {
Bram Moolenaarb782ba42018-08-07 21:39:28 +02004031 rootname = get_file_in_dir(fname, IObuff);
4032 if (rootname == NULL)
4033 backup = NULL;
4034 else
4035 {
4036 backup = buf_modname(
4037 (buf->b_p_sn || buf->b_shortname),
4038 rootname, backup_ext, FALSE);
4039 vim_free(rootname);
4040 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004041 }
4042
4043 if (backup != NULL)
4044 {
4045 /*
4046 * If we are not going to keep the backup file, don't
4047 * delete an existing one, try to use another name.
4048 * Change one character, just before the extension.
4049 */
4050 if (!p_bk && mch_getperm(backup) >= 0)
4051 {
4052 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
4053 if (p < backup) /* empty file name ??? */
4054 p = backup;
4055 *p = 'z';
4056 while (*p > 'a' && mch_getperm(backup) >= 0)
4057 --*p;
4058 /* They all exist??? Must be something wrong! */
4059 if (*p == 'a')
Bram Moolenaard23a8232018-02-10 18:45:26 +01004060 VIM_CLEAR(backup);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004061 }
4062 }
4063 if (backup != NULL)
4064 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004065 /*
Bram Moolenaarbfd8fc02005-09-20 23:22:24 +00004066 * Delete any existing backup and move the current version
4067 * to the backup. For safety, we don't remove the backup
4068 * until the write has finished successfully. And if the
4069 * 'backup' option is set, leave it around.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070 */
4071 /*
4072 * If the renaming of the original file to the backup file
4073 * works, quit here.
4074 */
4075 if (vim_rename(fname, backup) == 0)
4076 break;
4077
Bram Moolenaard23a8232018-02-10 18:45:26 +01004078 VIM_CLEAR(backup); /* don't do the rename below */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079 }
4080 }
4081 if (backup == NULL && !forceit)
4082 {
4083 errmsg = (char_u *)_("E510: Can't make backup file (add ! to override)");
4084 goto fail;
4085 }
4086 }
4087 }
4088
Bram Moolenaar53076832015-12-31 19:53:21 +01004089#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004090 /* When using ":w!" and the file was read-only: make it writable */
4091 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
4092 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
4093 {
4094 perm |= 0200;
4095 (void)mch_setperm(fname, perm);
4096 made_writable = TRUE;
4097 }
4098#endif
4099
Bram Moolenaar910f66f2006-04-05 20:41:53 +00004100 /* When using ":w!" and writing to the current file, 'readonly' makes no
Bram Moolenaar4399ef42005-02-12 14:29:27 +00004101 * sense, reset it, unless 'Z' appears in 'cpoptions'. */
4102 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004103 {
4104 buf->b_p_ro = FALSE;
4105#ifdef FEAT_TITLE
4106 need_maketitle = TRUE; /* set window title later */
4107#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 status_redraw_all(); /* redraw status lines later */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004109 }
4110
4111 if (end > buf->b_ml.ml_line_count)
4112 end = buf->b_ml.ml_line_count;
4113 if (buf->b_ml.ml_flags & ML_EMPTY)
4114 start = end + 1;
4115
4116 /*
4117 * If the original file is being overwritten, there is a small chance that
4118 * we crash in the middle of writing. Therefore the file is preserved now.
4119 * This makes all block numbers positive so that recovery does not need
4120 * the original file.
4121 * Don't do this if there is a backup file and we are exiting.
4122 */
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004123 if (reset_changed && !newfile && overwriting
Bram Moolenaar071d4272004-06-13 20:20:40 +00004124 && !(exiting && backup != NULL))
4125 {
4126 ml_preserve(buf, FALSE);
4127 if (got_int)
4128 {
4129 errmsg = (char_u *)_(e_interr);
4130 goto restore_backup;
4131 }
4132 }
4133
Bram Moolenaar071d4272004-06-13 20:20:40 +00004134#ifdef VMS
4135 vms_remove_version(fname); /* remove version */
4136#endif
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00004137 /* Default: write the file directly. May write to a temp file for
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 * multi-byte conversion. */
4139 wfname = fname;
4140
Bram Moolenaar071d4272004-06-13 20:20:40 +00004141 /* Check for forced 'fileencoding' from "++opt=val" argument. */
4142 if (eap != NULL && eap->force_enc != 0)
4143 {
4144 fenc = eap->cmd + eap->force_enc;
4145 fenc = enc_canonize(fenc);
4146 fenc_tofree = fenc;
4147 }
4148 else
4149 fenc = buf->b_p_fenc;
4150
4151 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004152 * Check if the file needs to be converted.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004153 */
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00004154 converted = need_conversion(fenc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004155
4156 /*
4157 * Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
4158 * Latin1 to Unicode conversion. This is handled in buf_write_bytes().
4159 * Prepare the flags for it and allocate bw_conv_buf when needed.
4160 */
4161 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
4162 {
4163 wb_flags = get_fio_flags(fenc);
4164 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
4165 {
4166 /* Need to allocate a buffer to translate into. */
4167 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
4168 write_info.bw_conv_buflen = bufsize * 2;
4169 else /* FIO_UCS4 */
4170 write_info.bw_conv_buflen = bufsize * 4;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004171 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004172 if (write_info.bw_conv_buf == NULL)
4173 end = 0;
4174 }
4175 }
4176
Bram Moolenaar4f974752019-02-17 17:44:42 +01004177#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
4179 {
4180 /* Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4: */
4181 write_info.bw_conv_buflen = bufsize * 4;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004182 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 if (write_info.bw_conv_buf == NULL)
4184 end = 0;
4185 }
Bram Moolenaar13505972019-01-24 15:04:48 +01004186#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004187
Bram Moolenaar13505972019-01-24 15:04:48 +01004188#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
4190 {
4191 write_info.bw_conv_buflen = bufsize * 3;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004192 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004193 if (write_info.bw_conv_buf == NULL)
4194 end = 0;
4195 }
Bram Moolenaar13505972019-01-24 15:04:48 +01004196#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004197
Bram Moolenaar13505972019-01-24 15:04:48 +01004198#if defined(FEAT_EVAL) || defined(USE_ICONV)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 if (converted && wb_flags == 0)
4200 {
Bram Moolenaar13505972019-01-24 15:04:48 +01004201# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004202 /*
4203 * Use iconv() conversion when conversion is needed and it's not done
4204 * internally.
4205 */
4206 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
4207 enc_utf8 ? (char_u *)"utf-8" : p_enc);
4208 if (write_info.bw_iconv_fd != (iconv_t)-1)
4209 {
4210 /* We're going to use iconv(), allocate a buffer to convert in. */
4211 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02004212 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004213 if (write_info.bw_conv_buf == NULL)
4214 end = 0;
4215 write_info.bw_first = TRUE;
4216 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004217# ifdef FEAT_EVAL
Bram Moolenaar13505972019-01-24 15:04:48 +01004218 else
4219# endif
4220# endif
4221
4222# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00004223 /*
4224 * When the file needs to be converted with 'charconvert' after
4225 * writing, write to a temp file instead and let the conversion
4226 * overwrite the original file.
4227 */
4228 if (*p_ccv != NUL)
4229 {
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004230 wfname = vim_tempname('w', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004231 if (wfname == NULL) /* Can't write without a tempfile! */
4232 {
4233 errmsg = (char_u *)_("E214: Can't find temp file for writing");
4234 goto restore_backup;
4235 }
4236 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004237# endif
Bram Moolenaar13505972019-01-24 15:04:48 +01004238 }
4239#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004240 if (converted && wb_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01004241#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00004242 && write_info.bw_iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01004243# endif
4244# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00004245 && wfname == fname
Bram Moolenaar13505972019-01-24 15:04:48 +01004246# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247 )
4248 {
4249 if (!forceit)
4250 {
4251 errmsg = (char_u *)_("E213: Cannot convert (add ! to write without conversion)");
4252 goto restore_backup;
4253 }
4254 notconverted = TRUE;
4255 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004256
4257 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004258 * If conversion is taking place, we may first pretend to write and check
4259 * for conversion errors. Then loop again to write for real.
4260 * When not doing conversion this writes for real right away.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004261 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004262 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004263 {
4264 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004265 * There is no need to check conversion when:
4266 * - there is no conversion
4267 * - we make a backup file, that can be restored in case of conversion
4268 * failure.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004269 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004270 if (!converted || dobackup)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004271 checking_conversion = FALSE;
4272
4273 if (checking_conversion)
4274 {
4275 /* Make sure we don't write anything. */
4276 fd = -1;
4277 write_info.bw_fd = fd;
4278 }
4279 else
4280 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004281#ifdef HAVE_FTRUNCATE
4282# define TRUNC_ON_OPEN 0
4283#else
4284# define TRUNC_ON_OPEN O_TRUNC
4285#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004286 /*
4287 * Open the file "wfname" for writing.
4288 * We may try to open the file twice: If we can't write to the file
4289 * and forceit is TRUE we delete the existing file and try to
4290 * create a new one. If this still fails we may have lost the
4291 * original file! (this may happen when the user reached his
4292 * quotum for number of files).
4293 * Appending will fail if the file does not exist and forceit is
4294 * FALSE.
4295 */
4296 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
4297 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004298 : (O_CREAT | TRUNC_ON_OPEN))
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004299 , perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004300 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004301 /*
4302 * A forced write will try to create a new file if the old one
4303 * is still readonly. This may also happen when the directory
4304 * is read-only. In that case the mch_remove() will fail.
4305 */
4306 if (errmsg == NULL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004307 {
4308#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004309 stat_T st;
4310
4311 /* Don't delete the file when it's a hard or symbolic link.
4312 */
4313 if ((!newfile && st_old.st_nlink > 1)
4314 || (mch_lstat((char *)fname, &st) == 0
4315 && (st.st_dev != st_old.st_dev
4316 || st.st_ino != st_old.st_ino)))
4317 errmsg = (char_u *)_("E166: Can't open linked file for writing");
4318 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004319#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004320 {
4321 errmsg = (char_u *)_("E212: Can't open file for writing");
4322 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
4323 && perm >= 0)
4324 {
4325#ifdef UNIX
4326 /* we write to the file, thus it should be marked
4327 writable after all */
4328 if (!(perm & 0200))
4329 made_writable = TRUE;
4330 perm |= 0200;
4331 if (st_old.st_uid != getuid()
4332 || st_old.st_gid != getgid())
4333 perm &= 0777;
4334#endif
4335 if (!append) /* don't remove when appending */
4336 mch_remove(wfname);
4337 continue;
4338 }
4339 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004340 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004341
4342restore_backup:
Bram Moolenaar071d4272004-06-13 20:20:40 +00004343 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004344 stat_T st;
4345
Bram Moolenaar071d4272004-06-13 20:20:40 +00004346 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004347 * If we failed to open the file, we don't need a backup.
4348 * Throw it away. If we moved or removed the original file
4349 * try to put the backup in its place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004350 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004351 if (backup != NULL && wfname == fname)
4352 {
4353 if (backup_copy)
4354 {
4355 /*
4356 * There is a small chance that we removed the
4357 * original, try to move the copy in its place.
4358 * This may not work if the vim_rename() fails.
4359 * In that case we leave the copy around.
4360 */
4361 /* If file does not exist, put the copy in its
4362 * place */
4363 if (mch_stat((char *)fname, &st) < 0)
4364 vim_rename(backup, fname);
4365 /* if original file does exist throw away the copy
4366 */
4367 if (mch_stat((char *)fname, &st) >= 0)
4368 mch_remove(backup);
4369 }
4370 else
4371 {
4372 /* try to put the original file back */
4373 vim_rename(backup, fname);
4374 }
4375 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004376
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004377 /* if original file no longer exists give an extra warning
4378 */
4379 if (!newfile && mch_stat((char *)fname, &st) < 0)
4380 end = 0;
4381 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004382
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004383 if (wfname != fname)
4384 vim_free(wfname);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004385 goto fail;
4386 }
4387 write_info.bw_fd = fd;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004388
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004389#if defined(UNIX)
4390 {
4391 stat_T st;
4392
4393 /* Double check we are writing the intended file before making
4394 * any changes. */
4395 if (overwriting
4396 && (!dobackup || backup_copy)
4397 && fname == wfname
4398 && perm >= 0
4399 && mch_fstat(fd, &st) == 0
4400 && st.st_ino != st_old.st_ino)
4401 {
4402 close(fd);
4403 errmsg = (char_u *)_("E949: File changed while writing");
4404 goto fail;
4405 }
4406 }
4407#endif
4408#ifdef HAVE_FTRUNCATE
4409 if (!append)
Bram Moolenaar42335f52018-09-13 15:33:43 +02004410 vim_ignored = ftruncate(fd, (off_t)0);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004411#endif
4412
Bram Moolenaar4f974752019-02-17 17:44:42 +01004413#if defined(MSWIN)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004414 if (backup != NULL && overwriting && !append)
4415 {
4416 if (backup_copy)
4417 (void)mch_copy_file_attribute(wfname, backup);
4418 else
4419 (void)mch_copy_file_attribute(backup, wfname);
4420 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004421
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004422 if (!overwriting && !append)
4423 {
4424 if (buf->b_ffname != NULL)
4425 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
4426 /* Should copy resource fork */
4427 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004428#endif
4429
Bram Moolenaar071d4272004-06-13 20:20:40 +00004430#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004431 if (*buf->b_p_key != NUL && !filtering)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004432 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004433 char_u *header;
4434 int header_len;
4435
4436 buf->b_cryptstate = crypt_create_for_writing(
4437 crypt_get_method_nr(buf),
4438 buf->b_p_key, &header, &header_len);
4439 if (buf->b_cryptstate == NULL || header == NULL)
4440 end = 0;
4441 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004442 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004443 /* Write magic number, so that Vim knows how this file is
4444 * encrypted when reading it back. */
4445 write_info.bw_buf = header;
4446 write_info.bw_len = header_len;
4447 write_info.bw_flags = FIO_NOCONVERT;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004448 if (buf_write_bytes(&write_info) == FAIL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004449 end = 0;
4450 wb_flags |= FIO_ENCRYPTED;
4451 vim_free(header);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004452 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004453 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004454#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004455 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004456 errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004457
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004458 write_info.bw_buf = buffer;
4459 nchars = 0;
4460
4461 /* use "++bin", "++nobin" or 'binary' */
4462 if (eap != NULL && eap->force_bin != 0)
4463 write_bin = (eap->force_bin == FORCE_BIN);
4464 else
4465 write_bin = buf->b_p_bin;
4466
Bram Moolenaar071d4272004-06-13 20:20:40 +00004467 /*
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004468 * The BOM is written just after the encryption magic number.
4469 * Skip it when appending and the file already existed, the BOM only
4470 * makes sense at the start of the file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004471 */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004472 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004473 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004474 write_info.bw_len = make_bom(buffer, fenc);
4475 if (write_info.bw_len > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004476 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004477 /* don't convert, do encryption */
4478 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
4479 if (buf_write_bytes(&write_info) == FAIL)
4480 end = 0;
4481 else
4482 nchars += write_info.bw_len;
4483 }
4484 }
4485 write_info.bw_start_lnum = start;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004486
4487#ifdef FEAT_PERSISTENT_UNDO
4488 write_undo_file = (buf->b_p_udf
4489 && overwriting
4490 && !append
4491 && !filtering
4492 && reset_changed
4493 && !checking_conversion);
4494 if (write_undo_file)
4495 /* Prepare for computing the hash value of the text. */
4496 sha256_start(&sha_ctx);
4497#endif
4498
4499 write_info.bw_len = bufsize;
4500#ifdef HAS_BW_FLAGS
4501 write_info.bw_flags = wb_flags;
4502#endif
4503 fileformat = get_fileformat_force(buf, eap);
4504 s = buffer;
4505 len = 0;
4506 for (lnum = start; lnum <= end; ++lnum)
4507 {
4508 /*
4509 * The next while loop is done once for each character written.
4510 * Keep it fast!
4511 */
4512 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
4513#ifdef FEAT_PERSISTENT_UNDO
4514 if (write_undo_file)
4515 sha256_update(&sha_ctx, ptr + 1,
4516 (UINT32_T)(STRLEN(ptr + 1) + 1));
4517#endif
4518 while ((c = *++ptr) != NUL)
4519 {
4520 if (c == NL)
4521 *s = NUL; /* replace newlines with NULs */
4522 else if (c == CAR && fileformat == EOL_MAC)
4523 *s = NL; /* Mac: replace CRs with NLs */
4524 else
4525 *s = c;
4526 ++s;
4527 if (++len != bufsize)
4528 continue;
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004529 if (buf_write_bytes(&write_info) == FAIL)
4530 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004531 end = 0; /* write error: break loop */
Bram Moolenaard4755bb2004-09-02 19:12:26 +00004532 break;
4533 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004534 nchars += bufsize;
4535 s = buffer;
4536 len = 0;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004537 write_info.bw_start_lnum = lnum;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004538 }
4539 /* write failed or last line has no EOL: stop here */
4540 if (end == 0
4541 || (lnum == end
4542 && (write_bin || !buf->b_p_fixeol)
4543 && (lnum == buf->b_no_eol_lnum
4544 || (lnum == buf->b_ml.ml_line_count
4545 && !buf->b_p_eol))))
4546 {
4547 ++lnum; /* written the line, count it */
4548 no_eol = TRUE;
4549 break;
4550 }
4551 if (fileformat == EOL_UNIX)
4552 *s++ = NL;
4553 else
4554 {
4555 *s++ = CAR; /* EOL_MAC or EOL_DOS: write CR */
4556 if (fileformat == EOL_DOS) /* write CR-NL */
4557 {
4558 if (++len == bufsize)
4559 {
4560 if (buf_write_bytes(&write_info) == FAIL)
4561 {
4562 end = 0; /* write error: break loop */
4563 break;
4564 }
4565 nchars += bufsize;
4566 s = buffer;
4567 len = 0;
4568 }
4569 *s++ = NL;
4570 }
4571 }
4572 if (++len == bufsize && end)
4573 {
4574 if (buf_write_bytes(&write_info) == FAIL)
4575 {
4576 end = 0; /* write error: break loop */
4577 break;
4578 }
4579 nchars += bufsize;
4580 s = buffer;
4581 len = 0;
4582
4583 ui_breakcheck();
4584 if (got_int)
4585 {
4586 end = 0; /* Interrupted, break loop */
4587 break;
4588 }
4589 }
4590#ifdef VMS
4591 /*
4592 * On VMS there is a problem: newlines get added when writing
4593 * blocks at a time. Fix it by writing a line at a time.
4594 * This is much slower!
4595 * Explanation: VAX/DECC RTL insists that records in some RMS
4596 * structures end with a newline (carriage return) character, and
4597 * if they don't it adds one.
4598 * With other RMS structures it works perfect without this fix.
4599 */
4600 if (buf->b_fab_rfm == FAB$C_VFC
4601 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
4602 {
4603 int b2write;
4604
4605 buf->b_fab_mrs = (buf->b_fab_mrs == 0
4606 ? MIN(4096, bufsize)
4607 : MIN(buf->b_fab_mrs, bufsize));
4608
4609 b2write = len;
4610 while (b2write > 0)
4611 {
4612 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
4613 if (buf_write_bytes(&write_info) == FAIL)
4614 {
4615 end = 0;
4616 break;
4617 }
4618 b2write -= MIN(b2write, buf->b_fab_mrs);
4619 }
4620 write_info.bw_len = bufsize;
4621 nchars += len;
4622 s = buffer;
4623 len = 0;
4624 }
4625#endif
4626 }
4627 if (len > 0 && end > 0)
4628 {
4629 write_info.bw_len = len;
4630 if (buf_write_bytes(&write_info) == FAIL)
4631 end = 0; /* write error */
4632 nchars += len;
4633 }
4634
4635 /* Stop when writing done or an error was encountered. */
4636 if (!checking_conversion || end == 0)
4637 break;
4638
4639 /* If no error happened until now, writing should be ok, so loop to
4640 * really write the buffer. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004641 }
4642
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004643 /* If we started writing, finish writing. Also when an error was
4644 * encountered. */
4645 if (!checking_conversion)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004646 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004647#if defined(UNIX) && defined(HAVE_FSYNC)
4648 /*
4649 * On many journalling file systems there is a bug that causes both the
4650 * original and the backup file to be lost when halting the system
4651 * right after writing the file. That's because only the meta-data is
4652 * journalled. Syncing the file slows down the system, but assures it
4653 * has been written to disk and we don't lose it.
4654 * For a device do try the fsync() but don't complain if it does not
4655 * work (could be a pipe).
4656 * If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
4657 */
Bram Moolenaara7870192019-02-14 12:56:36 +01004658 if (p_fs && vim_fsync(fd) != 0 && !device)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004659 {
Bram Moolenaar7567d0b2017-11-16 23:04:15 +01004660 errmsg = (char_u *)_(e_fsync);
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004661 end = 0;
4662 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004663#endif
4664
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02004665#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004666 /* Probably need to set the security context. */
4667 if (!backup_copy)
4668 mch_copy_sec(backup, wfname);
Bram Moolenaar588ebeb2008-05-07 17:09:24 +00004669#endif
4670
Bram Moolenaara5792f52005-11-23 21:25:05 +00004671#ifdef UNIX
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004672 /* When creating a new file, set its owner/group to that of the
4673 * original file. Get the new device and inode number. */
4674 if (backup != NULL && !backup_copy)
Bram Moolenaara5792f52005-11-23 21:25:05 +00004675 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004676# ifdef HAVE_FCHOWN
4677 stat_T st;
4678
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004679 /* Don't change the owner when it's already OK, some systems remove
4680 * permission or ACL stuff. */
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004681 if (mch_stat((char *)wfname, &st) < 0
4682 || st.st_uid != st_old.st_uid
4683 || st.st_gid != st_old.st_gid)
4684 {
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004685 /* changing owner might not be possible */
Bram Moolenaar42335f52018-09-13 15:33:43 +02004686 vim_ignored = fchown(fd, st_old.st_uid, -1);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004687 /* if changing group fails clear the group permissions */
4688 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
4689 perm &= ~070;
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004690 }
Bram Moolenaara5792f52005-11-23 21:25:05 +00004691# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004692 buf_setino(buf);
4693 }
4694 else if (!buf->b_dev_valid)
4695 /* Set the inode when creating a new file. */
4696 buf_setino(buf);
Bram Moolenaara5792f52005-11-23 21:25:05 +00004697#endif
4698
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004699#ifdef UNIX
4700 if (made_writable)
4701 perm &= ~0200; /* reset 'w' bit for security reasons */
4702#endif
4703#ifdef HAVE_FCHMOD
4704 /* set permission of new file same as old file */
4705 if (perm >= 0)
4706 (void)mch_fsetperm(fd, perm);
4707#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004708 if (close(fd) != 0)
4709 {
4710 errmsg = (char_u *)_("E512: Close failed");
4711 end = 0;
4712 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004713
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004714#ifndef HAVE_FCHMOD
4715 /* set permission of new file same as old file */
4716 if (perm >= 0)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004717 (void)mch_setperm(wfname, perm);
Bram Moolenaarcd142e32017-11-16 17:03:45 +01004718#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004719#ifdef HAVE_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004720 /*
4721 * Probably need to set the ACL before changing the user (can't set the
4722 * ACL on a file the user doesn't own).
4723 * On Solaris, with ZFS and the aclmode property set to "discard" (the
4724 * default), chmod() discards all part of a file's ACL that don't
4725 * represent the mode of the file. It's non-trivial for us to discover
4726 * whether we're in that situation, so we simply always re-set the ACL.
4727 */
Bram Moolenaarda412772016-07-14 20:37:07 +02004728# ifndef HAVE_SOLARIS_ZFS_ACL
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004729 if (!backup_copy)
Bram Moolenaarda412772016-07-14 20:37:07 +02004730# endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004731 mch_set_acl(wfname, acl);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004732#endif
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004733#ifdef FEAT_CRYPT
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004734 if (buf->b_cryptstate != NULL)
4735 {
4736 crypt_free_state(buf->b_cryptstate);
4737 buf->b_cryptstate = NULL;
4738 }
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02004739#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004740
Bram Moolenaar13505972019-01-24 15:04:48 +01004741#if defined(FEAT_EVAL)
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004742 if (wfname != fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004743 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004744 /*
4745 * The file was written to a temp file, now it needs to be
4746 * converted with 'charconvert' to (overwrite) the output file.
4747 */
4748 if (end != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004750 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
4751 fenc, wfname, fname) == FAIL)
4752 {
4753 write_info.bw_conv_error = TRUE;
4754 end = 0;
4755 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004756 }
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004757 mch_remove(wfname);
4758 vim_free(wfname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004759 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760#endif
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004761 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004762
4763 if (end == 0)
4764 {
Bram Moolenaare6bf6552017-06-27 22:11:51 +02004765 /*
4766 * Error encountered.
4767 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768 if (errmsg == NULL)
4769 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004770 if (write_info.bw_conv_error)
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004771 {
4772 if (write_info.bw_conv_error_lnum == 0)
4773 errmsg = (char_u *)_("E513: write error, conversion failed (make 'fenc' empty to override)");
4774 else
4775 {
4776 errmsg_allocated = TRUE;
4777 errmsg = alloc(300);
4778 vim_snprintf((char *)errmsg, 300, _("E513: write error, conversion failed in line %ld (make 'fenc' empty to override)"),
4779 (long)write_info.bw_conv_error_lnum);
4780 }
4781 }
Bram Moolenaar13505972019-01-24 15:04:48 +01004782 else if (got_int)
4783 errmsg = (char_u *)_(e_interr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004784 else
Bram Moolenaar13505972019-01-24 15:04:48 +01004785 errmsg = (char_u *)_("E514: write error (file system full?)");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004786 }
4787
4788 /*
4789 * If we have a backup file, try to put it in place of the new file,
Bram Moolenaare37d50a2008-08-06 17:06:04 +00004790 * because the new file is probably corrupt. This avoids losing the
Bram Moolenaar071d4272004-06-13 20:20:40 +00004791 * original file when trying to make a backup when writing the file a
4792 * second time.
4793 * When "backup_copy" is set we need to copy the backup over the new
4794 * file. Otherwise rename the backup file.
4795 * If this is OK, don't give the extra warning message.
4796 */
4797 if (backup != NULL)
4798 {
4799 if (backup_copy)
4800 {
4801 /* This may take a while, if we were interrupted let the user
4802 * know we got the message. */
4803 if (got_int)
4804 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01004805 msg(_(e_interr));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004806 out_flush();
4807 }
4808 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
4809 {
4810 if ((write_info.bw_fd = mch_open((char *)fname,
Bram Moolenaar9be038d2005-03-08 22:34:32 +00004811 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
4812 perm & 0777)) >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813 {
4814 /* copy the file. */
4815 write_info.bw_buf = smallbuf;
4816#ifdef HAS_BW_FLAGS
4817 write_info.bw_flags = FIO_NOCONVERT;
4818#endif
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01004819 while ((write_info.bw_len = read_eintr(fd, smallbuf,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004820 SMBUFSIZE)) > 0)
4821 if (buf_write_bytes(&write_info) == FAIL)
4822 break;
4823
4824 if (close(write_info.bw_fd) >= 0
4825 && write_info.bw_len == 0)
4826 end = 1; /* success */
4827 }
4828 close(fd); /* ignore errors for closing read file */
4829 }
4830 }
4831 else
4832 {
4833 if (vim_rename(backup, fname) == 0)
4834 end = 1;
4835 }
4836 }
4837 goto fail;
4838 }
4839
4840 lnum -= start; /* compute number of written lines */
4841 --no_wait_return; /* may wait for return now */
4842
4843#if !(defined(UNIX) || defined(VMS))
4844 fname = sfname; /* use shortname now, for the messages */
4845#endif
4846 if (!filtering)
4847 {
4848 msg_add_fname(buf, fname); /* put fname in IObuff with quotes */
4849 c = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004850 if (write_info.bw_conv_error)
4851 {
4852 STRCAT(IObuff, _(" CONVERSION ERROR"));
4853 c = TRUE;
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004854 if (write_info.bw_conv_error_lnum != 0)
Bram Moolenaara800b422010-06-27 01:15:55 +02004855 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
Bram Moolenaar32b485f2009-07-29 16:06:27 +00004856 (long)write_info.bw_conv_error_lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004857 }
4858 else if (notconverted)
4859 {
4860 STRCAT(IObuff, _("[NOT converted]"));
4861 c = TRUE;
4862 }
4863 else if (converted)
4864 {
4865 STRCAT(IObuff, _("[converted]"));
4866 c = TRUE;
4867 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868 if (device)
4869 {
4870 STRCAT(IObuff, _("[Device]"));
4871 c = TRUE;
4872 }
4873 else if (newfile)
4874 {
4875 STRCAT(IObuff, shortmess(SHM_NEW) ? _("[New]") : _("[New File]"));
4876 c = TRUE;
4877 }
4878 if (no_eol)
4879 {
4880 msg_add_eol();
4881 c = TRUE;
4882 }
4883 /* may add [unix/dos/mac] */
4884 if (msg_add_fileformat(fileformat))
4885 c = TRUE;
4886#ifdef FEAT_CRYPT
4887 if (wb_flags & FIO_ENCRYPTED)
4888 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02004889 crypt_append_msg(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004890 c = TRUE;
4891 }
4892#endif
4893 msg_add_lines(c, (long)lnum, nchars); /* add line/char count */
4894 if (!shortmess(SHM_WRITE))
4895 {
4896 if (append)
4897 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
4898 else
4899 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
4900 }
4901
Bram Moolenaar32526b32019-01-19 17:43:09 +01004902 set_keep_msg((char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004903 }
4904
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00004905 /* When written everything correctly: reset 'modified'. Unless not
4906 * writing to the original file and '+' is not in 'cpoptions'. */
Bram Moolenaar292ad192005-12-11 21:29:51 +00004907 if (reset_changed && whole && !append
Bram Moolenaar071d4272004-06-13 20:20:40 +00004908 && !write_info.bw_conv_error
Bram Moolenaar13505972019-01-24 15:04:48 +01004909 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004910 {
4911 unchanged(buf, TRUE);
Bram Moolenaar95c526e2017-02-25 14:59:34 +01004912 /* b:changedtick is always incremented in unchanged() but that
Bram Moolenaar086329d2014-10-31 19:51:36 +01004913 * should not trigger a TextChanged event. */
Bram Moolenaar5a093432018-02-10 18:15:19 +01004914 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
4915 buf->b_last_changedtick = CHANGEDTICK(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004916 u_unchanged(buf);
Bram Moolenaar730cde92010-06-27 05:18:54 +02004917 u_update_save_nr(buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004918 }
4919
4920 /*
4921 * If written to the current file, update the timestamp of the swap file
4922 * and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
4923 */
4924 if (overwriting)
4925 {
4926 ml_timestamp(buf);
Bram Moolenaar292ad192005-12-11 21:29:51 +00004927 if (append)
4928 buf->b_flags &= ~BF_NEW;
4929 else
4930 buf->b_flags &= ~BF_WRITE_MASK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004931 }
4932
4933 /*
4934 * If we kept a backup until now, and we are in patch mode, then we make
4935 * the backup file our 'original' file.
4936 */
4937 if (*p_pm && dobackup)
4938 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +01004939 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00004940 fname, p_pm, FALSE);
4941
4942 if (backup != NULL)
4943 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02004944 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004945
4946 /*
4947 * If the original file does not exist yet
4948 * the current backup file becomes the original file
4949 */
4950 if (org == NULL)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004951 emsg(_("E205: Patchmode: can't save original file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004952 else if (mch_stat(org, &st) < 0)
4953 {
4954 vim_rename(backup, (char_u *)org);
Bram Moolenaard23a8232018-02-10 18:45:26 +01004955 VIM_CLEAR(backup); /* don't delete the file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004956#ifdef UNIX
4957 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
4958#endif
4959 }
4960 }
4961 /*
4962 * If there is no backup file, remember that a (new) file was
4963 * created.
4964 */
4965 else
4966 {
4967 int empty_fd;
4968
4969 if (org == NULL
Bram Moolenaara5792f52005-11-23 21:25:05 +00004970 || (empty_fd = mch_open(org,
4971 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
Bram Moolenaar4317d9b2005-03-18 20:25:31 +00004972 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004973 emsg(_("E206: patchmode: can't touch empty original file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004974 else
4975 close(empty_fd);
4976 }
4977 if (org != NULL)
4978 {
4979 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
4980 vim_free(org);
4981 }
4982 }
4983
Bram Moolenaarcf0bfd92019-05-18 18:52:04 +02004984 // Remove the backup unless 'backup' option is set or there was a
4985 // conversion error.
4986 if (!p_bk && backup != NULL && !write_info.bw_conv_error
4987 && mch_remove(backup) != 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004988 emsg(_("E207: Can't delete backup file"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989
Bram Moolenaar071d4272004-06-13 20:20:40 +00004990 goto nofail;
4991
4992 /*
4993 * Finish up. We get here either after failure or success.
4994 */
4995fail:
4996 --no_wait_return; /* may wait for return now */
4997nofail:
4998
4999 /* Done saving, we accept changed buffer warnings again */
5000 buf->b_saving = FALSE;
5001
5002 vim_free(backup);
5003 if (buffer != smallbuf)
5004 vim_free(buffer);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005005 vim_free(fenc_tofree);
5006 vim_free(write_info.bw_conv_buf);
Bram Moolenaar13505972019-01-24 15:04:48 +01005007#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00005008 if (write_info.bw_iconv_fd != (iconv_t)-1)
5009 {
5010 iconv_close(write_info.bw_iconv_fd);
5011 write_info.bw_iconv_fd = (iconv_t)-1;
5012 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005013#endif
5014#ifdef HAVE_ACL
5015 mch_free_acl(acl);
5016#endif
5017
5018 if (errmsg != NULL)
5019 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005020 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005021
Bram Moolenaar8820b482017-03-16 17:23:31 +01005022 attr = HL_ATTR(HLF_E); /* set highlight for error messages */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005023 msg_add_fname(buf,
5024#ifndef UNIX
5025 sfname
5026#else
5027 fname
5028#endif
5029 ); /* put file name in IObuff with quotes */
5030 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
5031 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
5032 /* If the error message has the form "is ...", put the error number in
5033 * front of the file name. */
5034 if (errnum != NULL)
5035 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00005036 STRMOVE(IObuff + numlen, IObuff);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005037 mch_memmove(IObuff, errnum, (size_t)numlen);
5038 }
5039 STRCAT(IObuff, errmsg);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005040 emsg((char *)IObuff);
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005041 if (errmsg_allocated)
5042 vim_free(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043
5044 retval = FAIL;
5045 if (end == 0)
5046 {
Bram Moolenaar32526b32019-01-19 17:43:09 +01005047 msg_puts_attr(_("\nWARNING: Original file may be lost or damaged\n"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005048 attr | MSG_HIST);
Bram Moolenaar32526b32019-01-19 17:43:09 +01005049 msg_puts_attr(_("don't quit the editor until the file is successfully written!"),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 attr | MSG_HIST);
5051
5052 /* Update the timestamp to avoid an "overwrite changed file"
5053 * prompt when writing again. */
5054 if (mch_stat((char *)fname, &st_old) >= 0)
5055 {
5056 buf_store_time(buf, &st_old, fname);
5057 buf->b_mtime_read = buf->b_mtime;
5058 }
5059 }
5060 }
5061 msg_scroll = msg_save;
5062
Bram Moolenaar55debbe2010-05-23 23:34:36 +02005063#ifdef FEAT_PERSISTENT_UNDO
5064 /*
5065 * When writing the whole file and 'undofile' is set, also write the undo
5066 * file.
5067 */
5068 if (retval == OK && write_undo_file)
5069 {
5070 char_u hash[UNDO_HASH_SIZE];
5071
5072 sha256_finish(&sha_ctx, hash);
5073 u_write_undo(NULL, FALSE, buf, hash);
5074 }
5075#endif
5076
Bram Moolenaar071d4272004-06-13 20:20:40 +00005077#ifdef FEAT_EVAL
5078 if (!should_abort(retval))
5079#else
5080 if (!got_int)
5081#endif
5082 {
5083 aco_save_T aco;
5084
Bram Moolenaar68a33fc2012-04-25 16:50:48 +02005085 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
5086
Bram Moolenaar071d4272004-06-13 20:20:40 +00005087 /*
5088 * Apply POST autocommands.
5089 * Careful: The autocommands may call buf_write() recursively!
5090 */
5091 aucmd_prepbuf(&aco, buf);
5092
5093 if (append)
5094 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
5095 FALSE, curbuf, eap);
5096 else if (filtering)
5097 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
5098 FALSE, curbuf, eap);
5099 else if (reset_changed && whole)
5100 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
5101 FALSE, curbuf, eap);
5102 else
5103 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
5104 FALSE, curbuf, eap);
5105
5106 /* restore curwin/curbuf and a few other things */
5107 aucmd_restbuf(&aco);
5108
5109#ifdef FEAT_EVAL
5110 if (aborting()) /* autocmds may abort script processing */
5111 retval = FALSE;
5112#endif
5113 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005114
5115 got_int |= prev_got_int;
5116
Bram Moolenaar071d4272004-06-13 20:20:40 +00005117 return retval;
5118}
5119
Bram Moolenaara7870192019-02-14 12:56:36 +01005120#if defined(HAVE_FSYNC) || defined(PROTO)
5121/*
5122 * Call fsync() with Mac-specific exception.
5123 * Return fsync() result: zero for success.
5124 */
5125 int
5126vim_fsync(int fd)
5127{
5128 int r;
5129
5130# ifdef MACOS_X
5131 r = fcntl(fd, F_FULLFSYNC);
Bram Moolenaar91668382019-02-21 12:16:12 +01005132 if (r != 0) // F_FULLFSYNC not working or not supported
Bram Moolenaara7870192019-02-14 12:56:36 +01005133# endif
5134 r = fsync(fd);
5135 return r;
5136}
5137#endif
5138
Bram Moolenaar071d4272004-06-13 20:20:40 +00005139/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005140 * Set the name of the current buffer. Use when the buffer doesn't have a
5141 * name and a ":r" or ":w" command with a file name is used.
5142 */
5143 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005144set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005145{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005146 buf_T *buf = curbuf;
5147
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005148 /* It's like the unnamed buffer is deleted.... */
5149 if (curbuf->b_p_bl)
5150 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5151 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005152#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005153 if (aborting()) /* autocmds may abort script processing */
5154 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005155#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005156 if (curbuf != buf)
5157 {
5158 /* We are in another buffer now, don't do the renaming. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005159 emsg(_(e_auchangedbuf));
Bram Moolenaar8b38e242009-06-16 13:35:20 +00005160 return FAIL;
5161 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005162
5163 if (setfname(curbuf, fname, sfname, FALSE) == OK)
5164 curbuf->b_flags |= BF_NOTEDITED;
5165
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005166 /* ....and a new named one is created */
5167 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
5168 if (curbuf->b_p_bl)
5169 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005170#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005171 if (aborting()) /* autocmds may abort script processing */
5172 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01005173#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005174
5175 /* Do filetype detection now if 'filetype' is empty. */
5176 if (*curbuf->b_p_ft == NUL)
5177 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00005178 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02005179 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00005180 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005181 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00005182
5183 return OK;
5184}
5185
5186/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005187 * Put file name into IObuff with quotes.
5188 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005189 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005190msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191{
5192 if (fname == NULL)
5193 fname = (char_u *)"-stdin-";
5194 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
5195 IObuff[0] = '"';
5196 STRCAT(IObuff, "\" ");
5197}
5198
5199/*
5200 * Append message for text mode to IObuff.
5201 * Return TRUE if something appended.
5202 */
5203 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005204msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005205{
5206#ifndef USE_CRNL
5207 if (eol_type == EOL_DOS)
5208 {
5209 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
5210 return TRUE;
5211 }
5212#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213 if (eol_type == EOL_MAC)
5214 {
5215 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
5216 return TRUE;
5217 }
Bram Moolenaar00590742019-02-15 21:06:09 +01005218#ifdef USE_CRNL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005219 if (eol_type == EOL_UNIX)
5220 {
5221 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
5222 return TRUE;
5223 }
5224#endif
5225 return FALSE;
5226}
5227
5228/*
5229 * Append line and character count to IObuff.
5230 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00005231 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005232msg_add_lines(
5233 int insert_space,
5234 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02005235 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005236{
5237 char_u *p;
5238
5239 p = IObuff + STRLEN(IObuff);
5240
5241 if (insert_space)
5242 *p++ = ' ';
5243 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02005244 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaar88c86eb2019-01-17 17:13:30 +01005245 "%ldL, %lldC", lnum, (long_long_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005246 else
5247 {
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005248 sprintf((char *)p, NGETTEXT("%ld line, ", "%ld lines, ", lnum), lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005249 p += STRLEN(p);
Bram Moolenaarda6e8912018-08-21 15:12:14 +02005250 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
5251 NGETTEXT("%lld character", "%lld characters", nchars),
Bram Moolenaar88c86eb2019-01-17 17:13:30 +01005252 (long_long_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005253 }
5254}
5255
5256/*
5257 * Append message for missing line separator to IObuff.
5258 */
5259 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005260msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261{
5262 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
5263}
5264
5265/*
5266 * Check modification time of file, before writing to it.
5267 * The size isn't checked, because using a tool like "gzip" takes care of
5268 * using the same timestamp but can't set the size.
5269 */
5270 static int
Bram Moolenaar8767f522016-07-01 17:17:39 +02005271check_mtime(buf_T *buf, stat_T *st)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005272{
5273 if (buf->b_mtime_read != 0
5274 && time_differs((long)st->st_mtime, buf->b_mtime_read))
5275 {
5276 msg_scroll = TRUE; /* don't overwrite messages here */
5277 msg_silent = 0; /* must give this prompt */
5278 /* don't use emsg() here, don't want to flush the buffers */
Bram Moolenaar32526b32019-01-19 17:43:09 +01005279 msg_attr(_("WARNING: The file has been changed since reading it!!!"),
Bram Moolenaar8820b482017-03-16 17:23:31 +01005280 HL_ATTR(HLF_E));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005281 if (ask_yesno((char_u *)_("Do you really want to write to it"),
5282 TRUE) == 'n')
5283 return FAIL;
5284 msg_scroll = FALSE; /* always overwrite the file message now */
5285 }
5286 return OK;
5287}
5288
5289 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005290time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01005292#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005293 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
5294 * the seconds. Since the roundoff is done when flushing the inode, the
5295 * time may change unexpectedly by one second!!! */
5296 return (t1 - t2 > 1 || t2 - t1 > 1);
5297#else
5298 return (t1 != t2);
5299#endif
5300}
5301
5302/*
5303 * Call write() to write a number of bytes to the file.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005304 * Handles encryption and 'encoding' conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005305 *
5306 * Return FAIL for failure, OK otherwise.
5307 */
5308 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005309buf_write_bytes(struct bw_info *ip)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005310{
5311 int wlen;
5312 char_u *buf = ip->bw_buf; /* data to write */
5313 int len = ip->bw_len; /* length of data */
5314#ifdef HAS_BW_FLAGS
5315 int flags = ip->bw_flags; /* extra flags */
5316#endif
5317
Bram Moolenaar071d4272004-06-13 20:20:40 +00005318 /*
5319 * Skip conversion when writing the crypt magic number or the BOM.
5320 */
5321 if (!(flags & FIO_NOCONVERT))
5322 {
5323 char_u *p;
5324 unsigned c;
5325 int n;
5326
5327 if (flags & FIO_UTF8)
5328 {
5329 /*
5330 * Convert latin1 in the buffer to UTF-8 in the file.
5331 */
5332 p = ip->bw_conv_buf; /* translate to buffer */
5333 for (wlen = 0; wlen < len; ++wlen)
5334 p += utf_char2bytes(buf[wlen], p);
5335 buf = ip->bw_conv_buf;
5336 len = (int)(p - ip->bw_conv_buf);
5337 }
5338 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
5339 {
5340 /*
5341 * Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
5342 * Latin1 chars in the file.
5343 */
5344 if (flags & FIO_LATIN1)
5345 p = buf; /* translate in-place (can only get shorter) */
5346 else
5347 p = ip->bw_conv_buf; /* translate to buffer */
5348 for (wlen = 0; wlen < len; wlen += n)
5349 {
5350 if (wlen == 0 && ip->bw_restlen != 0)
5351 {
5352 int l;
5353
5354 /* Use remainder of previous call. Append the start of
5355 * buf[] to get a full sequence. Might still be too
5356 * short! */
5357 l = CONV_RESTLEN - ip->bw_restlen;
5358 if (l > len)
5359 l = len;
5360 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005361 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005362 if (n > ip->bw_restlen + len)
5363 {
5364 /* We have an incomplete byte sequence at the end to
5365 * be written. We can't convert it without the
5366 * remaining bytes. Keep them for the next call. */
5367 if (ip->bw_restlen + len > CONV_RESTLEN)
5368 return FAIL;
5369 ip->bw_restlen += len;
5370 break;
5371 }
5372 if (n > 1)
5373 c = utf_ptr2char(ip->bw_rest);
5374 else
5375 c = ip->bw_rest[0];
5376 if (n >= ip->bw_restlen)
5377 {
5378 n -= ip->bw_restlen;
5379 ip->bw_restlen = 0;
5380 }
5381 else
5382 {
5383 ip->bw_restlen -= n;
5384 mch_memmove(ip->bw_rest, ip->bw_rest + n,
5385 (size_t)ip->bw_restlen);
5386 n = 0;
5387 }
5388 }
5389 else
5390 {
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005391 n = utf_ptr2len_len(buf + wlen, len - wlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005392 if (n > len - wlen)
5393 {
5394 /* We have an incomplete byte sequence at the end to
5395 * be written. We can't convert it without the
5396 * remaining bytes. Keep them for the next call. */
5397 if (len - wlen > CONV_RESTLEN)
5398 return FAIL;
5399 ip->bw_restlen = len - wlen;
5400 mch_memmove(ip->bw_rest, buf + wlen,
5401 (size_t)ip->bw_restlen);
5402 break;
5403 }
5404 if (n > 1)
5405 c = utf_ptr2char(buf + wlen);
5406 else
5407 c = buf[wlen];
5408 }
5409
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005410 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
5411 {
5412 ip->bw_conv_error = TRUE;
5413 ip->bw_conv_error_lnum = ip->bw_start_lnum;
5414 }
5415 if (c == NL)
5416 ++ip->bw_start_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005417 }
5418 if (flags & FIO_LATIN1)
5419 len = (int)(p - buf);
5420 else
5421 {
5422 buf = ip->bw_conv_buf;
5423 len = (int)(p - ip->bw_conv_buf);
5424 }
5425 }
5426
Bram Moolenaar4f974752019-02-17 17:44:42 +01005427#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005428 else if (flags & FIO_CODEPAGE)
5429 {
5430 /*
5431 * Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
5432 * codepage.
5433 */
5434 char_u *from;
5435 size_t fromlen;
5436 char_u *to;
5437 int u8c;
5438 BOOL bad = FALSE;
5439 int needed;
5440
5441 if (ip->bw_restlen > 0)
5442 {
5443 /* Need to concatenate the remainder of the previous call and
5444 * the bytes of the current call. Use the end of the
5445 * conversion buffer for this. */
5446 fromlen = len + ip->bw_restlen;
5447 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5448 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5449 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5450 }
5451 else
5452 {
5453 from = buf;
5454 fromlen = len;
5455 }
5456
5457 to = ip->bw_conv_buf;
5458 if (enc_utf8)
5459 {
5460 /* Convert from UTF-8 to UCS-2, to the start of the buffer.
5461 * The buffer has been allocated to be big enough. */
5462 while (fromlen > 0)
5463 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005464 n = (int)utf_ptr2len_len(from, (int)fromlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005465 if (n > (int)fromlen) /* incomplete byte sequence */
5466 break;
5467 u8c = utf_ptr2char(from);
5468 *to++ = (u8c & 0xff);
5469 *to++ = (u8c >> 8);
5470 fromlen -= n;
5471 from += n;
5472 }
5473
5474 /* Copy remainder to ip->bw_rest[] to be used for the next
5475 * call. */
5476 if (fromlen > CONV_RESTLEN)
5477 {
5478 /* weird overlong sequence */
5479 ip->bw_conv_error = TRUE;
5480 return FAIL;
5481 }
5482 mch_memmove(ip->bw_rest, from, fromlen);
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005483 ip->bw_restlen = (int)fromlen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005484 }
5485 else
5486 {
5487 /* Convert from enc_codepage to UCS-2, to the start of the
5488 * buffer. The buffer has been allocated to be big enough. */
5489 ip->bw_restlen = 0;
5490 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005491 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005492 NULL, 0);
5493 if (needed == 0)
5494 {
5495 /* When conversion fails there may be a trailing byte. */
5496 needed = MultiByteToWideChar(enc_codepage,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005497 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00005498 NULL, 0);
5499 if (needed == 0)
5500 {
5501 /* Conversion doesn't work. */
5502 ip->bw_conv_error = TRUE;
5503 return FAIL;
5504 }
5505 /* Save the trailing byte for the next call. */
5506 ip->bw_rest[0] = from[fromlen - 1];
5507 ip->bw_restlen = 1;
5508 }
5509 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005510 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
Bram Moolenaar071d4272004-06-13 20:20:40 +00005511 (LPWSTR)to, needed);
5512 if (needed == 0)
5513 {
5514 /* Safety check: Conversion doesn't work. */
5515 ip->bw_conv_error = TRUE;
5516 return FAIL;
5517 }
5518 to += needed * 2;
5519 }
5520
5521 fromlen = to - ip->bw_conv_buf;
5522 buf = to;
Bram Moolenaar13505972019-01-24 15:04:48 +01005523# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005524 if (FIO_GET_CP(flags) == CP_UTF8)
5525 {
5526 /* Convert from UCS-2 to UTF-8, using the remainder of the
5527 * conversion buffer. Fails when out of space. */
5528 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
5529 {
5530 u8c = *from++;
5531 u8c += (*from++ << 8);
5532 to += utf_char2bytes(u8c, to);
5533 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
5534 {
5535 ip->bw_conv_error = TRUE;
5536 return FAIL;
5537 }
5538 }
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00005539 len = (int)(to - buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005540 }
5541 else
Bram Moolenaar13505972019-01-24 15:04:48 +01005542# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005543 {
5544 /* Convert from UCS-2 to the codepage, using the remainder of
5545 * the conversion buffer. If the conversion uses the default
5546 * character "0", the data doesn't fit in this encoding, so
5547 * fail. */
5548 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
5549 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
Bram Moolenaar36f5ac02007-05-06 12:40:34 +00005550 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
5551 &bad);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005552 if (bad)
5553 {
5554 ip->bw_conv_error = TRUE;
5555 return FAIL;
5556 }
5557 }
5558 }
Bram Moolenaar13505972019-01-24 15:04:48 +01005559#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005560
Bram Moolenaar13505972019-01-24 15:04:48 +01005561#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005562 else if (flags & FIO_MACROMAN)
5563 {
5564 /*
5565 * Convert UTF-8 or latin1 to Apple MacRoman.
5566 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005567 char_u *from;
5568 size_t fromlen;
5569
5570 if (ip->bw_restlen > 0)
5571 {
5572 /* Need to concatenate the remainder of the previous call and
5573 * the bytes of the current call. Use the end of the
5574 * conversion buffer for this. */
5575 fromlen = len + ip->bw_restlen;
5576 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5577 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
5578 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
5579 }
5580 else
5581 {
5582 from = buf;
5583 fromlen = len;
5584 }
5585
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00005586 if (enc2macroman(from, fromlen,
5587 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
5588 ip->bw_rest, &ip->bw_restlen) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 {
5590 ip->bw_conv_error = TRUE;
5591 return FAIL;
5592 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005593 buf = ip->bw_conv_buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005594 }
Bram Moolenaar13505972019-01-24 15:04:48 +01005595#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005596
Bram Moolenaar13505972019-01-24 15:04:48 +01005597#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00005598 if (ip->bw_iconv_fd != (iconv_t)-1)
5599 {
5600 const char *from;
5601 size_t fromlen;
5602 char *to;
5603 size_t tolen;
5604
5605 /* Convert with iconv(). */
5606 if (ip->bw_restlen > 0)
5607 {
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005608 char *fp;
5609
Bram Moolenaar071d4272004-06-13 20:20:40 +00005610 /* Need to concatenate the remainder of the previous call and
5611 * the bytes of the current call. Use the end of the
5612 * conversion buffer for this. */
5613 fromlen = len + ip->bw_restlen;
Bram Moolenaar5d294d12009-03-11 12:11:02 +00005614 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
5615 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
5616 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
5617 from = fp;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005618 tolen = ip->bw_conv_buflen - fromlen;
5619 }
5620 else
5621 {
5622 from = (const char *)buf;
5623 fromlen = len;
5624 tolen = ip->bw_conv_buflen;
5625 }
5626 to = (char *)ip->bw_conv_buf;
5627
5628 if (ip->bw_first)
5629 {
5630 size_t save_len = tolen;
5631
5632 /* output the initial shift state sequence */
5633 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
5634
5635 /* There is a bug in iconv() on Linux (which appears to be
5636 * wide-spread) which sets "to" to NULL and messes up "tolen".
5637 */
5638 if (to == NULL)
5639 {
5640 to = (char *)ip->bw_conv_buf;
5641 tolen = save_len;
5642 }
5643 ip->bw_first = FALSE;
5644 }
5645
5646 /*
5647 * If iconv() has an error or there is not enough room, fail.
5648 */
5649 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
5650 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
5651 || fromlen > CONV_RESTLEN)
5652 {
5653 ip->bw_conv_error = TRUE;
5654 return FAIL;
5655 }
5656
5657 /* copy remainder to ip->bw_rest[] to be used for the next call. */
5658 if (fromlen > 0)
5659 mch_memmove(ip->bw_rest, (void *)from, fromlen);
5660 ip->bw_restlen = (int)fromlen;
5661
5662 buf = ip->bw_conv_buf;
5663 len = (int)((char_u *)to - ip->bw_conv_buf);
5664 }
Bram Moolenaar13505972019-01-24 15:04:48 +01005665#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005666 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005667
Bram Moolenaare6bf6552017-06-27 22:11:51 +02005668 if (ip->bw_fd < 0)
5669 /* Only checking conversion, which is OK if we get here. */
5670 return OK;
5671
Bram Moolenaar071d4272004-06-13 20:20:40 +00005672#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005673 if (flags & FIO_ENCRYPTED)
5674 {
5675 /* Encrypt the data. Do it in-place if possible, otherwise use an
5676 * allocated buffer. */
Bram Moolenaar987411d2019-01-18 22:48:34 +01005677# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005678 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
5679 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01005680# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005681 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len);
Bram Moolenaar987411d2019-01-18 22:48:34 +01005682# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005683 }
5684 else
5685 {
5686 char_u *outbuf;
5687
5688 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf);
5689 if (len == 0)
5690 return OK; /* Crypt layer is buffering, will flush later. */
5691 wlen = write_eintr(ip->bw_fd, outbuf, len);
5692 vim_free(outbuf);
5693 return (wlen < len) ? FAIL : OK;
5694 }
Bram Moolenaar987411d2019-01-18 22:48:34 +01005695# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02005696 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005697#endif
5698
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005699 wlen = write_eintr(ip->bw_fd, buf, len);
5700 return (wlen < len) ? FAIL : OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005701}
5702
Bram Moolenaar071d4272004-06-13 20:20:40 +00005703/*
5704 * Convert a Unicode character to bytes.
Bram Moolenaar32b485f2009-07-29 16:06:27 +00005705 * Return TRUE for an error, FALSE when it's OK.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005706 */
5707 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005708ucs2bytes(
5709 unsigned c, /* in: character */
5710 char_u **pp, /* in/out: pointer to result */
5711 int flags) /* FIO_ flags */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005712{
5713 char_u *p = *pp;
5714 int error = FALSE;
5715 int cc;
5716
5717
5718 if (flags & FIO_UCS4)
5719 {
5720 if (flags & FIO_ENDIAN_L)
5721 {
5722 *p++ = c;
5723 *p++ = (c >> 8);
5724 *p++ = (c >> 16);
5725 *p++ = (c >> 24);
5726 }
5727 else
5728 {
5729 *p++ = (c >> 24);
5730 *p++ = (c >> 16);
5731 *p++ = (c >> 8);
5732 *p++ = c;
5733 }
5734 }
5735 else if (flags & (FIO_UCS2 | FIO_UTF16))
5736 {
5737 if (c >= 0x10000)
5738 {
5739 if (flags & FIO_UTF16)
5740 {
5741 /* Make two words, ten bits of the character in each. First
5742 * word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff */
5743 c -= 0x10000;
5744 if (c >= 0x100000)
5745 error = TRUE;
5746 cc = ((c >> 10) & 0x3ff) + 0xd800;
5747 if (flags & FIO_ENDIAN_L)
5748 {
5749 *p++ = cc;
5750 *p++ = ((unsigned)cc >> 8);
5751 }
5752 else
5753 {
5754 *p++ = ((unsigned)cc >> 8);
5755 *p++ = cc;
5756 }
5757 c = (c & 0x3ff) + 0xdc00;
5758 }
5759 else
5760 error = TRUE;
5761 }
5762 if (flags & FIO_ENDIAN_L)
5763 {
5764 *p++ = c;
5765 *p++ = (c >> 8);
5766 }
5767 else
5768 {
5769 *p++ = (c >> 8);
5770 *p++ = c;
5771 }
5772 }
5773 else /* Latin1 */
5774 {
5775 if (c >= 0x100)
5776 {
5777 error = TRUE;
5778 *p++ = 0xBF;
5779 }
5780 else
5781 *p++ = c;
5782 }
5783
5784 *pp = p;
5785 return error;
5786}
5787
5788/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005789 * Return TRUE if file encoding "fenc" requires conversion from or to
5790 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005791 */
5792 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005793need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005794{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005795 int same_encoding;
5796 int enc_flags;
5797 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005798
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005799 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02005800 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005801 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02005802 fenc_flags = 0;
5803 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00005804 else
5805 {
5806 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
5807 * "ucs-4be", etc. */
5808 enc_flags = get_fio_flags(p_enc);
5809 fenc_flags = get_fio_flags(fenc);
5810 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
5811 }
5812 if (same_encoding)
5813 {
5814 /* Specified encoding matches with 'encoding'. This requires
5815 * conversion when 'encoding' is Unicode but not UTF-8. */
5816 return enc_unicode != 0;
5817 }
5818
5819 /* Encodings differ. However, conversion is not needed when 'enc' is any
5820 * Unicode encoding and the file is UTF-8. */
5821 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005822}
5823
5824/*
5825 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
5826 * internal conversion.
5827 * if "ptr" is an empty string, use 'encoding'.
5828 */
5829 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005830get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005831{
5832 int prop;
5833
5834 if (*ptr == NUL)
5835 ptr = p_enc;
5836
5837 prop = enc_canon_props(ptr);
5838 if (prop & ENC_UNICODE)
5839 {
5840 if (prop & ENC_2BYTE)
5841 {
5842 if (prop & ENC_ENDIAN_L)
5843 return FIO_UCS2 | FIO_ENDIAN_L;
5844 return FIO_UCS2;
5845 }
5846 if (prop & ENC_4BYTE)
5847 {
5848 if (prop & ENC_ENDIAN_L)
5849 return FIO_UCS4 | FIO_ENDIAN_L;
5850 return FIO_UCS4;
5851 }
5852 if (prop & ENC_2WORD)
5853 {
5854 if (prop & ENC_ENDIAN_L)
5855 return FIO_UTF16 | FIO_ENDIAN_L;
5856 return FIO_UTF16;
5857 }
5858 return FIO_UTF8;
5859 }
5860 if (prop & ENC_LATIN1)
5861 return FIO_LATIN1;
5862 /* must be ENC_DBCS, requires iconv() */
5863 return 0;
5864}
5865
Bram Moolenaar4f974752019-02-17 17:44:42 +01005866#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005867/*
5868 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
5869 * for the conversion MS-Windows can do for us. Also accept "utf-8".
5870 * Used for conversion between 'encoding' and 'fileencoding'.
5871 */
5872 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005873get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005874{
5875 int cp;
5876
5877 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
5878 if (!enc_utf8 && enc_codepage <= 0)
5879 return 0;
5880
5881 cp = encname2codepage(ptr);
5882 if (cp == 0)
5883 {
5884# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
5885 if (STRCMP(ptr, "utf-8") == 0)
5886 cp = CP_UTF8;
5887 else
5888# endif
5889 return 0;
5890 }
5891 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
5892}
5893#endif
5894
Bram Moolenaard0573012017-10-28 21:11:06 +02005895#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00005896/*
5897 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
5898 * needed for the internal conversion to/from utf-8 or latin1.
5899 */
5900 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005901get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005902{
5903 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
5904 && (enc_canon_props(ptr) & ENC_MACROMAN))
5905 return FIO_MACROMAN;
5906 return 0;
5907}
5908#endif
5909
5910/*
5911 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
5912 * "size" must be at least 2.
5913 * Return the name of the encoding and set "*lenp" to the length.
5914 * Returns NULL when no BOM found.
5915 */
5916 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005917check_for_bom(
5918 char_u *p,
5919 long size,
5920 int *lenp,
5921 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005922{
5923 char *name = NULL;
5924 int len = 2;
5925
5926 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00005927 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005928 {
5929 name = "utf-8"; /* EF BB BF */
5930 len = 3;
5931 }
5932 else if (p[0] == 0xff && p[1] == 0xfe)
5933 {
5934 if (size >= 4 && p[2] == 0 && p[3] == 0
5935 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
5936 {
5937 name = "ucs-4le"; /* FF FE 00 00 */
5938 len = 4;
5939 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00005940 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005941 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00005942 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
5943 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005944 name = "utf-16le"; /* FF FE */
5945 }
5946 else if (p[0] == 0xfe && p[1] == 0xff
5947 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
5948 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005949 /* Default to utf-16, it works also for ucs-2 text. */
5950 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005951 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00005952 else
5953 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005954 }
5955 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
5956 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
5957 {
5958 name = "ucs-4"; /* 00 00 FE FF */
5959 len = 4;
5960 }
5961
5962 *lenp = len;
5963 return (char_u *)name;
5964}
5965
5966/*
5967 * Generate a BOM in "buf[4]" for encoding "name".
5968 * Return the length of the BOM (zero when no BOM).
5969 */
5970 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005971make_bom(char_u *buf, char_u *name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005972{
5973 int flags;
5974 char_u *p;
5975
5976 flags = get_fio_flags(name);
5977
5978 /* Can't put a BOM in a non-Unicode file. */
5979 if (flags == FIO_LATIN1 || flags == 0)
5980 return 0;
5981
5982 if (flags == FIO_UTF8) /* UTF-8 */
5983 {
5984 buf[0] = 0xef;
5985 buf[1] = 0xbb;
5986 buf[2] = 0xbf;
5987 return 3;
5988 }
5989 p = buf;
5990 (void)ucs2bytes(0xfeff, &p, flags);
5991 return (int)(p - buf);
5992}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005993
5994/*
5995 * Try to find a shortname by comparing the fullname with the current
5996 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00005997 * Returns "full_path" or pointer into "full_path" if shortened.
5998 */
5999 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006000shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006001{
Bram Moolenaard9462e32011-04-11 21:35:11 +02006002 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006003 char_u *p = full_path;
6004
Bram Moolenaard9462e32011-04-11 21:35:11 +02006005 dirname = alloc(MAXPATHL);
6006 if (dirname == NULL)
6007 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006008 if (mch_dirname(dirname, MAXPATHL) == OK)
6009 {
6010 p = shorten_fname(full_path, dirname);
6011 if (p == NULL || *p == NUL)
6012 p = full_path;
6013 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02006014 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00006015 return p;
6016}
6017
6018/*
6019 * Try to find a shortname by comparing the fullname with the current
6020 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006021 * Returns NULL if not shorter name possible, pointer into "full_path"
6022 * otherwise.
6023 */
6024 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006025shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006026{
6027 int len;
6028 char_u *p;
6029
6030 if (full_path == NULL)
6031 return NULL;
6032 len = (int)STRLEN(dir_name);
6033 if (fnamencmp(dir_name, full_path, len) == 0)
6034 {
6035 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006036#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006037 /*
Bram Moolenaar4f974752019-02-17 17:44:42 +01006038 * MS-Windows: when a file is in the root directory, dir_name will end
6039 * in a slash, since C: by itself does not define a specific dir. In
6040 * this case p may already be correct. <negri>
Bram Moolenaar071d4272004-06-13 20:20:40 +00006041 */
6042 if (!((len > 2) && (*(p - 2) == ':')))
6043#endif
6044 {
6045 if (vim_ispathsep(*p))
6046 ++p;
6047#ifndef VMS /* the path separator is always part of the path */
6048 else
6049 p = NULL;
6050#endif
6051 }
6052 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006053#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006054 /*
6055 * When using a file in the current drive, remove the drive name:
6056 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
6057 * a floppy from "A:\dir" to "B:\dir".
6058 */
6059 else if (len > 3
6060 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
6061 && full_path[1] == ':'
6062 && vim_ispathsep(full_path[2]))
6063 p = full_path + 2;
6064#endif
6065 else
6066 p = NULL;
6067 return p;
6068}
6069
6070/*
Bram Moolenaara796d462018-05-01 14:30:36 +02006071 * Shorten filename of a buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006072 * When "force" is TRUE: Use full path from now on for files currently being
6073 * edited, both for file name and swap file name. Try to shorten the file
6074 * names a bit, if safe to do so.
6075 * When "force" is FALSE: Only try to shorten absolute file names.
6076 * For buffers that have buftype "nofile" or "scratch": never change the file
6077 * name.
6078 */
6079 void
Bram Moolenaara796d462018-05-01 14:30:36 +02006080shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
6081{
6082 char_u *p;
6083
6084 if (buf->b_fname != NULL
6085#ifdef FEAT_QUICKFIX
6086 && !bt_nofile(buf)
6087#endif
6088 && !path_with_url(buf->b_fname)
6089 && (force
6090 || buf->b_sfname == NULL
6091 || mch_isFullName(buf->b_sfname)))
6092 {
Bram Moolenaar3d6014f2018-10-11 19:27:47 +02006093 if (buf->b_sfname != buf->b_ffname)
6094 VIM_CLEAR(buf->b_sfname);
Bram Moolenaara796d462018-05-01 14:30:36 +02006095 p = shorten_fname(buf->b_ffname, dirname);
6096 if (p != NULL)
6097 {
6098 buf->b_sfname = vim_strsave(p);
6099 buf->b_fname = buf->b_sfname;
6100 }
6101 if (p == NULL || buf->b_fname == NULL)
6102 buf->b_fname = buf->b_ffname;
6103 }
6104}
6105
6106/*
6107 * Shorten filenames for all buffers.
6108 */
6109 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006110shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006111{
6112 char_u dirname[MAXPATHL];
6113 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006114
6115 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02006116 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006117 {
Bram Moolenaara796d462018-05-01 14:30:36 +02006118 shorten_buf_fname(buf, dirname, force);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00006119
6120 /* Always make the swap file name a full path, a "nofile" buffer may
6121 * also have a swap file. */
6122 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006123 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006124 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00006125 redraw_tabline = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006126}
6127
6128#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
6129 || defined(FEAT_GUI_MSWIN) \
6130 || defined(FEAT_GUI_MAC) \
6131 || defined(PROTO)
6132/*
6133 * Shorten all filenames in "fnames[count]" by current directory.
6134 */
6135 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006136shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006137{
6138 int i;
6139 char_u dirname[MAXPATHL];
6140 char_u *p;
6141
6142 if (fnames == NULL || count < 1)
6143 return;
6144 mch_dirname(dirname, sizeof(dirname));
6145 for (i = 0; i < count; ++i)
6146 {
6147 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
6148 {
6149 /* shorten_fname() returns pointer in given "fnames[i]". If free
6150 * "fnames[i]" first, "p" becomes invalid. So we need to copy
6151 * "p" first then free fnames[i]. */
6152 p = vim_strsave(p);
6153 vim_free(fnames[i]);
6154 fnames[i] = p;
6155 }
6156 }
6157}
6158#endif
6159
6160/*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02006161 * Add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00006162 * fo_o_h.ext for MSDOS or when shortname option set.
6163 *
6164 * Assumed that fname is a valid name found in the filesystem we assure that
6165 * the return value is a different name and ends in 'ext'.
6166 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
6167 * characters otherwise.
6168 * Space for the returned name is allocated, must be freed later.
6169 * Returns NULL when out of memory.
6170 */
6171 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006172modname(
6173 char_u *fname,
6174 char_u *ext,
6175 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006176{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01006177 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00006178 fname, ext, prepend_dot);
6179}
6180
6181 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006182buf_modname(
6183 int shortname, /* use 8.3 file name */
6184 char_u *fname,
6185 char_u *ext,
6186 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006187{
6188 char_u *retval;
6189 char_u *s;
6190 char_u *e;
6191 char_u *ptr;
6192 int fnamelen, extlen;
6193
6194 extlen = (int)STRLEN(ext);
6195
6196 /*
6197 * If there is no file name we must get the name of the current directory
6198 * (we need the full path in case :cd is used).
6199 */
6200 if (fname == NULL || *fname == NUL)
6201 {
Bram Moolenaar964b3742019-05-24 18:54:09 +02006202 retval = alloc(MAXPATHL + extlen + 3);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006203 if (retval == NULL)
6204 return NULL;
6205 if (mch_dirname(retval, MAXPATHL) == FAIL ||
6206 (fnamelen = (int)STRLEN(retval)) == 0)
6207 {
6208 vim_free(retval);
6209 return NULL;
6210 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00006211 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006212 {
6213 retval[fnamelen++] = PATHSEP;
6214 retval[fnamelen] = NUL;
6215 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006216 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006217 }
6218 else
6219 {
6220 fnamelen = (int)STRLEN(fname);
Bram Moolenaar964b3742019-05-24 18:54:09 +02006221 retval = alloc(fnamelen + extlen + 3);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006222 if (retval == NULL)
6223 return NULL;
6224 STRCPY(retval, fname);
6225#ifdef VMS
6226 vms_remove_version(retval); /* we do not need versions here */
6227#endif
6228 }
6229
6230 /*
6231 * search backwards until we hit a '/', '\' or ':' replacing all '.'
6232 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
6233 * Then truncate what is after the '/', '\' or ':' to 8 characters for
6234 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
6235 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01006236 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006237 {
Bram Moolenaar00f148d2019-02-12 22:37:27 +01006238 if (*ext == '.' && shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006239 if (*ptr == '.') /* replace '.' by '_' */
6240 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006241 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006242 {
6243 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006244 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00006245 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006246 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006247
6248 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006249 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
6250 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006251
6252 s = ptr + STRLEN(ptr);
6253
6254 /*
6255 * For 8.3 file names we may have to reduce the length.
6256 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006257 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006258 {
6259 /*
6260 * If there is no file name, or the file name ends in '/', and the
6261 * extension starts with '.', put a '_' before the dot, because just
6262 * ".ext" is invalid.
6263 */
6264 if (fname == NULL || *fname == NUL
6265 || vim_ispathsep(fname[STRLEN(fname) - 1]))
6266 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006267 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006268 *s++ = '_';
6269 }
6270 /*
6271 * If the extension starts with '.', truncate the base name at 8
6272 * characters
6273 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006274 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006275 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00006276 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006277 {
6278 s = ptr + 8;
6279 *s = '\0';
6280 }
6281 }
6282 /*
6283 * If the extension doesn't start with '.', and the file name
6284 * doesn't have an extension yet, append a '.'
6285 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006286 else if ((e = vim_strchr(ptr, '.')) == NULL)
6287 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006288 /*
6289 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00006290 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00006291 */
6292 else if ((int)STRLEN(e) + extlen > 4)
6293 s = e + 4 - extlen;
6294 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01006295#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00006296 /*
6297 * If there is no file name, and the extension starts with '.', put a
6298 * '_' before the dot, because just ".ext" may be invalid if it's on a
6299 * FAT partition, and on HPFS it doesn't matter.
6300 */
6301 else if ((fname == NULL || *fname == NUL) && *ext == '.')
6302 *s++ = '_';
6303#endif
6304
6305 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006306 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006307 * ext can start with '.' and cannot exceed 3 more characters.
6308 */
6309 STRCPY(s, ext);
6310
Bram Moolenaar071d4272004-06-13 20:20:40 +00006311 /*
6312 * Prepend the dot.
6313 */
Bram Moolenaar00f148d2019-02-12 22:37:27 +01006314 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00006315 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006316 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006317 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00006318 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006319
6320 /*
6321 * Check that, after appending the extension, the file name is really
6322 * different.
6323 */
6324 if (fname != NULL && STRCMP(fname, retval) == 0)
6325 {
6326 /* we search for a character that can be replaced by '_' */
6327 while (--s >= ptr)
6328 {
6329 if (*s != '_')
6330 {
6331 *s = '_';
6332 break;
6333 }
6334 }
6335 if (s < ptr) /* fname was "________.<ext>", how tricky! */
6336 *ptr = 'v';
6337 }
6338 return retval;
6339}
6340
6341/*
6342 * Like fgets(), but if the file line is too long, it is truncated and the
6343 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01006344 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006345 */
6346 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006347vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006348{
6349 char *eof;
6350#define FGETS_SIZE 200
6351 char tbuf[FGETS_SIZE];
6352
6353 buf[size - 2] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006354 eof = fgets((char *)buf, size, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006355 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
6356 {
6357 buf[size - 1] = NUL; /* Truncate the line */
6358
6359 /* Now throw away the rest of the line: */
6360 do
6361 {
6362 tbuf[FGETS_SIZE - 2] = NUL;
Bram Moolenaar42335f52018-09-13 15:33:43 +02006363 vim_ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006364 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
6365 }
6366 return (eof == NULL);
6367}
6368
Bram Moolenaar071d4272004-06-13 20:20:40 +00006369/*
6370 * rename() only works if both files are on the same file system, this
6371 * function will (attempts to?) copy the file across if rename fails -- webb
6372 * Return -1 for failure, 0 for success.
6373 */
6374 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006375vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006376{
6377 int fd_in;
6378 int fd_out;
6379 int n;
6380 char *errmsg = NULL;
6381 char *buffer;
6382#ifdef AMIGA
6383 BPTR flock;
6384#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006385 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006386 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006387#ifdef HAVE_ACL
6388 vim_acl_T acl; /* ACL from original file */
6389#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006390 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006391
6392 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006393 * When the names are identical, there is nothing to do. When they refer
6394 * to the same file (ignoring case and slash/backslash differences) but
6395 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00006396 */
6397 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006398 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01006399 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006400 use_tmp_file = TRUE;
6401 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006402 return 0;
6403 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006404
6405 /*
6406 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
6407 */
6408 if (mch_stat((char *)from, &st) < 0)
6409 return -1;
6410
Bram Moolenaar3576da72008-12-30 15:15:57 +00006411#ifdef UNIX
6412 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02006413 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006414
6415 /* It's possible for the source and destination to be the same file.
6416 * This happens when "from" and "to" differ in case and are on a FAT32
6417 * filesystem. In that case go through a temp file name. */
6418 if (mch_stat((char *)to, &st_to) >= 0
6419 && st.st_dev == st_to.st_dev
6420 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006421 use_tmp_file = TRUE;
6422 }
6423#endif
Bram Moolenaar4f974752019-02-17 17:44:42 +01006424#ifdef MSWIN
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02006425 {
6426 BY_HANDLE_FILE_INFORMATION info1, info2;
6427
6428 /* It's possible for the source and destination to be the same file.
6429 * In that case go through a temp file name. This makes rename("foo",
6430 * "./foo") a no-op (in a complicated way). */
6431 if (win32_fileinfo(from, &info1) == FILEINFO_OK
6432 && win32_fileinfo(to, &info2) == FILEINFO_OK
6433 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
6434 && info1.nFileIndexHigh == info2.nFileIndexHigh
6435 && info1.nFileIndexLow == info2.nFileIndexLow)
6436 use_tmp_file = TRUE;
6437 }
6438#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006439
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006440 if (use_tmp_file)
6441 {
6442 char tempname[MAXPATHL + 1];
6443
6444 /*
6445 * Find a name that doesn't exist and is in the same directory.
6446 * Rename "from" to "tempname" and then rename "tempname" to "to".
6447 */
6448 if (STRLEN(from) >= MAXPATHL - 5)
6449 return -1;
6450 STRCPY(tempname, from);
6451 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006452 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006453 sprintf((char *)gettail((char_u *)tempname), "%d", n);
6454 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006455 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006456 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00006457 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006458 if (mch_rename(tempname, (char *)to) == 0)
6459 return 0;
6460 /* Strange, the second step failed. Try moving the
6461 * file back and return failure. */
6462 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00006463 return -1;
6464 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006465 /* If it fails for one temp name it will most likely fail
6466 * for any temp name, give up. */
6467 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006468 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006469 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00006470 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00006471 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00006472
Bram Moolenaar071d4272004-06-13 20:20:40 +00006473 /*
6474 * Delete the "to" file, this is required on some systems to make the
6475 * mch_rename() work, on other systems it makes sure that we don't have
6476 * two files when the mch_rename() fails.
6477 */
6478
6479#ifdef AMIGA
6480 /*
6481 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
6482 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00006483 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00006484 * deleting the "from" file (horror!) we lock it during the remove.
6485 *
6486 * When used for making a backup before writing the file: This should not
6487 * happen with ":w", because startscript() should detect this problem and
6488 * set buf->b_shortname, causing modname() to return a correct ".bak" file
6489 * name. This problem does exist with ":w filename", but then the
6490 * original file will be somewhere else so the backup isn't really
6491 * important. If autoscripting is off the rename may fail.
6492 */
6493 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
6494#endif
6495 mch_remove(to);
6496#ifdef AMIGA
6497 if (flock)
6498 UnLock(flock);
6499#endif
6500
6501 /*
6502 * First try a normal rename, return if it works.
6503 */
6504 if (mch_rename((char *)from, (char *)to) == 0)
6505 return 0;
6506
6507 /*
6508 * Rename() failed, try copying the file.
6509 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006510 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006511#ifdef HAVE_ACL
6512 /* For systems that support ACL: get the ACL from the original file. */
6513 acl = mch_get_acl(from);
6514#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006515 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
6516 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006517 {
6518#ifdef HAVE_ACL
6519 mch_free_acl(acl);
6520#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006521 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006522 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006523
6524 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00006525 fd_out = mch_open((char *)to,
6526 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006527 if (fd_out == -1)
6528 {
6529 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006530#ifdef HAVE_ACL
6531 mch_free_acl(acl);
6532#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006533 return -1;
6534 }
6535
6536 buffer = (char *)alloc(BUFSIZE);
6537 if (buffer == NULL)
6538 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006539 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006540 close(fd_in);
6541#ifdef HAVE_ACL
6542 mch_free_acl(acl);
6543#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006544 return -1;
6545 }
6546
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01006547 while ((n = read_eintr(fd_in, buffer, BUFSIZE)) > 0)
6548 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006549 {
6550 errmsg = _("E208: Error writing to \"%s\"");
6551 break;
6552 }
6553
6554 vim_free(buffer);
6555 close(fd_in);
6556 if (close(fd_out) < 0)
6557 errmsg = _("E209: Error closing \"%s\"");
6558 if (n < 0)
6559 {
6560 errmsg = _("E210: Error reading \"%s\"");
6561 to = from;
6562 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00006563#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00006564 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00006565#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006566#ifdef HAVE_ACL
6567 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00006568 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00006569#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02006570#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01006571 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01006572#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006573 if (errmsg != NULL)
6574 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006575 semsg(errmsg, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006576 return -1;
6577 }
6578 mch_remove(from);
6579 return 0;
6580}
6581
6582static int already_warned = FALSE;
6583
6584/*
6585 * Check if any not hidden buffer has been changed.
6586 * Postpone the check if there are characters in the stuff buffer, a global
6587 * command is being executed, a mapping is being executed or an autocommand is
6588 * busy.
6589 * Returns TRUE if some message was written (screen should be redrawn and
6590 * cursor positioned).
6591 */
6592 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006593check_timestamps(
6594 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006595{
6596 buf_T *buf;
6597 int didit = 0;
6598 int n;
6599
6600 /* Don't check timestamps while system() or another low-level function may
6601 * cause us to lose and gain focus. */
6602 if (no_check_timestamps > 0)
6603 return FALSE;
6604
6605 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
6606 * event and we would keep on checking if the file is steadily growing.
6607 * Do check again after typing something. */
6608 if (focus && did_check_timestamps)
6609 {
6610 need_check_timestamps = TRUE;
6611 return FALSE;
6612 }
6613
6614 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006615 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006616 need_check_timestamps = TRUE; /* check later */
6617 else
6618 {
6619 ++no_wait_return;
6620 did_check_timestamps = TRUE;
6621 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02006622 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006623 {
6624 /* Only check buffers in a window. */
6625 if (buf->b_nwindows > 0)
6626 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006627 bufref_T bufref;
6628
6629 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006630 n = buf_check_timestamp(buf, focus);
6631 if (didit < n)
6632 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006633 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00006634 {
6635 /* Autocommands have removed the buffer, start at the
6636 * first one again. */
6637 buf = firstbuf;
6638 continue;
6639 }
6640 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006641 }
6642 --no_wait_return;
6643 need_check_timestamps = FALSE;
6644 if (need_wait_return && didit == 2)
6645 {
6646 /* make sure msg isn't overwritten */
Bram Moolenaar32526b32019-01-19 17:43:09 +01006647 msg_puts("\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006648 out_flush();
6649 }
6650 }
6651 return didit;
6652}
6653
6654/*
6655 * Move all the lines from buffer "frombuf" to buffer "tobuf".
6656 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
6657 * empty.
6658 */
6659 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006660move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006661{
6662 buf_T *tbuf = curbuf;
6663 int retval = OK;
6664 linenr_T lnum;
6665 char_u *p;
6666
6667 /* Copy the lines in "frombuf" to "tobuf". */
6668 curbuf = tobuf;
6669 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
6670 {
6671 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
6672 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
6673 {
6674 vim_free(p);
6675 retval = FAIL;
6676 break;
6677 }
6678 vim_free(p);
6679 }
6680
6681 /* Delete all the lines in "frombuf". */
6682 if (retval != FAIL)
6683 {
6684 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00006685 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
6686 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006687 {
6688 /* Oops! We could try putting back the saved lines, but that
6689 * might fail again... */
6690 retval = FAIL;
6691 break;
6692 }
6693 }
6694
6695 curbuf = tbuf;
6696 return retval;
6697}
6698
6699/*
6700 * Check if buffer "buf" has been changed.
6701 * Also check if the file for a new buffer unexpectedly appeared.
6702 * return 1 if a changed buffer was found.
6703 * return 2 if a message has been displayed.
6704 * return 0 otherwise.
6705 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006706 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006707buf_check_timestamp(
6708 buf_T *buf,
6709 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00006710{
Bram Moolenaar8767f522016-07-01 17:17:39 +02006711 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006712 int stat_res;
6713 int retval = 0;
6714 char_u *path;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006715 char *tbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006716 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00006717 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006718 int helpmesg = FALSE;
6719 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006720 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006721#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6722 int can_reload = FALSE;
6723#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02006724 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006725 int orig_mode = buf->b_orig_mode;
6726#ifdef FEAT_GUI
6727 int save_mouse_correct = need_mouse_correct;
6728#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006729 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006730 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006731#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006732 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006733#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006734 bufref_T bufref;
6735
6736 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006737
6738 /* If there is no file name, the buffer is not loaded, 'buftype' is
6739 * set, we are in the middle of a save or being called recursively: ignore
6740 * this buffer. */
6741 if (buf->b_ffname == NULL
6742 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar91335e52018-08-01 17:53:12 +02006743 || !bt_normal(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006744 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00006745 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00006746#ifdef FEAT_NETBEANS_INTG
6747 || isNetbeansBuffer(buf)
6748#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02006749#ifdef FEAT_TERMINAL
6750 || buf->b_term != NULL
6751#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006752 )
6753 return 0;
6754
6755 if ( !(buf->b_flags & BF_NOTEDITED)
6756 && buf->b_mtime != 0
6757 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
6758 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02006759 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00006760#ifdef HAVE_ST_MODE
6761 || (int)st.st_mode != buf->b_orig_mode
6762#else
6763 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
6764#endif
6765 ))
6766 {
6767 retval = 1;
6768
Bram Moolenaar386bc822018-07-07 18:34:12 +02006769 // set b_mtime to stop further warnings (e.g., when executing
6770 // FileChangedShell autocmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006771 if (stat_res < 0)
6772 {
Bram Moolenaar8239c622019-05-24 16:46:01 +02006773 // Check the file again later to see if it re-appears.
6774 buf->b_mtime = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006775 buf->b_orig_size = 0;
6776 buf->b_orig_mode = 0;
6777 }
6778 else
6779 buf_store_time(buf, &st, buf->b_ffname);
6780
6781 /* Don't do anything for a directory. Might contain the file
6782 * explorer. */
6783 if (mch_isdir(buf->b_fname))
6784 ;
6785
6786 /*
6787 * If 'autoread' is set, the buffer has no changes and the file still
6788 * exists, reload the buffer. Use the buffer-local option value if it
6789 * was set, the global option value otherwise.
6790 */
6791 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
6792 && !bufIsChanged(buf) && stat_res >= 0)
6793 reload = TRUE;
6794 else
6795 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006796 if (stat_res < 0)
6797 reason = "deleted";
6798 else if (bufIsChanged(buf))
6799 reason = "conflict";
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01006800 /*
6801 * Check if the file contents really changed to avoid giving a
6802 * warning when only the timestamp was set (e.g., checked out of
6803 * CVS). Always warn when the buffer was changed.
6804 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006805 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
6806 reason = "changed";
6807 else if (orig_mode != buf->b_orig_mode)
6808 reason = "mode";
6809 else
6810 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00006811
6812 /*
6813 * Only give the warning if there are no FileChangedShell
6814 * autocommands.
6815 * Avoid being called recursively by setting "busy".
6816 */
6817 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006818#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006819 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
6820 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006821#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006822 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006823 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
6824 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00006825 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006826 busy = FALSE;
6827 if (n)
6828 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006829 if (!bufref_valid(&bufref))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006830 emsg(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006831#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006832 s = get_vim_var_str(VV_FCS_CHOICE);
6833 if (STRCMP(s, "reload") == 0 && *reason != 'd')
6834 reload = TRUE;
6835 else if (STRCMP(s, "ask") == 0)
6836 n = FALSE;
6837 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006838#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006839 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006840 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006841 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006842 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006843 if (*reason == 'd')
6844 mesg = _("E211: File \"%s\" no longer available");
Bram Moolenaar071d4272004-06-13 20:20:40 +00006845 else
6846 {
6847 helpmesg = TRUE;
6848#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6849 can_reload = TRUE;
6850#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006851 if (reason[2] == 'n')
6852 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006853 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006854 mesg2 = _("See \":help W12\" for more info.");
6855 }
6856 else if (reason[1] == 'h')
6857 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006858 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006859 mesg2 = _("See \":help W11\" for more info.");
6860 }
6861 else if (*reason == 'm')
6862 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006863 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006864 mesg2 = _("See \":help W16\" for more info.");
6865 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00006866 else
6867 /* Only timestamp changed, store it to avoid a warning
6868 * in check_mtime() later. */
6869 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006870 }
6871 }
6872 }
6873
6874 }
6875 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
6876 && vim_fexists(buf->b_ffname))
6877 {
6878 retval = 1;
6879 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
6880 buf->b_flags |= BF_NEW_W;
6881#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6882 can_reload = TRUE;
6883#endif
6884 }
6885
6886 if (mesg != NULL)
6887 {
6888 path = home_replace_save(buf, buf->b_fname);
6889 if (path != NULL)
6890 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00006891 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006892 mesg2 = "";
Bram Moolenaar964b3742019-05-24 18:54:09 +02006893 tbuf = (char *)alloc(STRLEN(path) + STRLEN(mesg)
6894 + STRLEN(mesg2) + 2);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006895 sprintf(tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006896#ifdef FEAT_EVAL
6897 /* Set warningmsg here, before the unimportant and output-specific
6898 * mesg2 has been appended. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006899 set_vim_var_string(VV_WARNINGMSG, (char_u *)tbuf, -1);
Bram Moolenaar496c5262009-03-18 14:42:00 +00006900#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006901#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
6902 if (can_reload)
6903 {
6904 if (*mesg2 != NUL)
6905 {
6906 STRCAT(tbuf, "\n");
6907 STRCAT(tbuf, mesg2);
6908 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006909 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"),
6910 (char_u *)tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01006911 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006912 reload = TRUE;
6913 }
6914 else
6915#endif
6916 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
6917 {
6918 if (*mesg2 != NUL)
6919 {
6920 STRCAT(tbuf, "; ");
6921 STRCAT(tbuf, mesg2);
6922 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01006923 emsg(tbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006924 retval = 2;
6925 }
6926 else
6927 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00006928 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00006929 {
6930 msg_start();
Bram Moolenaar32526b32019-01-19 17:43:09 +01006931 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006932 if (*mesg2 != NUL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01006933 msg_puts_attr(mesg2, HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006934 msg_clr_eos();
6935 (void)msg_end();
6936 if (emsg_silent == 0)
6937 {
6938 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006939#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00006940 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01006941#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00006942 /* give the user some time to think about it */
6943 ui_delay(1000L, TRUE);
6944
6945 /* don't redraw and erase the message */
6946 redraw_cmdline = FALSE;
6947 }
6948 }
6949 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00006950 }
6951
6952 vim_free(path);
6953 vim_free(tbuf);
6954 }
6955 }
6956
6957 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02006958 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006959 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00006960 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02006961#ifdef FEAT_PERSISTENT_UNDO
6962 if (buf->b_p_udf && buf->b_ffname != NULL)
6963 {
6964 char_u hash[UNDO_HASH_SIZE];
6965 buf_T *save_curbuf = curbuf;
6966
6967 /* Any existing undo file is unusable, write it now. */
6968 curbuf = buf;
6969 u_compute_hash(hash);
6970 u_write_undo(NULL, FALSE, buf, hash);
6971 curbuf = save_curbuf;
6972 }
6973#endif
6974 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00006975
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00006976 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02006977 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00006978 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
6979 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00006980#ifdef FEAT_GUI
6981 /* restore this in case an autocommand has set it; it would break
6982 * 'mousefocus' */
6983 need_mouse_correct = save_mouse_correct;
6984#endif
6985
6986 return retval;
6987}
6988
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006989/*
6990 * Reload a buffer that is already loaded.
6991 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00006992 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
6993 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006994 */
6995 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01006996buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00006997{
6998 exarg_T ea;
6999 pos_T old_cursor;
7000 linenr_T old_topline;
7001 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007002 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007003 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007004 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007005 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007006 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007007
7008 /* set curwin/curbuf for "buf" and save some things */
7009 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007010
7011 /* We only want to read the text from the file, not reset the syntax
7012 * highlighting, clear marks, diff status, etc. Force the fileformat
7013 * and encoding to be the same. */
7014 if (prep_exarg(&ea, buf) == OK)
7015 {
7016 old_cursor = curwin->w_cursor;
7017 old_topline = curwin->w_topline;
7018
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007019 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007020 {
7021 /* Save all the text, so that the reload can be undone.
7022 * Sync first so that this is a separate undo-able action. */
7023 u_sync(FALSE);
7024 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
7025 flags |= READ_KEEP_UNDO;
7026 }
7027
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007028 /*
7029 * To behave like when a new file is edited (matters for
7030 * BufReadPost autocommands) we first need to delete the current
7031 * buffer contents. But if reading the file fails we should keep
7032 * the old contents. Can't use memory only, the file might be
7033 * too big. Use a hidden buffer to move the buffer contents to.
7034 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007035 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007036 savebuf = NULL;
7037 else
7038 {
7039 /* Allocate a buffer without putting it in the buffer list. */
7040 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007041 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00007042 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007043 {
7044 /* Open the memline. */
7045 curbuf = savebuf;
7046 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00007047 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007048 curbuf = buf;
7049 curwin->w_buffer = buf;
7050 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00007051 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007052 || move_lines(buf, savebuf) == FAIL)
7053 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007054 semsg(_("E462: Could not prepare for reloading \"%s\""),
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007055 buf->b_fname);
7056 saved = FAIL;
7057 }
7058 }
7059
7060 if (saved == OK)
7061 {
7062 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007063 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007064 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
7065 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01007066 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007067 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01007068#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007069 if (!aborting())
7070#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007071 semsg(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007072 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007073 {
7074 /* Put the text back from the save buffer. First
7075 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01007076 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00007077 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007078 break;
7079 (void)move_lines(savebuf, buf);
7080 }
7081 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007082 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007083 {
7084 /* Mark the buffer as unmodified and free undo info. */
7085 unchanged(buf, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007086 if ((flags & READ_KEEP_UNDO) == 0)
7087 {
7088 u_blockfree(buf);
7089 u_clearall(buf);
7090 }
7091 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007092 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02007093 /* Mark all undo states as changed. */
7094 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02007095 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007096 }
7097 }
7098 vim_free(ea.cmd);
7099
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02007100 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007101 wipe_buffer(savebuf, FALSE);
7102
7103#ifdef FEAT_DIFF
7104 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00007105 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007106#endif
7107
7108 /* Restore the topline and cursor position and check it (lines may
7109 * have been removed). */
7110 if (old_topline > curbuf->b_ml.ml_line_count)
7111 curwin->w_topline = curbuf->b_ml.ml_line_count;
7112 else
7113 curwin->w_topline = old_topline;
7114 curwin->w_cursor = old_cursor;
7115 check_cursor();
7116 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007117 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007118#ifdef FEAT_FOLDING
7119 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007120 win_T *wp;
7121 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007122
7123 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00007124 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007125 if (wp->w_buffer == curwin->w_buffer
7126 && !foldmethodIsManual(wp))
7127 foldUpdateAll(wp);
7128 }
7129#endif
7130 /* If the mode didn't change and 'readonly' was set, keep the old
7131 * value; the user probably used the ":view" command. But don't
7132 * reset it, might have had a read error. */
7133 if (orig_mode == curbuf->b_orig_mode)
7134 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01007135
7136 /* Modelines must override settings done by autocommands. */
7137 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007138 }
7139
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007140 /* restore curwin/curbuf and a few other things */
7141 aucmd_restbuf(&aco);
7142 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00007143}
7144
Bram Moolenaar071d4272004-06-13 20:20:40 +00007145 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02007146buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007147{
7148 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02007149 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007150#ifdef HAVE_ST_MODE
7151 buf->b_orig_mode = (int)st->st_mode;
7152#else
7153 buf->b_orig_mode = mch_getperm(fname);
7154#endif
7155}
7156
7157/*
7158 * Adjust the line with missing eol, used for the next write.
7159 * Used for do_filter(), when the input lines for the filter are deleted.
7160 */
7161 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007162write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007163{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01007164 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
7165 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007166}
7167
Bram Moolenaarda440d22016-01-16 21:27:23 +01007168#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
7169/*
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007170 * Core part of "readdir()" function.
7171 * Retrieve the list of files/directories of "path" into "gap".
7172 * Return OK for success, FAIL for failure.
7173 */
7174 int
7175readdir_core(
7176 garray_T *gap,
7177 char_u *path,
7178 void *context,
7179 int (*checkitem)(void *context, char_u *name))
7180{
7181 int failed = FALSE;
7182#ifdef MSWIN
7183 char_u *buf, *p;
7184 int ok;
7185 HANDLE hFind = INVALID_HANDLE_VALUE;
7186 WIN32_FIND_DATAW wfb;
7187 WCHAR *wn = NULL; // UTF-16 name, NULL when not used.
7188#endif
7189
7190 ga_init2(gap, (int)sizeof(char *), 20);
7191
7192#ifdef MSWIN
7193 buf = alloc((int)MAXPATHL);
7194 if (buf == NULL)
7195 return FAIL;
7196 STRNCPY(buf, path, MAXPATHL-5);
Bram Moolenaar71de7202019-05-24 19:04:29 +02007197 p = buf + STRLEN(buf);
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007198 MB_PTR_BACK(buf, p);
7199 if (*p == '\\' || *p == '/')
7200 *p = NUL;
7201 STRCAT(buf, "\\*");
7202
7203 wn = enc_to_utf16(buf, NULL);
7204 if (wn != NULL)
7205 hFind = FindFirstFileW(wn, &wfb);
7206 ok = (hFind != INVALID_HANDLE_VALUE);
7207 if (!ok)
7208 {
7209 failed = TRUE;
7210 smsg(_(e_notopen), path);
7211 }
7212 else
7213 {
7214 while (ok)
7215 {
7216 int ignore;
7217
7218 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
7219 if (p == NULL)
7220 break; // out of memory
7221
7222 ignore = p[0] == '.' && (p[1] == NUL
7223 || (p[1] == '.' && p[2] == NUL));
7224 if (!ignore && checkitem != NULL)
7225 {
7226 int r = checkitem(context, p);
7227
7228 if (r < 0)
7229 {
7230 vim_free(p);
7231 break;
7232 }
7233 if (r == 0)
7234 ignore = TRUE;
7235 }
7236
7237 if (!ignore)
7238 {
7239 if (ga_grow(gap, 1) == OK)
7240 ((char_u**)gap->ga_data)[gap->ga_len++] = vim_strsave(p);
7241 else
7242 {
7243 failed = TRUE;
7244 vim_free(p);
7245 break;
7246 }
7247 }
7248
7249 vim_free(p);
7250 ok = FindNextFileW(hFind, &wfb);
7251 }
7252 FindClose(hFind);
7253 }
7254
7255 vim_free(buf);
7256 vim_free(wn);
7257#else
7258 DIR *dirp;
7259 struct dirent *dp;
7260 char_u *p;
7261
7262 dirp = opendir((char *)path);
7263 if (dirp == NULL)
7264 {
7265 failed = TRUE;
7266 smsg(_(e_notopen), path);
7267 }
7268 else
7269 {
7270 for (;;)
7271 {
7272 int ignore;
7273
7274 dp = readdir(dirp);
7275 if (dp == NULL)
7276 break;
7277 p = (char_u *)dp->d_name;
7278
7279 ignore = p[0] == '.' &&
7280 (p[1] == NUL ||
7281 (p[1] == '.' && p[2] == NUL));
7282 if (!ignore && checkitem != NULL)
7283 {
7284 int r = checkitem(context, p);
7285
7286 if (r < 0)
7287 break;
7288 if (r == 0)
7289 ignore = TRUE;
7290 }
7291
7292 if (!ignore)
7293 {
7294 if (ga_grow(gap, 1) == OK)
7295 ((char_u**)gap->ga_data)[gap->ga_len++] = vim_strsave(p);
7296 else
7297 {
7298 failed = TRUE;
7299 break;
7300 }
7301 }
7302 }
7303
7304 closedir(dirp);
7305 }
7306#endif
7307
7308 if (!failed && gap->ga_len > 0)
7309 sort_strings((char_u **)gap->ga_data, gap->ga_len);
7310
7311 return failed ? FAIL : OK;
7312}
7313
7314/*
Bram Moolenaarda440d22016-01-16 21:27:23 +01007315 * Delete "name" and everything in it, recursively.
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007316 * return 0 for success, -1 if some file was not deleted.
Bram Moolenaarda440d22016-01-16 21:27:23 +01007317 */
7318 int
7319delete_recursive(char_u *name)
7320{
7321 int result = 0;
Bram Moolenaarda440d22016-01-16 21:27:23 +01007322 int i;
7323 char_u *exp;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007324 garray_T ga;
Bram Moolenaarda440d22016-01-16 21:27:23 +01007325
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007326 // A symbolic link to a directory itself is deleted, not the directory it
7327 // points to.
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007328 if (
Bram Moolenaar4f974752019-02-17 17:44:42 +01007329# if defined(UNIX) || defined(MSWIN)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007330 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01007331# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007332 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01007333# endif
7334 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01007335 {
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007336 exp = vim_strsave(name);
Bram Moolenaarda440d22016-01-16 21:27:23 +01007337 if (exp == NULL)
7338 return -1;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007339 if (readdir_core(&ga, exp, NULL, NULL) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007340 {
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007341 for (i = 0; i < ga.ga_len; ++i)
7342 {
7343 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/%s", exp,
7344 ((char_u **)ga.ga_data)[i]);
7345 if (delete_recursive(NameBuff) != 0)
Bram Moolenaarda440d22016-01-16 21:27:23 +01007346 result = -1;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007347 }
7348 ga_clear_strings(&ga);
Bram Moolenaarda440d22016-01-16 21:27:23 +01007349 }
7350 else
7351 result = -1;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02007352 (void)mch_rmdir(exp);
Bram Moolenaarda440d22016-01-16 21:27:23 +01007353 vim_free(exp);
Bram Moolenaarda440d22016-01-16 21:27:23 +01007354 }
7355 else
7356 result = mch_remove(name) == 0 ? 0 : -1;
7357
7358 return result;
7359}
7360#endif
7361
Bram Moolenaar071d4272004-06-13 20:20:40 +00007362#if defined(TEMPDIRNAMES) || defined(PROTO)
7363static long temp_count = 0; /* Temp filename counter. */
7364
7365/*
7366 * Delete the temp directory and all files it contains.
7367 */
7368 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007369vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007370{
Bram Moolenaar071d4272004-06-13 20:20:40 +00007371 if (vim_tempdir != NULL)
7372 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01007373 /* remove the trailing path separator */
7374 gettail(vim_tempdir)[-1] = NUL;
7375 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01007376 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007377 }
7378}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007379
7380/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00007381 * Directory "tempdir" was created. Expand this name to a full path and put
7382 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
7383 * "tempdir" must be no longer than MAXPATHL.
7384 */
7385 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007386vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007387{
7388 char_u *buf;
7389
Bram Moolenaar964b3742019-05-24 18:54:09 +02007390 buf = alloc(MAXPATHL + 2);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007391 if (buf != NULL)
7392 {
7393 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
7394 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007395 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007396 vim_tempdir = vim_strsave(buf);
7397 vim_free(buf);
7398 }
7399}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00007400#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00007401
7402/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00007403 * vim_tempname(): Return a unique name that can be used for a temp file.
7404 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02007405 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
7406 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007407 *
7408 * The returned pointer is to allocated memory.
7409 * The returned pointer is NULL if no valid name was found.
7410 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007411 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007412vim_tempname(
7413 int extra_char UNUSED, /* char to use in the name instead of '?' */
7414 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007415{
7416#ifdef USE_TMPNAM
7417 char_u itmp[L_tmpnam]; /* use tmpnam() */
Bram Moolenaar4f974752019-02-17 17:44:42 +01007418#elif defined(MSWIN)
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01007419 WCHAR itmp[TEMPNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007420#else
7421 char_u itmp[TEMPNAMELEN];
7422#endif
7423
7424#ifdef TEMPDIRNAMES
7425 static char *(tempdirs[]) = {TEMPDIRNAMES};
7426 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007427# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02007428 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007429# endif
7430
7431 /*
7432 * This will create a directory for private use by this instance of Vim.
7433 * This is done once, and the same directory is used for all temp files.
7434 * This method avoids security problems because of symlink attacks et al.
7435 * It's also a bit faster, because we only need to check for an existing
7436 * file when creating the directory and not for each temp file.
7437 */
7438 if (vim_tempdir == NULL)
7439 {
7440 /*
7441 * Try the entries in TEMPDIRNAMES to create the temp directory.
7442 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00007443 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007444 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007445# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007446 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007447 long nr;
7448 long off;
7449# endif
7450
Bram Moolenaare1a61992015-12-03 21:02:27 +01007451 /* Expand $TMP, leave room for "/v1100000/999999999".
7452 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007453 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01007454 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007455 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01007456 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02007457 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007458
Bram Moolenaareaf03392009-11-17 11:08:52 +00007459# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02007460 {
7461# if defined(UNIX) || defined(VMS)
7462 /* Make sure the umask doesn't remove the executable bit.
7463 * "repl" has been reported to use "177". */
7464 mode_t umask_save = umask(077);
7465# endif
7466 /* Leave room for filename */
7467 STRCAT(itmp, "vXXXXXX");
7468 if (mkdtemp((char *)itmp) != NULL)
7469 vim_settempdir(itmp);
7470# if defined(UNIX) || defined(VMS)
7471 (void)umask(umask_save);
7472# endif
7473 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007474# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00007475 /* Get an arbitrary number of up to 6 digits. When it's
7476 * unlikely that it already exists it will be faster,
7477 * otherwise it doesn't matter. The use of mkdir() avoids any
7478 * security problems because of the predictable number. */
7479 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01007480 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007481
7482 /* Try up to 10000 different values until we find a name that
7483 * doesn't exist. */
7484 for (off = 0; off < 10000L; ++off)
7485 {
7486 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007487# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007488 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007489# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007490
Bram Moolenaareaf03392009-11-17 11:08:52 +00007491 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
7492# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007493 /* If mkdir() does not set errno to EEXIST, check for
7494 * existing file here. There is a race condition then,
7495 * although it's fail-safe. */
7496 if (mch_stat((char *)itmp, &st) >= 0)
7497 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00007498# endif
7499# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007500 /* Make sure the umask doesn't remove the executable bit.
7501 * "repl" has been reported to use "177". */
7502 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007503# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007504 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007505# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007506 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00007507# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007508 if (r == 0)
7509 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00007510 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007511 break;
7512 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007513# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00007514 /* If the mkdir() didn't fail because the file/dir exists,
7515 * we probably can't create any dir here, try another
7516 * place. */
7517 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00007518# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00007519 break;
7520 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00007521# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007522 if (vim_tempdir != NULL)
7523 break;
7524 }
7525 }
7526 }
7527
7528 if (vim_tempdir != NULL)
7529 {
7530 /* There is no need to check if the file exists, because we own the
7531 * directory and nobody else creates a file in it. */
7532 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
7533 return vim_strsave(itmp);
7534 }
7535
7536 return NULL;
7537
7538#else /* TEMPDIRNAMES */
7539
Bram Moolenaar4f974752019-02-17 17:44:42 +01007540# ifdef MSWIN
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01007541 WCHAR wszTempFile[_MAX_PATH + 1];
7542 WCHAR buf4[4];
Bram Moolenaar071d4272004-06-13 20:20:40 +00007543 char_u *retval;
7544 char_u *p;
7545
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01007546 wcscpy(itmp, L"");
7547 if (GetTempPathW(_MAX_PATH, wszTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01007548 {
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01007549 wszTempFile[0] = L'.'; // GetTempPathW() failed, use current dir
7550 wszTempFile[1] = NUL;
Bram Moolenaarb1891912011-02-09 14:47:03 +01007551 }
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01007552 wcscpy(buf4, L"VIM");
Bram Moolenaar071d4272004-06-13 20:20:40 +00007553 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01007554 if (GetTempFileNameW(wszTempFile, buf4, 0, itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007555 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02007556 if (!keep)
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01007557 // GetTempFileName() will create the file, we don't want that
7558 (void)DeleteFileW(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007559
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01007560 // Backslashes in a temp file name cause problems when filtering with
7561 // "sh". NOTE: This also checks 'shellcmdflag' to help those people who
7562 // didn't set 'shellslash'.
7563 retval = utf16_to_enc(itmp, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007564 if (*p_shcf == '-' || p_ssl)
7565 for (p = retval; *p; ++p)
7566 if (*p == '\\')
7567 *p = '/';
7568 return retval;
7569
Bram Moolenaar4f974752019-02-17 17:44:42 +01007570# else // MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007571
7572# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007573 char_u *p;
7574
Bram Moolenaar071d4272004-06-13 20:20:40 +00007575 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01007576 p = tmpnam((char *)itmp);
7577 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007578 return NULL;
7579# else
7580 char_u *p;
7581
7582# ifdef VMS_TEMPNAM
7583 /* mktemp() is not working on VMS. It seems to be
7584 * a do-nothing function. Therefore we use tempnam().
7585 */
7586 sprintf((char *)itmp, "VIM%c", extra_char);
7587 p = (char_u *)tempnam("tmp:", (char *)itmp);
7588 if (p != NULL)
7589 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01007590 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00007591 * and VIM will then be unable to find the file later */
7592 STRCPY(itmp, p);
7593 STRCAT(itmp, ".txt");
7594 free(p);
7595 }
7596 else
7597 return NULL;
7598# else
7599 STRCPY(itmp, TEMPNAME);
7600 if ((p = vim_strchr(itmp, '?')) != NULL)
7601 *p = extra_char;
7602 if (mktemp((char *)itmp) == NULL)
7603 return NULL;
7604# endif
7605# endif
7606
7607 return vim_strsave(itmp);
Bram Moolenaar4f974752019-02-17 17:44:42 +01007608# endif // MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00007609#endif /* TEMPDIRNAMES */
7610}
7611
7612#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
7613/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007614 * Convert all backslashes in fname to forward slashes in-place, unless when
7615 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007616 */
7617 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007618forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007619{
7620 char_u *p;
7621
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02007622 if (path_with_url(fname))
7623 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007624 for (p = fname; *p != NUL; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007625 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007626 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007627 ++p;
Bram Moolenaar13505972019-01-24 15:04:48 +01007628 else if (*p == '\\')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007629 *p = '/';
7630}
7631#endif
7632
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00007633/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00007634 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
7635 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
7636 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00007637 * Used for autocommands and 'wildignore'.
7638 * Returns TRUE if there is a match, FALSE otherwise.
7639 */
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01007640 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007641match_file_pat(
7642 char_u *pattern, /* pattern to match with */
7643 regprog_T **prog, /* pre-compiled regprog or NULL */
7644 char_u *fname, /* full path of file name */
7645 char_u *sfname, /* short file name or NULL */
7646 char_u *tail, /* tail of path */
7647 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007648{
7649 regmatch_T regmatch;
7650 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007651
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01007652 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01007653 if (prog != NULL)
7654 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007655 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01007656 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007657
7658 /*
7659 * Try for a match with the pattern with:
7660 * 1. the full file name, when the pattern has a '/'.
7661 * 2. the short file name, when the pattern has a '/'.
7662 * 3. the tail of the file name, when the pattern has no '/'.
7663 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01007664 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00007665 && ((allow_dirs
7666 && (vim_regexec(&regmatch, fname, (colnr_T)0)
7667 || (sfname != NULL
7668 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01007669 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007670 result = TRUE;
7671
Bram Moolenaardffa5b82014-11-19 16:38:07 +01007672 if (prog != NULL)
7673 *prog = regmatch.regprog;
7674 else
Bram Moolenaar473de612013-06-08 18:19:48 +02007675 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007676 return result;
7677}
Bram Moolenaar071d4272004-06-13 20:20:40 +00007678
7679#if defined(FEAT_WILDIGN) || defined(PROTO)
7680/*
7681 * Return TRUE if a file matches with a pattern in "list".
7682 * "list" is a comma-separated list of patterns, like 'wildignore'.
7683 * "sfname" is the short file name or NULL, "ffname" the long file name.
7684 */
7685 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007686match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007687{
7688 char_u buf[100];
7689 char_u *tail;
7690 char_u *regpat;
7691 char allow_dirs;
7692 int match;
7693 char_u *p;
7694
7695 tail = gettail(sfname);
7696
7697 /* try all patterns in 'wildignore' */
7698 p = list;
7699 while (*p)
7700 {
7701 copy_option_part(&p, buf, 100, ",");
7702 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
7703 if (regpat == NULL)
7704 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00007705 match = match_file_pat(regpat, NULL, ffname, sfname,
7706 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007707 vim_free(regpat);
7708 if (match)
7709 return TRUE;
7710 }
7711 return FALSE;
7712}
7713#endif
7714
7715/*
7716 * Convert the given pattern "pat" which has shell style wildcards in it, into
7717 * a regular expression, and return the result in allocated memory. If there
7718 * is a directory path separator to be matched, then TRUE is put in
7719 * allow_dirs, otherwise FALSE is put there -- webb.
7720 * Handle backslashes before special characters, like "\*" and "\ ".
7721 *
Bram Moolenaar071d4272004-06-13 20:20:40 +00007722 * Returns NULL when out of memory.
7723 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007724 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007725file_pat_to_reg_pat(
7726 char_u *pat,
7727 char_u *pat_end, /* first char after pattern or NULL */
7728 char *allow_dirs, /* Result passed back out in here */
7729 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007730{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01007731 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007732 char_u *endp;
7733 char_u *reg_pat;
7734 char_u *p;
7735 int i;
7736 int nested = 0;
7737 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007738
7739 if (allow_dirs != NULL)
7740 *allow_dirs = FALSE;
7741 if (pat_end == NULL)
7742 pat_end = pat + STRLEN(pat);
7743
Bram Moolenaar071d4272004-06-13 20:20:40 +00007744 for (p = pat; p < pat_end; p++)
7745 {
7746 switch (*p)
7747 {
7748 case '*':
7749 case '.':
7750 case ',':
7751 case '{':
7752 case '}':
7753 case '~':
7754 size += 2; /* extra backslash */
7755 break;
7756#ifdef BACKSLASH_IN_FILENAME
7757 case '\\':
7758 case '/':
7759 size += 4; /* could become "[\/]" */
7760 break;
7761#endif
7762 default:
7763 size++;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007764 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007765 {
7766 ++p;
7767 ++size;
7768 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007769 break;
7770 }
7771 }
7772 reg_pat = alloc(size + 1);
7773 if (reg_pat == NULL)
7774 return NULL;
7775
Bram Moolenaar071d4272004-06-13 20:20:40 +00007776 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007777
7778 if (pat[0] == '*')
7779 while (pat[0] == '*' && pat < pat_end - 1)
7780 pat++;
7781 else
7782 reg_pat[i++] = '^';
7783 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +02007784 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +00007785 {
7786 while (endp - pat > 0 && *endp == '*')
7787 endp--;
7788 add_dollar = FALSE;
7789 }
7790 for (p = pat; *p && nested >= 0 && p <= endp; p++)
7791 {
7792 switch (*p)
7793 {
7794 case '*':
7795 reg_pat[i++] = '.';
7796 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +00007797 while (p[1] == '*') /* "**" matches like "*" */
7798 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00007799 break;
7800 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007801 case '~':
7802 reg_pat[i++] = '\\';
7803 reg_pat[i++] = *p;
7804 break;
7805 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +00007806 reg_pat[i++] = '.';
7807 break;
7808 case '\\':
7809 if (p[1] == NUL)
7810 break;
7811#ifdef BACKSLASH_IN_FILENAME
7812 if (!no_bslash)
7813 {
7814 /* translate:
7815 * "\x" to "\\x" e.g., "dir\file"
7816 * "\*" to "\\.*" e.g., "dir\*.c"
7817 * "\?" to "\\." e.g., "dir\??.c"
7818 * "\+" to "\+" e.g., "fileX\+.c"
7819 */
7820 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
7821 && p[1] != '+')
7822 {
7823 reg_pat[i++] = '[';
7824 reg_pat[i++] = '\\';
7825 reg_pat[i++] = '/';
7826 reg_pat[i++] = ']';
7827 if (allow_dirs != NULL)
7828 *allow_dirs = TRUE;
7829 break;
7830 }
7831 }
7832#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +02007833 /* Undo escaping from ExpandEscape():
7834 * foo\?bar -> foo?bar
7835 * foo\%bar -> foo%bar
7836 * foo\,bar -> foo,bar
7837 * foo\ bar -> foo bar
7838 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +02007839 * regexp.
7840 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +02007841 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +02007842 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00007843 if (*++p == '?'
7844#ifdef BACKSLASH_IN_FILENAME
7845 && no_bslash
7846#endif
7847 )
7848 reg_pat[i++] = '?';
7849 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +02007850 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +02007851 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +02007852 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +02007853 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
7854 {
7855 reg_pat[i++] = '\\';
7856 reg_pat[i++] = '{';
7857 p += 2;
7858 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00007859 else
7860 {
7861 if (allow_dirs != NULL && vim_ispathsep(*p)
7862#ifdef BACKSLASH_IN_FILENAME
7863 && (!no_bslash || *p != '\\')
7864#endif
7865 )
7866 *allow_dirs = TRUE;
7867 reg_pat[i++] = '\\';
7868 reg_pat[i++] = *p;
7869 }
7870 break;
7871#ifdef BACKSLASH_IN_FILENAME
7872 case '/':
7873 reg_pat[i++] = '[';
7874 reg_pat[i++] = '\\';
7875 reg_pat[i++] = '/';
7876 reg_pat[i++] = ']';
7877 if (allow_dirs != NULL)
7878 *allow_dirs = TRUE;
7879 break;
7880#endif
7881 case '{':
7882 reg_pat[i++] = '\\';
7883 reg_pat[i++] = '(';
7884 nested++;
7885 break;
7886 case '}':
7887 reg_pat[i++] = '\\';
7888 reg_pat[i++] = ')';
7889 --nested;
7890 break;
7891 case ',':
7892 if (nested)
7893 {
7894 reg_pat[i++] = '\\';
7895 reg_pat[i++] = '|';
7896 }
7897 else
7898 reg_pat[i++] = ',';
7899 break;
7900 default:
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00007901 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00007902 reg_pat[i++] = *p++;
Bram Moolenaar13505972019-01-24 15:04:48 +01007903 else if (allow_dirs != NULL && vim_ispathsep(*p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00007904 *allow_dirs = TRUE;
7905 reg_pat[i++] = *p;
7906 break;
7907 }
7908 }
7909 if (add_dollar)
7910 reg_pat[i++] = '$';
7911 reg_pat[i] = NUL;
7912 if (nested != 0)
7913 {
7914 if (nested < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007915 emsg(_("E219: Missing {."));
Bram Moolenaar071d4272004-06-13 20:20:40 +00007916 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01007917 emsg(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +01007918 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00007919 }
7920 return reg_pat;
7921}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01007922
7923#if defined(EINTR) || defined(PROTO)
7924/*
7925 * Version of read() that retries when interrupted by EINTR (possibly
7926 * by a SIGWINCH).
7927 */
7928 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007929read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01007930{
7931 long ret;
7932
7933 for (;;)
7934 {
7935 ret = vim_read(fd, buf, bufsize);
7936 if (ret >= 0 || errno != EINTR)
7937 break;
7938 }
7939 return ret;
7940}
7941
7942/*
7943 * Version of write() that retries when interrupted by EINTR (possibly
7944 * by a SIGWINCH).
7945 */
7946 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01007947write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01007948{
7949 long ret = 0;
7950 long wlen;
7951
7952 /* Repeat the write() so long it didn't fail, other than being interrupted
7953 * by a signal. */
7954 while (ret < (long)bufsize)
7955 {
Bram Moolenaar9c263032010-12-17 18:06:06 +01007956 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01007957 if (wlen < 0)
7958 {
7959 if (errno != EINTR)
7960 break;
7961 }
7962 else
7963 ret += wlen;
7964 }
7965 return ret;
7966}
7967#endif