blob: e05dfa3a5ddc88936934adcf3a43beec3b925013 [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
Christian Brabandtf573c6e2021-06-20 14:02:16 +020016#ifdef FEAT_SODIUM
17# include <sodium.h>
18#endif
19
Bram Moolenaare3f915d2020-07-14 23:02:44 +020020#if defined(__TANDEM)
Bram Moolenaar217e1b82019-12-01 21:41:28 +010021# include <limits.h> // for SSIZE_MAX
Bram Moolenaar071d4272004-06-13 20:20:40 +000022#endif
Bram Moolenaar82c38fe2021-01-04 10:47:26 +010023#if (defined(UNIX) || defined(VMS)) && defined(FEAT_EVAL)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +020024# include <pwd.h>
25# include <grp.h>
26#endif
Bram Moolenaar82c38fe2021-01-04 10:47:26 +010027#if defined(VMS) && defined(HAVE_XOS_R_H)
28# include <x11/xos_r.h>
29#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000030
Bram Moolenaar217e1b82019-12-01 21:41:28 +010031// Is there any system that doesn't have access()?
Bram Moolenaar9372a112005-12-06 19:59:18 +000032#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000033
Bram Moolenaar9d8bfae2020-09-02 21:21:35 +020034#if defined(__hpux) && !defined(HAVE_DIRFD)
35# define dirfd(x) ((x)->__dd_fd)
36# define HAVE_DIRFD
37#endif
38
Bram Moolenaarf077db22019-08-13 00:18:24 +020039static char_u *next_fenc(char_u **pp, int *alloced);
Bram Moolenaar13505972019-01-24 15:04:48 +010040#ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010041static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000042#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000043#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020044static 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 +000045#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010046static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010047static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000048static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
Bram Moolenaarb0bf8582005-12-13 20:02:15 +000049
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +020050#ifdef FEAT_EVAL
51static int readdirex_sort;
52#endif
53
Bram Moolenaar473952e2019-09-28 16:30:04 +020054 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010055filemess(
56 buf_T *buf,
57 char_u *name,
58 char_u *s,
59 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +000060{
61 int msg_scroll_save;
Bram Moolenaar473952e2019-09-28 16:30:04 +020062 int prev_msg_col = msg_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +000063
64 if (msg_silent != 0)
65 return;
Bram Moolenaar217e1b82019-12-01 21:41:28 +010066 msg_add_fname(buf, name); // put file name in IObuff with quotes
Bram Moolenaar6378b212020-06-29 21:32:06 +020067
Bram Moolenaar217e1b82019-12-01 21:41:28 +010068 // If it's extremely long, truncate it.
Bram Moolenaar6378b212020-06-29 21:32:06 +020069 if (STRLEN(IObuff) > IOSIZE - 100)
70 IObuff[IOSIZE - 100] = NUL;
71
72 // Avoid an over-long translation to cause trouble.
73 STRNCAT(IObuff, s, 99);
74
Bram Moolenaar071d4272004-06-13 20:20:40 +000075 /*
76 * For the first message may have to start a new line.
77 * For further ones overwrite the previous one, reset msg_scroll before
78 * calling filemess().
79 */
80 msg_scroll_save = msg_scroll;
81 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
82 msg_scroll = FALSE;
Bram Moolenaar217e1b82019-12-01 21:41:28 +010083 if (!msg_scroll) // wait a bit when overwriting an error msg
Bram Moolenaar071d4272004-06-13 20:20:40 +000084 check_for_delay(FALSE);
85 msg_start();
Bram Moolenaar473952e2019-09-28 16:30:04 +020086 if (prev_msg_col != 0 && msg_col == 0)
87 msg_putchar('\r'); // overwrite any previous message.
Bram Moolenaar071d4272004-06-13 20:20:40 +000088 msg_scroll = msg_scroll_save;
89 msg_scrolled_ign = TRUE;
Bram Moolenaar217e1b82019-12-01 21:41:28 +010090 // may truncate the message to avoid a hit-return prompt
Bram Moolenaar071d4272004-06-13 20:20:40 +000091 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
92 msg_clr_eos();
93 out_flush();
94 msg_scrolled_ign = FALSE;
95}
96
97/*
98 * Read lines from file "fname" into the buffer after line "from".
99 *
100 * 1. We allocate blocks with lalloc, as big as possible.
101 * 2. Each block is filled with characters from the file with a single read().
102 * 3. The lines are inserted in the buffer with ml_append().
103 *
104 * (caller must check that fname != NULL, unless READ_STDIN is used)
105 *
106 * "lines_to_skip" is the number of lines that must be skipped
107 * "lines_to_read" is the number of lines that are appended
108 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
109 *
110 * flags:
111 * READ_NEW starting to edit a new buffer
112 * READ_FILTER reading filter output
113 * READ_STDIN read from stdin instead of a file
114 * READ_BUFFER read from curbuf instead of a file (converting after reading
115 * stdin)
116 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +0200117 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200118 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000119 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100120 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +0000121 */
122 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100123readfile(
124 char_u *fname,
125 char_u *sfname,
126 linenr_T from,
127 linenr_T lines_to_skip,
128 linenr_T lines_to_read,
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100129 exarg_T *eap, // can be NULL!
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +0100130 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000131{
132 int fd = 0;
133 int newfile = (flags & READ_NEW);
134 int check_readonly;
135 int filtering = (flags & READ_FILTER);
136 int read_stdin = (flags & READ_STDIN);
137 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200138 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000139 int set_options = newfile || read_buffer
140 || (eap != NULL && eap->read_edit);
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100141 linenr_T read_buf_lnum = 1; // next line to read from curbuf
142 colnr_T read_buf_col = 0; // next char to read from this line
Bram Moolenaar071d4272004-06-13 20:20:40 +0000143 char_u c;
144 linenr_T lnum = from;
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100145 char_u *ptr = NULL; // pointer into read buffer
146 char_u *buffer = NULL; // read buffer
147 char_u *new_buffer = NULL; // init to shut up gcc
148 char_u *line_start = NULL; // init to shut up gcc
149 int wasempty; // buffer was empty before reading
Bram Moolenaar071d4272004-06-13 20:20:40 +0000150 colnr_T len;
151 long size = 0;
152 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200153 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154 int skip_read = FALSE;
Christian Brabandtf573c6e2021-06-20 14:02:16 +0200155 off_T filesize_disk = 0; // file size read from disk
156 off_T filesize_count = 0; // counter
Bram Moolenaar071d4272004-06-13 20:20:40 +0000157#ifdef FEAT_CRYPT
158 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200159 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000160#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200161#ifdef FEAT_PERSISTENT_UNDO
162 context_sha256_T sha_ctx;
163 int read_undo_file = FALSE;
164#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100165 int split = 0; // number of split lines
166#define UNKNOWN 0x0fffffff // file size is unknown
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167 linenr_T linecnt;
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100168 int error = FALSE; // errors encountered
169 int ff_error = EOL_UNKNOWN; // file format with errors
170 long linerest = 0; // remaining chars in line
Bram Moolenaar071d4272004-06-13 20:20:40 +0000171#ifdef UNIX
172 int perm = 0;
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100173 int swap_mode = -1; // protection bits for swap file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000174#else
175 int perm;
176#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100177 int fileformat = 0; // end-of-line format
Bram Moolenaar071d4272004-06-13 20:20:40 +0000178 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200179 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180 int file_readonly;
181 linenr_T skip_count = 0;
182 linenr_T read_count = 0;
183 int msg_save = msg_scroll;
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100184 linenr_T read_no_eol_lnum = 0; // non-zero lnum when last line of
185 // last read was missing the eol
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100186 int try_mac;
187 int try_dos;
188 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000189 int file_rewind = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000190 int can_retry;
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100191 linenr_T conv_error = 0; // line nr with conversion error
192 linenr_T illegal_byte = 0; // line nr with illegal byte
193 int keep_dest_enc = FALSE; // don't retry when char doesn't fit
194 // in destination encoding
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000195 int bad_char_behavior = BAD_REPLACE;
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100196 // BAD_KEEP, BAD_DROP or character to
197 // replace with
198 char_u *tmpname = NULL; // name of 'charconvert' output file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000199 int fio_flags = 0;
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100200 char_u *fenc; // fileencoding to use
201 int fenc_alloced; // fenc_next is in allocated memory
202 char_u *fenc_next = NULL; // next item in 'fencs' or NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000203 int advance_fenc = FALSE;
204 long real_size = 0;
Bram Moolenaar13505972019-01-24 15:04:48 +0100205#ifdef USE_ICONV
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100206 iconv_t iconv_fd = (iconv_t)-1; // descriptor for iconv() or -1
Bram Moolenaar13505972019-01-24 15:04:48 +0100207# ifdef FEAT_EVAL
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100208 int did_iconv = FALSE; // TRUE when iconv() failed and trying
209 // 'charconvert' next
Bram Moolenaar071d4272004-06-13 20:20:40 +0000210# endif
Bram Moolenaar13505972019-01-24 15:04:48 +0100211#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100212 int converted = FALSE; // TRUE if conversion done
213 int notconverted = FALSE; // TRUE if conversion wanted but it
214 // wasn't possible
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215 char_u conv_rest[CONV_RESTLEN];
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100216 int conv_restlen = 0; // nr of bytes in conv_rest[]
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100217 pos_T orig_start;
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200218 buf_T *old_curbuf;
219 char_u *old_b_ffname;
220 char_u *old_b_fname;
221 int using_b_ffname;
222 int using_b_fname;
Bram Moolenaarc8fe6452020-10-03 17:04:37 +0200223 static char *msg_is_a_directory = N_("is a directory");
Christian Brabandtf573c6e2021-06-20 14:02:16 +0200224 int eof;
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200225
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100226 au_did_filetype = FALSE; // reset before triggering any autocommands
Bram Moolenaarc3691332016-04-20 12:49:49 +0200227
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100228 curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read
Bram Moolenaar071d4272004-06-13 20:20:40 +0000229
230 /*
231 * If there is no file name yet, use the one for the read file.
232 * BF_NOTEDITED is set to reflect this.
233 * Don't do this for a read from a filter.
234 * Only do this when 'cpoptions' contains the 'f' flag.
235 */
236 if (curbuf->b_ffname == NULL
237 && !filtering
238 && fname != NULL
239 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
240 && !(flags & READ_DUMMY))
241 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000242 if (set_rw_fname(fname, sfname) == FAIL)
243 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000244 }
245
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100246 // Remember the initial values of curbuf, curbuf->b_ffname and
247 // curbuf->b_fname to detect whether they are altered as a result of
248 // executing nasty autocommands. Also check if "fname" and "sfname"
249 // point to one of these values.
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200250 old_curbuf = curbuf;
251 old_b_ffname = curbuf->b_ffname;
252 old_b_fname = curbuf->b_fname;
253 using_b_ffname = (fname == curbuf->b_ffname)
254 || (sfname == curbuf->b_ffname);
255 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200256
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100257 // After reading a file the cursor line changes but we don't want to
258 // display the line.
Bram Moolenaardf177f62005-02-22 08:39:57 +0000259 ex_no_reprint = TRUE;
260
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100261 // don't display the file info for another buffer now
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000262 need_fileinfo = FALSE;
263
Bram Moolenaar071d4272004-06-13 20:20:40 +0000264 /*
265 * For Unix: Use the short file name whenever possible.
266 * Avoids problems with networks and when directory names are changed.
267 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
268 * another directory, which we don't detect.
269 */
270 if (sfname == NULL)
271 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200272#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000273 fname = sfname;
274#endif
275
Bram Moolenaar071d4272004-06-13 20:20:40 +0000276 /*
277 * The BufReadCmd and FileReadCmd events intercept the reading process by
278 * executing the associated commands instead.
279 */
280 if (!filtering && !read_stdin && !read_buffer)
281 {
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100282 orig_start = curbuf->b_op_start;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000283
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100284 // Set '[ mark to the line above where the lines go (line 1 if zero).
Bram Moolenaar071d4272004-06-13 20:20:40 +0000285 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
286 curbuf->b_op_start.col = 0;
287
288 if (newfile)
289 {
290 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
291 FALSE, curbuf, eap))
Bram Moolenaar0fff4412020-03-29 16:06:29 +0200292 {
293 int status = OK;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294#ifdef FEAT_EVAL
Bram Moolenaar0fff4412020-03-29 16:06:29 +0200295 if (aborting())
296 status = FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000297#endif
Bram Moolenaar0fff4412020-03-29 16:06:29 +0200298 // The BufReadCmd code usually uses ":read" to get the text and
299 // perhaps ":file" to change the buffer name. But we should
300 // consider this to work like ":edit", thus reset the
301 // BF_NOTEDITED flag. Then ":write" will work to overwrite the
302 // same file.
303 if (status == OK)
304 curbuf->b_flags &= ~BF_NOTEDITED;
305 return status;
306 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000307 }
308 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
309 FALSE, NULL, eap))
310#ifdef FEAT_EVAL
311 return aborting() ? FAIL : OK;
312#else
313 return OK;
314#endif
315
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100316 curbuf->b_op_start = orig_start;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000317 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000318
319 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100320 msg_scroll = FALSE; // overwrite previous file message
Bram Moolenaar071d4272004-06-13 20:20:40 +0000321 else
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100322 msg_scroll = TRUE; // don't overwrite previous file message
Bram Moolenaar071d4272004-06-13 20:20:40 +0000323
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000324 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000325 {
Bram Moolenaarc8fe6452020-10-03 17:04:37 +0200326 size_t namelen = STRLEN(fname);
327
328 // If the name is too long we might crash further on, quit here.
329 if (namelen >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000330 {
331 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
332 msg_end();
333 msg_scroll = msg_save;
334 return FAIL;
335 }
Bram Moolenaarc8fe6452020-10-03 17:04:37 +0200336
337 // If the name ends in a path separator, we can't open it. Check here,
338 // because reading the file may actually work, but then creating the
339 // swap file may destroy it! Reported on MS-DOS and Win 95.
340 if (after_pathsep(fname, fname + namelen))
341 {
342 filemess(curbuf, fname, (char_u *)_(msg_is_a_directory), 0);
343 msg_end();
344 msg_scroll = msg_save;
345 return FAIL;
346 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000347 }
348
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200349 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000350 {
Bram Moolenaar82c38fe2021-01-04 10:47:26 +0100351#if defined(UNIX) || defined(VMS)
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200352 /*
353 * On Unix it is possible to read a directory, so we have to
354 * check for it before the mch_open().
355 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000356 perm = mch_getperm(fname);
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100357 if (perm >= 0 && !S_ISREG(perm) // not a regular file ...
358 && !S_ISFIFO(perm) // ... or fifo
359 && !S_ISSOCK(perm) // ... or socket
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000360# ifdef OPEN_CHR_FILES
361 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100362 // ... or a character special file named /dev/fd/<n>
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000363# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000364 )
365 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100366 int retval = FAIL;
367
Bram Moolenaar071d4272004-06-13 20:20:40 +0000368 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100369 {
Bram Moolenaarc8fe6452020-10-03 17:04:37 +0200370 filemess(curbuf, fname, (char_u *)_(msg_is_a_directory), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100371 retval = NOTDONE;
372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000373 else
374 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
375 msg_end();
376 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100377 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000378 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200379#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100380#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000381 /*
382 * MS-Windows allows opening a device, but we will probably get stuck
383 * trying to read it.
384 */
385 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
386 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000387 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000388 msg_end();
389 msg_scroll = msg_save;
390 return FAIL;
391 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000392#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200393 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000394
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100395 // Set default or forced 'fileformat' and 'binary'.
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200396 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000397
398 /*
399 * When opening a new file we take the readonly flag from the file.
400 * Default is r/w, can be set to r/o below.
401 * Don't reset it when in readonly mode
402 * Only set/reset b_p_ro when BF_CHECK_RO is set.
403 */
404 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000405 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000406 curbuf->b_p_ro = FALSE;
407
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200408 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000409 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100410 // Remember time of file.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000411 if (mch_stat((char *)fname, &st) >= 0)
412 {
413 buf_store_time(curbuf, &st, fname);
414 curbuf->b_mtime_read = curbuf->b_mtime;
Christian Brabandtf573c6e2021-06-20 14:02:16 +0200415 filesize_disk = st.st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000416#ifdef UNIX
417 /*
418 * Use the protection bits of the original file for the swap file.
419 * This makes it possible for others to read the name of the
420 * edited file from the swapfile, but only if they can read the
421 * edited file.
422 * Remove the "write" and "execute" bits for group and others
423 * (they must not write the swapfile).
424 * Add the "read" and "write" bits for the user, otherwise we may
425 * not be able to write to the file ourselves.
426 * Setting the bits is done below, after creating the swap file.
427 */
428 swap_mode = (st.st_mode & 0644) | 0600;
429#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000430#ifdef VMS
431 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000432 curbuf->b_fab_rat = st.st_fab_rat;
433 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000434#endif
435 }
436 else
437 {
438 curbuf->b_mtime = 0;
439 curbuf->b_mtime_read = 0;
440 curbuf->b_orig_size = 0;
441 curbuf->b_orig_mode = 0;
442 }
443
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100444 // Reset the "new file" flag. It will be set again below when the
445 // file doesn't exist.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000446 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
447 }
448
449/*
450 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100451 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000452 */
453 file_readonly = FALSE;
454 if (read_stdin)
455 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100456#if defined(MSWIN)
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100457 // Force binary I/O on stdin to avoid CR-LF -> LF conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000458 setmode(0, O_BINARY);
459#endif
460 }
461 else if (!read_buffer)
462 {
463#ifdef USE_MCH_ACCESS
464 if (
465# ifdef UNIX
466 !(perm & 0222) ||
467# endif
468 mch_access((char *)fname, W_OK))
469 file_readonly = TRUE;
470 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
471#else
472 if (!newfile
473 || readonlymode
474 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
475 {
476 file_readonly = TRUE;
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100477 // try to open ro
Bram Moolenaar071d4272004-06-13 20:20:40 +0000478 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
479 }
480#endif
481 }
482
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100483 if (fd < 0) // cannot open at all
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 {
485#ifndef UNIX
486 int isdir_f;
487#endif
488 msg_scroll = msg_save;
489#ifndef UNIX
490 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100491 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000492 */
493 isdir_f = (mch_isdir(fname));
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100494 perm = mch_getperm(fname); // check if the file exists
Bram Moolenaar071d4272004-06-13 20:20:40 +0000495 if (isdir_f)
496 {
Bram Moolenaarc8fe6452020-10-03 17:04:37 +0200497 filemess(curbuf, sfname, (char_u *)_(msg_is_a_directory), 0);
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100498 curbuf->b_p_ro = TRUE; // must use "w!" now
Bram Moolenaar071d4272004-06-13 20:20:40 +0000499 }
500 else
501#endif
502 if (newfile)
503 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200504 if (perm < 0
505#ifdef ENOENT
506 && errno == ENOENT
507#endif
508 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 {
510 /*
511 * Set the 'new-file' flag, so that when the file has
512 * been created by someone else, a ":w" will complain.
513 */
514 curbuf->b_flags |= BF_NEW;
515
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100516 // Create a swap file now, so that other Vims are warned
517 // that we are editing this file. Don't do this for a
518 // "nofile" or "nowrite" buffer type.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000519#ifdef FEAT_QUICKFIX
520 if (!bt_dontwrite(curbuf))
521#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000522 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000523 check_need_swap(newfile);
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100524 // SwapExists autocommand may mess things up
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000525 if (curbuf != old_curbuf
526 || (using_b_ffname
527 && (old_b_ffname != curbuf->b_ffname))
528 || (using_b_fname
529 && (old_b_fname != curbuf->b_fname)))
530 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100531 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000532 return FAIL;
533 }
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000534 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000535 if (dir_of_file_exists(fname))
Bram Moolenaar722e5052020-06-12 22:31:00 +0200536 filemess(curbuf, sfname,
537 (char_u *)new_file_message(), 0);
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000538 else
539 filemess(curbuf, sfname,
540 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000541#ifdef FEAT_VIMINFO
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100542 // Even though this is a new file, it might have been
543 // edited before and deleted. Get the old marks.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000544 check_marks_read();
545#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100546 // Set forced 'fileencoding'.
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200547 if (eap != NULL)
548 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000549 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
550 FALSE, curbuf, eap);
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100551 // remember the current fileformat
Bram Moolenaar071d4272004-06-13 20:20:40 +0000552 save_file_ff(curbuf);
553
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +0100554#if defined(FEAT_EVAL)
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100555 if (aborting()) // autocmds may abort script processing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000556 return FAIL;
557#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100558 return OK; // a new file is not an error
Bram Moolenaar071d4272004-06-13 20:20:40 +0000559 }
560 else
561 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000562 filemess(curbuf, sfname, (char_u *)(
563# ifdef EFBIG
564 (errno == EFBIG) ? _("[File too big]") :
565# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200566# ifdef EOVERFLOW
567 (errno == EOVERFLOW) ? _("[File too big]") :
568# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000569 _("[Permission Denied]")), 0);
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100570 curbuf->b_p_ro = TRUE; // must use "w!" now
Bram Moolenaar071d4272004-06-13 20:20:40 +0000571 }
572 }
573
574 return FAIL;
575 }
576
577 /*
578 * Only set the 'ro' flag for readonly files the first time they are
579 * loaded. Help files always get readonly mode
580 */
581 if ((check_readonly && file_readonly) || curbuf->b_help)
582 curbuf->b_p_ro = TRUE;
583
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000584 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000585 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100586 // Don't change 'eol' if reading from buffer as it will already be
587 // correctly set when reading stdin.
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000588 if (!read_buffer)
589 {
590 curbuf->b_p_eol = TRUE;
591 curbuf->b_start_eol = TRUE;
592 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000593 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000594 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000595 }
596
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100597 // Create a swap file now, so that other Vims are warned that we are
598 // editing this file.
599 // Don't do this for a "nofile" or "nowrite" buffer type.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000600#ifdef FEAT_QUICKFIX
601 if (!bt_dontwrite(curbuf))
602#endif
603 {
604 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000605 if (!read_stdin && (curbuf != old_curbuf
606 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
607 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
608 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100609 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000610 if (!read_buffer)
611 close(fd);
612 return FAIL;
613 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614#ifdef UNIX
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100615 // Set swap file protection bits after creating it.
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000616 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
617 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100618 {
619 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
620
621 /*
622 * If the group-read bit is set but not the world-read bit, then
623 * the group must be equal to the group of the original file. If
624 * we can't make that happen then reset the group-read bit. This
625 * avoids making the swap file readable to more users when the
626 * primary group of the user is too permissive.
627 */
628 if ((swap_mode & 044) == 040)
629 {
630 stat_T swap_st;
631
632 if (mch_stat((char *)swap_fname, &swap_st) >= 0
633 && st.st_gid != swap_st.st_gid
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200634# ifdef HAVE_FCHOWN
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100635 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200636 == -1
Bram Moolenaar1f131ae2018-05-21 13:39:40 +0200637# endif
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200638 )
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100639 swap_mode &= 0600;
640 }
641
642 (void)mch_setperm(swap_fname, (long)swap_mode);
643 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000644#endif
645 }
646
Bram Moolenaar67cf86b2019-04-28 22:25:38 +0200647 // If "Quit" selected at ATTENTION dialog, don't load the file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000648 if (swap_exists_action == SEA_QUIT)
649 {
650 if (!read_buffer && !read_stdin)
651 close(fd);
652 return FAIL;
653 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000654
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100655 ++no_wait_return; // don't wait for return yet
Bram Moolenaar071d4272004-06-13 20:20:40 +0000656
657 /*
658 * Set '[ mark to the line above where the lines go (line 1 if zero).
659 */
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100660 orig_start = curbuf->b_op_start;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000661 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
662 curbuf->b_op_start.col = 0;
663
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100664 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
665 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
666 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
667
Bram Moolenaar071d4272004-06-13 20:20:40 +0000668 if (!read_buffer)
669 {
670 int m = msg_scroll;
671 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000672
673 /*
674 * The file must be closed again, the autocommands may want to change
675 * the file before reading it.
676 */
677 if (!read_stdin)
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100678 close(fd); // ignore errors
Bram Moolenaar071d4272004-06-13 20:20:40 +0000679
680 /*
681 * The output from the autocommands should not overwrite anything and
682 * should not be overwritten: Set msg_scroll, restore its value if no
683 * output was done.
684 */
685 msg_scroll = TRUE;
686 if (filtering)
687 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
688 FALSE, curbuf, eap);
689 else if (read_stdin)
690 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
691 FALSE, curbuf, eap);
692 else if (newfile)
693 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
694 FALSE, curbuf, eap);
695 else
696 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
697 FALSE, NULL, eap);
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100698 // autocommands may have changed it
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100699 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
700 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
701 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100702 curbuf->b_op_start = orig_start;
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100703
Bram Moolenaar071d4272004-06-13 20:20:40 +0000704 if (msg_scrolled == n)
705 msg_scroll = m;
706
707#ifdef FEAT_EVAL
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100708 if (aborting()) // autocmds may abort script processing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000709 {
710 --no_wait_return;
711 msg_scroll = msg_save;
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100712 curbuf->b_p_ro = TRUE; // must use "w!" now
Bram Moolenaar071d4272004-06-13 20:20:40 +0000713 return FAIL;
714 }
715#endif
716 /*
717 * Don't allow the autocommands to change the current buffer.
718 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000719 *
720 * Don't allow the autocommands to change the buffer name either
721 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000722 */
723 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000724 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
725 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000726 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
727 {
728 --no_wait_return;
729 msg_scroll = msg_save;
730 if (fd < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100731 emsg(_("E200: *ReadPre autocommands made the file unreadable"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000732 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100733 emsg(_("E201: *ReadPre autocommands must not change current buffer"));
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100734 curbuf->b_p_ro = TRUE; // must use "w!" now
Bram Moolenaar071d4272004-06-13 20:20:40 +0000735 return FAIL;
736 }
737 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000738
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100739 // Autocommands may add lines to the file, need to check if it is empty
Bram Moolenaar071d4272004-06-13 20:20:40 +0000740 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
741
742 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
743 {
744 /*
745 * Show the user that we are busy reading the input. Sometimes this
746 * may take a while. When reading from stdin another program may
747 * still be running, don't move the cursor to the last line, unless
748 * always using the GUI.
749 */
750 if (read_stdin)
751 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100752 if (!is_not_a_term())
753 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000754#ifndef ALWAYS_USE_GUI
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200755# ifdef VIMDLL
756 if (!gui.in_use)
757# endif
758 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000759#endif
760#ifdef FEAT_GUI
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100761 // Also write a message in the GUI window, if there is one.
Bram Moolenaar234d1622017-11-18 14:55:23 +0100762 if (gui.in_use && !gui.dying && !gui.starting)
763 {
764 p = (char_u *)_("Reading from stdin...");
765 gui_write(p, (int)STRLEN(p));
766 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000767#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100768 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000769 }
770 else if (!read_buffer)
771 filemess(curbuf, sfname, (char_u *)"", 0);
772 }
773
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100774 msg_scroll = FALSE; // overwrite the file message
Bram Moolenaar071d4272004-06-13 20:20:40 +0000775
776 /*
777 * Set linecnt now, before the "retry" caused by a wrong guess for
778 * fileformat, and after the autocommands, which may change them.
779 */
780 linecnt = curbuf->b_ml.ml_line_count;
781
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100782 // "++bad=" argument.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000783 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000784 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000785 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000786 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000787 curbuf->b_bad_char = eap->bad_char;
788 }
789 else
790 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000791
Bram Moolenaar071d4272004-06-13 20:20:40 +0000792 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000793 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000794 */
795 if (eap != NULL && eap->force_enc != 0)
796 {
797 fenc = enc_canonize(eap->cmd + eap->force_enc);
798 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000799 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000800 }
801 else if (curbuf->b_p_bin)
802 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100803 fenc = (char_u *)""; // binary: don't convert
Bram Moolenaar071d4272004-06-13 20:20:40 +0000804 fenc_alloced = FALSE;
805 }
806 else if (curbuf->b_help)
807 {
808 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000809 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000810
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100811 // Help files are either utf-8 or latin1. Try utf-8 first, if this
812 // fails it must be latin1.
813 // Always do this when 'encoding' is "utf-8". Otherwise only do
814 // this when needed to avoid [converted] remarks all the time.
815 // It is needed when the first line contains non-ASCII characters.
816 // That is only in *.??x files.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817 fenc = (char_u *)"latin1";
818 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000819 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000820 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000821 fc = fname[STRLEN(fname) - 1];
822 if (TOLOWER_ASC(fc) == 'x')
823 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100824 // Read the first line (and a bit more). Immediately rewind to
825 // the start of the file. If the read() fails "len" is -1.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100826 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200827 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000828 for (p = firstline; p < firstline + len; ++p)
829 if (*p >= 0x80)
830 {
831 c = TRUE;
832 break;
833 }
834 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000835 }
836
837 if (c)
838 {
839 fenc_next = fenc;
840 fenc = (char_u *)"utf-8";
841
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100842 // When the file is utf-8 but a character doesn't fit in
843 // 'encoding' don't retry. In help text editing utf-8 bytes
844 // doesn't make sense.
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000845 if (!enc_utf8)
846 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000847 }
848 fenc_alloced = FALSE;
849 }
850 else if (*p_fencs == NUL)
851 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100852 fenc = curbuf->b_p_fenc; // use format from buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +0000853 fenc_alloced = FALSE;
854 }
855 else
856 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100857 fenc_next = p_fencs; // try items in 'fileencodings'
Bram Moolenaarf077db22019-08-13 00:18:24 +0200858 fenc = next_fenc(&fenc_next, &fenc_alloced);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000859 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000860
861 /*
862 * Jump back here to retry reading the file in different ways.
863 * Reasons to retry:
864 * - encoding conversion failed: try another one from "fenc_next"
865 * - BOM detected and fenc was set, need to setup conversion
866 * - "fileformat" check failed: try another
867 *
868 * Variables set for special retry actions:
869 * "file_rewind" Rewind the file to start reading it again.
870 * "advance_fenc" Advance "fenc" using "fenc_next".
871 * "skip_read" Re-use already read bytes (BOM detected).
872 * "did_iconv" iconv() conversion failed, try 'charconvert'.
873 * "keep_fileformat" Don't reset "fileformat".
874 *
875 * Other status indicators:
876 * "tmpname" When != NULL did conversion with 'charconvert'.
877 * Output file has to be deleted afterwards.
878 * "iconv_fd" When != -1 did conversion with iconv().
879 */
880retry:
881
882 if (file_rewind)
883 {
884 if (read_buffer)
885 {
886 read_buf_lnum = 1;
887 read_buf_col = 0;
888 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200889 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000890 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100891 // Can't rewind the file, give up.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000892 error = TRUE;
893 goto failed;
894 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100895 // Delete the previously read lines.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000896 while (lnum > from)
Bram Moolenaarca70c072020-05-30 20:30:46 +0200897 ml_delete(lnum--);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000898 file_rewind = FALSE;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000899 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000900 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000901 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000902 curbuf->b_start_bomb = FALSE;
903 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000904 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000905 }
906
907 /*
908 * When retrying with another "fenc" and the first time "fileformat"
909 * will be reset.
910 */
911 if (keep_fileformat)
912 keep_fileformat = FALSE;
913 else
914 {
915 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000916 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000917 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000918 try_unix = try_dos = try_mac = FALSE;
919 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920 else if (curbuf->b_p_bin)
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100921 fileformat = EOL_UNIX; // binary: use Unix format
Bram Moolenaar071d4272004-06-13 20:20:40 +0000922 else if (*p_ffs == NUL)
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100923 fileformat = get_fileformat(curbuf);// use format from buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +0000924 else
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100925 fileformat = EOL_UNKNOWN; // detect from file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000926 }
927
Bram Moolenaar13505972019-01-24 15:04:48 +0100928#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000929 if (iconv_fd != (iconv_t)-1)
930 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100931 // aborted conversion with iconv(), close the descriptor
Bram Moolenaar071d4272004-06-13 20:20:40 +0000932 iconv_close(iconv_fd);
933 iconv_fd = (iconv_t)-1;
934 }
Bram Moolenaar13505972019-01-24 15:04:48 +0100935#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000936
937 if (advance_fenc)
938 {
939 /*
940 * Try the next entry in 'fileencodings'.
941 */
942 advance_fenc = FALSE;
943
944 if (eap != NULL && eap->force_enc != 0)
945 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100946 // Conversion given with "++cc=" wasn't possible, read
947 // without conversion.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000948 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000949 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000950 if (fenc_alloced)
951 vim_free(fenc);
952 fenc = (char_u *)"";
953 fenc_alloced = FALSE;
954 }
955 else
956 {
957 if (fenc_alloced)
958 vim_free(fenc);
959 if (fenc_next != NULL)
960 {
Bram Moolenaarf077db22019-08-13 00:18:24 +0200961 fenc = next_fenc(&fenc_next, &fenc_alloced);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000962 }
963 else
964 {
965 fenc = (char_u *)"";
966 fenc_alloced = FALSE;
967 }
968 }
969 if (tmpname != NULL)
970 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100971 mch_remove(tmpname); // delete converted file
Bram Moolenaard23a8232018-02-10 18:45:26 +0100972 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000973 }
974 }
975
976 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000977 * Conversion may be required when the encoding of the file is different
978 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000979 */
980 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000981 converted = need_conversion(fenc);
982 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983 {
984
Bram Moolenaar217e1b82019-12-01 21:41:28 +0100985 // "ucs-bom" means we need to check the first bytes of the file
986 // for a BOM.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987 if (STRCMP(fenc, ENC_UCSBOM) == 0)
988 fio_flags = FIO_UCSBOM;
989
990 /*
991 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
992 * done. This is handled below after read(). Prepare the
993 * fio_flags to avoid having to parse the string each time.
994 * Also check for Unicode to Latin1 conversion, because iconv()
995 * appears not to handle this correctly. This works just like
996 * conversion to UTF-8 except how the resulting character is put in
997 * the buffer.
998 */
999 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
1000 fio_flags = get_fio_flags(fenc);
1001
Bram Moolenaar4f974752019-02-17 17:44:42 +01001002#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003 /*
1004 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
1005 * is handled with MultiByteToWideChar().
1006 */
1007 if (fio_flags == 0)
1008 fio_flags = get_win_fio_flags(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01001009#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001010
Bram Moolenaar13505972019-01-24 15:04:48 +01001011#ifdef MACOS_CONVERT
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001012 // Conversion from Apple MacRoman to latin1 or UTF-8
Bram Moolenaar071d4272004-06-13 20:20:40 +00001013 if (fio_flags == 0)
1014 fio_flags = get_mac_fio_flags(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01001015#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016
Bram Moolenaar13505972019-01-24 15:04:48 +01001017#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001018 /*
1019 * Try using iconv() if we can't convert internally.
1020 */
1021 if (fio_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001022# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001023 && !did_iconv
Bram Moolenaar13505972019-01-24 15:04:48 +01001024# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001025 )
1026 iconv_fd = (iconv_t)my_iconv_open(
1027 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01001028#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001029
Bram Moolenaar13505972019-01-24 15:04:48 +01001030#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001031 /*
1032 * Use the 'charconvert' expression when conversion is required
1033 * and we can't do it internally or with iconv().
1034 */
1035 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001036 && !read_fifo
Bram Moolenaar13505972019-01-24 15:04:48 +01001037# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001038 && iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001039# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001040 )
1041 {
Bram Moolenaar13505972019-01-24 15:04:48 +01001042# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001043 did_iconv = FALSE;
Bram Moolenaar13505972019-01-24 15:04:48 +01001044# endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001045 // Skip conversion when it's already done (retry for wrong
1046 // "fileformat").
Bram Moolenaar071d4272004-06-13 20:20:40 +00001047 if (tmpname == NULL)
1048 {
1049 tmpname = readfile_charconvert(fname, fenc, &fd);
1050 if (tmpname == NULL)
1051 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001052 // Conversion failed. Try another one.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001053 advance_fenc = TRUE;
1054 if (fd < 0)
1055 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001056 // Re-opening the original file failed!
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001057 emsg(_("E202: Conversion made file unreadable!"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001058 error = TRUE;
1059 goto failed;
1060 }
1061 goto retry;
1062 }
1063 }
1064 }
1065 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001066#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001067 {
1068 if (fio_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001069#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001070 && iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001071#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072 )
1073 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001074 // Conversion wanted but we can't.
1075 // Try the next conversion in 'fileencodings'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001076 advance_fenc = TRUE;
1077 goto retry;
1078 }
1079 }
1080 }
1081
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001082 // Set "can_retry" when it's possible to rewind the file and try with
1083 // another "fenc" value. It's FALSE when no other "fenc" to try, reading
1084 // stdin or fixed at a specific encoding.
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001085 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001086
1087 if (!skip_read)
1088 {
1089 linerest = 0;
1090 filesize = 0;
Christian Brabandtf573c6e2021-06-20 14:02:16 +02001091 filesize_count = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001092 skip_count = lines_to_skip;
1093 read_count = lines_to_read;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001094 conv_restlen = 0;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001095#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001096 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1097 && curbuf->b_ffname != NULL
1098 && curbuf->b_p_udf
1099 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001100 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001101 && !read_stdin
1102 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001103 if (read_undo_file)
1104 sha256_start(&sha_ctx);
1105#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001106#ifdef FEAT_CRYPT
1107 if (curbuf->b_cryptstate != NULL)
1108 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001109 // Need to free the state, but keep the key, don't want to ask for
1110 // it again.
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001111 crypt_free_state(curbuf->b_cryptstate);
1112 curbuf->b_cryptstate = NULL;
1113 }
1114#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001115 }
1116
1117 while (!error && !got_int)
1118 {
1119 /*
1120 * We allocate as much space for the file as we can get, plus
1121 * space for the old line plus room for one terminating NUL.
1122 * The amount is limited by the fact that read() only can read
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +01001123 * up to max_unsigned characters (and other things).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001124 */
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001125 if (!skip_read)
1126 {
Bram Moolenaar30276f22019-01-24 17:59:39 +01001127#if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001128 size = SSIZE_MAX; // use max I/O size, 52K
Bram Moolenaar30276f22019-01-24 17:59:39 +01001129#else
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001130 // Use buffer >= 64K. Add linerest to double the size if the
1131 // line gets very long, to avoid a lot of copying. But don't
1132 // read more than 1 Mbyte at a time, so we can be interrupted.
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001133 size = 0x10000L + linerest;
1134 if (size > 0x100000L)
1135 size = 0x100000L;
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001136#endif
1137 }
1138
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001139 // Protect against the argument of lalloc() going negative.
Bram Moolenaar30276f22019-01-24 17:59:39 +01001140 if (size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001141 {
1142 ++split;
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001143 *ptr = NL; // split line by inserting a NL
Bram Moolenaar071d4272004-06-13 20:20:40 +00001144 size = 1;
1145 }
1146 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001147 {
1148 if (!skip_read)
1149 {
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001150 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001151 {
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02001152 if ((new_buffer = lalloc(size + linerest + 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001153 FALSE)) != NULL)
1154 break;
1155 }
1156 if (new_buffer == NULL)
1157 {
1158 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1159 error = TRUE;
1160 break;
1161 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001162 if (linerest) // copy characters from the previous buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +00001163 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1164 vim_free(buffer);
1165 buffer = new_buffer;
1166 ptr = buffer + linerest;
1167 line_start = buffer;
1168
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001169 // May need room to translate into.
1170 // For iconv() we don't really know the required space, use a
1171 // factor ICONV_MULT.
1172 // latin1 to utf-8: 1 byte becomes up to 2 bytes
1173 // utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1174 // become up to 4 bytes, size must be multiple of 2
1175 // ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1176 // multiple of 2
1177 // ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1178 // multiple of 4
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001179 real_size = (int)size;
Bram Moolenaar13505972019-01-24 15:04:48 +01001180#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001181 if (iconv_fd != (iconv_t)-1)
1182 size = size / ICONV_MULT;
1183 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001184#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001185 if (fio_flags & FIO_LATIN1)
1186 size = size / 2;
1187 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1188 size = (size * 2 / 3) & ~1;
1189 else if (fio_flags & FIO_UCS4)
1190 size = (size * 2 / 3) & ~3;
1191 else if (fio_flags == FIO_UCSBOM)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001192 size = size / ICONV_MULT; // worst case
Bram Moolenaar4f974752019-02-17 17:44:42 +01001193#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001194 else if (fio_flags & FIO_CODEPAGE)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001195 size = size / ICONV_MULT; // also worst case
Bram Moolenaar13505972019-01-24 15:04:48 +01001196#endif
1197#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001198 else if (fio_flags & FIO_MACROMAN)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001199 size = size / ICONV_MULT; // also worst case
Bram Moolenaar071d4272004-06-13 20:20:40 +00001200#endif
1201
Bram Moolenaar071d4272004-06-13 20:20:40 +00001202 if (conv_restlen > 0)
1203 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001204 // Insert unconverted bytes from previous line.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001205 mch_memmove(ptr, conv_rest, conv_restlen);
1206 ptr += conv_restlen;
1207 size -= conv_restlen;
1208 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001209
1210 if (read_buffer)
1211 {
1212 /*
1213 * Read bytes from curbuf. Used for converting text read
1214 * from stdin.
1215 */
1216 if (read_buf_lnum > from)
1217 size = 0;
1218 else
1219 {
1220 int n, ni;
1221 long tlen;
1222
1223 tlen = 0;
1224 for (;;)
1225 {
1226 p = ml_get(read_buf_lnum) + read_buf_col;
1227 n = (int)STRLEN(p);
1228 if ((int)tlen + n + 1 > size)
1229 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001230 // Filled up to "size", append partial line.
1231 // Change NL to NUL to reverse the effect done
1232 // below.
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001233 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 for (ni = 0; ni < n; ++ni)
1235 {
1236 if (p[ni] == NL)
1237 ptr[tlen++] = NUL;
1238 else
1239 ptr[tlen++] = p[ni];
1240 }
1241 read_buf_col += n;
1242 break;
1243 }
1244 else
1245 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001246 // Append whole line and new-line. Change NL
1247 // to NUL to reverse the effect done below.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001248 for (ni = 0; ni < n; ++ni)
1249 {
1250 if (p[ni] == NL)
1251 ptr[tlen++] = NUL;
1252 else
1253 ptr[tlen++] = p[ni];
1254 }
1255 ptr[tlen++] = NL;
1256 read_buf_col = 0;
1257 if (++read_buf_lnum > from)
1258 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001259 // When the last line didn't have an
1260 // end-of-line don't add it now either.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001261 if (!curbuf->b_p_eol)
1262 --tlen;
1263 size = tlen;
1264 break;
1265 }
1266 }
1267 }
1268 }
1269 }
1270 else
1271 {
1272 /*
1273 * Read bytes from the file.
1274 */
Christian Brabandtf573c6e2021-06-20 14:02:16 +02001275# ifdef FEAT_SODIUM
1276 // Let the crypt layer work with a buffer size of 8192
1277 if (filesize == 0)
1278 // set size to 8K + Sodium Crypt Metadata
1279 size = WRITEBUFSIZE + 36
1280 + crypto_secretstream_xchacha20poly1305_HEADERBYTES
1281 + crypto_secretstream_xchacha20poly1305_ABYTES;
1282
1283 else if (filesize > 0 && (curbuf->b_cryptstate != NULL &&
1284 curbuf->b_cryptstate->method_nr == CRYPT_M_SOD))
1285 size = WRITEBUFSIZE + crypto_secretstream_xchacha20poly1305_ABYTES;
1286# endif
1287 eof = size;
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001288 size = read_eintr(fd, ptr, size);
Christian Brabandtf573c6e2021-06-20 14:02:16 +02001289 filesize_count += size;
1290 // hit end of file
1291 eof = (size < eof || filesize_count == filesize_disk);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001292 }
1293
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001294#ifdef FEAT_CRYPT
1295 /*
1296 * At start of file: Check for magic number of encryption.
1297 */
1298 if (filesize == 0 && size > 0)
1299 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1300 &filesize, newfile, sfname,
1301 &did_ask_for_key);
1302 /*
1303 * Decrypt the read bytes. This is done before checking for
1304 * EOF because the crypt layer may be buffering.
1305 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001306 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1307 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001308 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001309# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001310 if (crypt_works_inplace(curbuf->b_cryptstate))
1311 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001312# endif
Christian Brabandtf573c6e2021-06-20 14:02:16 +02001313 crypt_decode_inplace(curbuf->b_cryptstate, ptr,
1314 size, eof);
Bram Moolenaar987411d2019-01-18 22:48:34 +01001315# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001316 }
1317 else
1318 {
1319 char_u *newptr = NULL;
1320 int decrypted_size;
1321
1322 decrypted_size = crypt_decode_alloc(
Christian Brabandtf573c6e2021-06-20 14:02:16 +02001323 curbuf->b_cryptstate, ptr, size,
1324 &newptr, eof);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001325
Christian Brabandtf573c6e2021-06-20 14:02:16 +02001326 if (decrypted_size < 0)
1327 {
1328 // error message already given
1329 error = TRUE;
1330 vim_free(newptr);
1331 break;
1332 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001333 // If the crypt layer is buffering, not producing
1334 // anything yet, need to read more.
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +02001335 if (decrypted_size == 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001336 continue;
1337
1338 if (linerest == 0)
1339 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001340 // Simple case: reuse returned buffer (may be
1341 // NULL, checked later).
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001342 new_buffer = newptr;
1343 }
1344 else
1345 {
1346 long_u new_size;
1347
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001348 // Need new buffer to add bytes carried over.
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001349 new_size = (long_u)(decrypted_size + linerest + 1);
1350 new_buffer = lalloc(new_size, FALSE);
1351 if (new_buffer == NULL)
1352 {
1353 do_outofmem_msg(new_size);
1354 error = TRUE;
1355 break;
1356 }
1357
1358 mch_memmove(new_buffer, buffer, linerest);
1359 if (newptr != NULL)
1360 mch_memmove(new_buffer + linerest, newptr,
1361 decrypted_size);
Christian Brabandtf573c6e2021-06-20 14:02:16 +02001362 vim_free(newptr);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001363 }
1364
1365 if (new_buffer != NULL)
1366 {
1367 vim_free(buffer);
1368 buffer = new_buffer;
1369 new_buffer = NULL;
1370 line_start = buffer;
1371 ptr = buffer + linerest;
Christian Brabandtf573c6e2021-06-20 14:02:16 +02001372 real_size = size;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001373 }
1374 size = decrypted_size;
1375 }
Bram Moolenaar987411d2019-01-18 22:48:34 +01001376# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001377 }
1378#endif
1379
Bram Moolenaar071d4272004-06-13 20:20:40 +00001380 if (size <= 0)
1381 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001382 if (size < 0) // read error
Bram Moolenaar071d4272004-06-13 20:20:40 +00001383 error = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001384 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001385 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001386 /*
1387 * Reached end-of-file but some trailing bytes could
1388 * not be converted. Truncated file?
1389 */
1390
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001391 // When we did a conversion report an error.
Bram Moolenaarf453d352008-06-04 17:37:34 +00001392 if (fio_flags != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001393#ifdef USE_ICONV
Bram Moolenaarf453d352008-06-04 17:37:34 +00001394 || iconv_fd != (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001395#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001396 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001397 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001398 if (can_retry)
1399 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001400 if (conv_error == 0)
1401 conv_error = curbuf->b_ml.ml_line_count
1402 - linecnt + 1;
1403 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001404 // Remember the first linenr with an illegal byte
Bram Moolenaarf453d352008-06-04 17:37:34 +00001405 else if (illegal_byte == 0)
1406 illegal_byte = curbuf->b_ml.ml_line_count
1407 - linecnt + 1;
1408 if (bad_char_behavior == BAD_DROP)
1409 {
1410 *(ptr - conv_restlen) = NUL;
1411 conv_restlen = 0;
1412 }
1413 else
1414 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001415 // Replace the trailing bytes with the replacement
1416 // character if we were converting; if we weren't,
1417 // leave the UTF8 checking code to do it, as it
1418 // works slightly differently.
Bram Moolenaarf453d352008-06-04 17:37:34 +00001419 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001420#ifdef USE_ICONV
Bram Moolenaarf453d352008-06-04 17:37:34 +00001421 || iconv_fd != (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001422#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001423 ))
1424 {
1425 while (conv_restlen > 0)
1426 {
1427 *(--ptr) = bad_char_behavior;
1428 --conv_restlen;
1429 }
1430 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001431 fio_flags = 0; // don't convert this
Bram Moolenaar13505972019-01-24 15:04:48 +01001432#ifdef USE_ICONV
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001433 if (iconv_fd != (iconv_t)-1)
1434 {
1435 iconv_close(iconv_fd);
1436 iconv_fd = (iconv_t)-1;
1437 }
Bram Moolenaar13505972019-01-24 15:04:48 +01001438#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001439 }
1440 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001442 }
1443 skip_read = FALSE;
1444
Bram Moolenaar071d4272004-06-13 20:20:40 +00001445 /*
1446 * At start of file (or after crypt magic number): Check for BOM.
1447 * Also check for a BOM for other Unicode encodings, but not after
1448 * converting with 'charconvert' or when a BOM has already been
1449 * found.
1450 */
1451 if ((filesize == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001452#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001453 || (cryptkey != NULL
1454 && filesize == crypt_get_header_len(
1455 crypt_get_method_nr(curbuf)))
Bram Moolenaar13505972019-01-24 15:04:48 +01001456#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001457 )
1458 && (fio_flags == FIO_UCSBOM
1459 || (!curbuf->b_p_bomb
1460 && tmpname == NULL
1461 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1462 {
1463 char_u *ccname;
1464 int blen;
1465
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001466 // no BOM detection in a short file or in binary mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00001467 if (size < 2 || curbuf->b_p_bin)
1468 ccname = NULL;
1469 else
1470 ccname = check_for_bom(ptr, size, &blen,
1471 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1472 if (ccname != NULL)
1473 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001474 // Remove BOM from the text
Bram Moolenaar071d4272004-06-13 20:20:40 +00001475 filesize += blen;
1476 size -= blen;
1477 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001478 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001479 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001480 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001481 curbuf->b_start_bomb = TRUE;
1482 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001483 }
1484
1485 if (fio_flags == FIO_UCSBOM)
1486 {
1487 if (ccname == NULL)
1488 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001489 // No BOM detected: retry with next encoding.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001490 advance_fenc = TRUE;
1491 }
1492 else
1493 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001494 // BOM detected: set "fenc" and jump back
Bram Moolenaar071d4272004-06-13 20:20:40 +00001495 if (fenc_alloced)
1496 vim_free(fenc);
1497 fenc = ccname;
1498 fenc_alloced = FALSE;
1499 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001500 // retry reading without getting new bytes or rewinding
Bram Moolenaar071d4272004-06-13 20:20:40 +00001501 skip_read = TRUE;
1502 goto retry;
1503 }
1504 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001505
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001506 // Include not converted bytes.
Bram Moolenaarf453d352008-06-04 17:37:34 +00001507 ptr -= conv_restlen;
1508 size += conv_restlen;
1509 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001510 /*
1511 * Break here for a read error or end-of-file.
1512 */
1513 if (size <= 0)
1514 break;
1515
Bram Moolenaar071d4272004-06-13 20:20:40 +00001516
Bram Moolenaar13505972019-01-24 15:04:48 +01001517#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001518 if (iconv_fd != (iconv_t)-1)
1519 {
1520 /*
1521 * Attempt conversion of the read bytes to 'encoding' using
1522 * iconv().
1523 */
1524 const char *fromp;
1525 char *top;
1526 size_t from_size;
1527 size_t to_size;
1528
1529 fromp = (char *)ptr;
1530 from_size = size;
1531 ptr += size;
1532 top = (char *)ptr;
1533 to_size = real_size - size;
1534
1535 /*
1536 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001537 * another conversion. Except for when there is no
1538 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001539 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001540 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1541 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001542 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1543 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001544 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001545 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001546 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001547 if (conv_error == 0)
1548 conv_error = readfile_linenr(linecnt,
1549 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001550
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001551 // Deal with a bad byte and continue with the next.
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001552 ++fromp;
1553 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001554 if (bad_char_behavior == BAD_KEEP)
1555 {
1556 *top++ = *(fromp - 1);
1557 --to_size;
1558 }
1559 else if (bad_char_behavior != BAD_DROP)
1560 {
1561 *top++ = bad_char_behavior;
1562 --to_size;
1563 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001564 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001565
1566 if (from_size > 0)
1567 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001568 // Some remaining characters, keep them for the next
1569 // round.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001570 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1571 conv_restlen = (int)from_size;
1572 }
1573
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001574 // move the linerest to before the converted characters
Bram Moolenaar071d4272004-06-13 20:20:40 +00001575 line_start = ptr - linerest;
1576 mch_memmove(line_start, buffer, (size_t)linerest);
1577 size = (long)((char_u *)top - ptr);
1578 }
Bram Moolenaar13505972019-01-24 15:04:48 +01001579#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001580
Bram Moolenaar4f974752019-02-17 17:44:42 +01001581#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001582 if (fio_flags & FIO_CODEPAGE)
1583 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001584 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001585 WCHAR ucs2buf[3];
1586 int ucs2len;
1587 int codepage = FIO_GET_CP(fio_flags);
1588 int bytelen;
1589 int found_bad;
1590 char replstr[2];
1591
Bram Moolenaar071d4272004-06-13 20:20:40 +00001592 /*
1593 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001594 * a codepage, using standard MS-Windows functions. This
1595 * requires two steps:
1596 * 1. convert from 'fileencoding' to ucs-2
1597 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001598 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001599 * Because there may be illegal bytes AND an incomplete byte
1600 * sequence at the end, we may have to do the conversion one
1601 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001602 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001603
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001604 // Replacement string for WideCharToMultiByte().
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001605 if (bad_char_behavior > 0)
1606 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001607 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001608 replstr[0] = '?';
1609 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001610
1611 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001612 * Move the bytes to the end of the buffer, so that we have
1613 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001614 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001615 src = ptr + real_size - size;
1616 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001617
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001618 /*
1619 * Do the conversion.
1620 */
1621 dst = ptr;
1622 size = size;
1623 while (size > 0)
1624 {
1625 found_bad = FALSE;
1626
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001627# ifdef CP_UTF8 // VC 4.1 doesn't define CP_UTF8
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001628 if (codepage == CP_UTF8)
1629 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001630 // Handle CP_UTF8 input ourselves to be able to handle
1631 // trailing bytes properly.
1632 // Get one UTF-8 character from src.
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001633 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001634 if (bytelen > size)
1635 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001636 // Only got some bytes of a character. Normally
1637 // it's put in "conv_rest", but if it's too long
1638 // deal with it as if they were illegal bytes.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001639 if (bytelen <= CONV_RESTLEN)
1640 break;
1641
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001642 // weird overlong byte sequence
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001643 bytelen = size;
1644 found_bad = TRUE;
1645 }
1646 else
1647 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001648 int u8c = utf_ptr2char(src);
1649
Bram Moolenaar86e01082005-12-29 22:45:34 +00001650 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001651 found_bad = TRUE;
1652 ucs2buf[0] = u8c;
1653 ucs2len = 1;
1654 }
1655 }
1656 else
1657# endif
1658 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001659 // We don't know how long the byte sequence is, try
1660 // from one to three bytes.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001661 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1662 ++bytelen)
1663 {
1664 ucs2len = MultiByteToWideChar(codepage,
1665 MB_ERR_INVALID_CHARS,
1666 (LPCSTR)src, bytelen,
1667 ucs2buf, 3);
1668 if (ucs2len > 0)
1669 break;
1670 }
1671 if (ucs2len == 0)
1672 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001673 // If we have only one byte then it's probably an
1674 // incomplete byte sequence. Otherwise discard
1675 // one byte as a bad character.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001676 if (size == 1)
1677 break;
1678 found_bad = TRUE;
1679 bytelen = 1;
1680 }
1681 }
1682
1683 if (!found_bad)
1684 {
1685 int i;
1686
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001687 // Convert "ucs2buf[ucs2len]" to 'enc' in "dst".
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001688 if (enc_utf8)
1689 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001690 // From UCS-2 to UTF-8. Cannot fail.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001691 for (i = 0; i < ucs2len; ++i)
1692 dst += utf_char2bytes(ucs2buf[i], dst);
1693 }
1694 else
1695 {
1696 BOOL bad = FALSE;
1697 int dstlen;
1698
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001699 // From UCS-2 to "enc_codepage". If the
1700 // conversion uses the default character "?",
1701 // the data doesn't fit in this encoding.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001702 dstlen = WideCharToMultiByte(enc_codepage, 0,
1703 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001704 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001705 replstr, &bad);
1706 if (bad)
1707 found_bad = TRUE;
1708 else
1709 dst += dstlen;
1710 }
1711 }
1712
1713 if (found_bad)
1714 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001715 // Deal with bytes we can't convert.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001716 if (can_retry)
1717 goto rewind_retry;
1718 if (conv_error == 0)
1719 conv_error = readfile_linenr(linecnt, ptr, dst);
1720 if (bad_char_behavior != BAD_DROP)
1721 {
1722 if (bad_char_behavior == BAD_KEEP)
1723 {
1724 mch_memmove(dst, src, bytelen);
1725 dst += bytelen;
1726 }
1727 else
1728 *dst++ = bad_char_behavior;
1729 }
1730 }
1731
1732 src += bytelen;
1733 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001734 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001735
1736 if (size > 0)
1737 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001738 // An incomplete byte sequence remaining.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001739 mch_memmove(conv_rest, src, size);
1740 conv_restlen = size;
1741 }
1742
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001743 // The new size is equal to how much "dst" was advanced.
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001744 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001745 }
1746 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001747#endif
1748#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001749 if (fio_flags & FIO_MACROMAN)
1750 {
1751 /*
1752 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001753 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001754 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001755 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001756 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001757 }
1758 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001759#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001760 if (fio_flags != 0)
1761 {
1762 int u8c;
1763 char_u *dest;
1764 char_u *tail = NULL;
1765
1766 /*
1767 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1768 * "enc_utf8" not set: Convert Unicode to Latin1.
1769 * Go from end to start through the buffer, because the number
1770 * of bytes may increase.
1771 * "dest" points to after where the UTF-8 bytes go, "p" points
1772 * to after the next character to convert.
1773 */
1774 dest = ptr + real_size;
1775 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1776 {
1777 p = ptr + size;
1778 if (fio_flags == FIO_UTF8)
1779 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001780 // Check for a trailing incomplete UTF-8 sequence
Bram Moolenaar071d4272004-06-13 20:20:40 +00001781 tail = ptr + size - 1;
1782 while (tail > ptr && (*tail & 0xc0) == 0x80)
1783 --tail;
1784 if (tail + utf_byte2len(*tail) <= ptr + size)
1785 tail = NULL;
1786 else
1787 p = tail;
1788 }
1789 }
1790 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1791 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001792 // Check for a trailing byte
Bram Moolenaar071d4272004-06-13 20:20:40 +00001793 p = ptr + (size & ~1);
1794 if (size & 1)
1795 tail = p;
1796 if ((fio_flags & FIO_UTF16) && p > ptr)
1797 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001798 // Check for a trailing leading word
Bram Moolenaar071d4272004-06-13 20:20:40 +00001799 if (fio_flags & FIO_ENDIAN_L)
1800 {
1801 u8c = (*--p << 8);
1802 u8c += *--p;
1803 }
1804 else
1805 {
1806 u8c = *--p;
1807 u8c += (*--p << 8);
1808 }
1809 if (u8c >= 0xd800 && u8c <= 0xdbff)
1810 tail = p;
1811 else
1812 p += 2;
1813 }
1814 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001815 else // FIO_UCS4
Bram Moolenaar071d4272004-06-13 20:20:40 +00001816 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001817 // Check for trailing 1, 2 or 3 bytes
Bram Moolenaar071d4272004-06-13 20:20:40 +00001818 p = ptr + (size & ~3);
1819 if (size & 3)
1820 tail = p;
1821 }
1822
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001823 // If there is a trailing incomplete sequence move it to
1824 // conv_rest[].
Bram Moolenaar071d4272004-06-13 20:20:40 +00001825 if (tail != NULL)
1826 {
1827 conv_restlen = (int)((ptr + size) - tail);
1828 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1829 size -= conv_restlen;
1830 }
1831
1832
1833 while (p > ptr)
1834 {
1835 if (fio_flags & FIO_LATIN1)
1836 u8c = *--p;
1837 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1838 {
1839 if (fio_flags & FIO_ENDIAN_L)
1840 {
1841 u8c = (*--p << 8);
1842 u8c += *--p;
1843 }
1844 else
1845 {
1846 u8c = *--p;
1847 u8c += (*--p << 8);
1848 }
1849 if ((fio_flags & FIO_UTF16)
1850 && u8c >= 0xdc00 && u8c <= 0xdfff)
1851 {
1852 int u16c;
1853
1854 if (p == ptr)
1855 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001856 // Missing leading word.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001857 if (can_retry)
1858 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001859 if (conv_error == 0)
1860 conv_error = readfile_linenr(linecnt,
1861 ptr, p);
1862 if (bad_char_behavior == BAD_DROP)
1863 continue;
1864 if (bad_char_behavior != BAD_KEEP)
1865 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001866 }
1867
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001868 // found second word of double-word, get the first
1869 // word and compute the resulting character
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 if (fio_flags & FIO_ENDIAN_L)
1871 {
1872 u16c = (*--p << 8);
1873 u16c += *--p;
1874 }
1875 else
1876 {
1877 u16c = *--p;
1878 u16c += (*--p << 8);
1879 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001880 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1881 + (u8c & 0x3ff);
1882
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001883 // Check if the word is indeed a leading word.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001884 if (u16c < 0xd800 || u16c > 0xdbff)
1885 {
1886 if (can_retry)
1887 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001888 if (conv_error == 0)
1889 conv_error = readfile_linenr(linecnt,
1890 ptr, p);
1891 if (bad_char_behavior == BAD_DROP)
1892 continue;
1893 if (bad_char_behavior != BAD_KEEP)
1894 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001895 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001896 }
1897 }
1898 else if (fio_flags & FIO_UCS4)
1899 {
1900 if (fio_flags & FIO_ENDIAN_L)
1901 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001902 u8c = (unsigned)*--p << 24;
1903 u8c += (unsigned)*--p << 16;
1904 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001905 u8c += *--p;
1906 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001907 else // big endian
Bram Moolenaar071d4272004-06-13 20:20:40 +00001908 {
1909 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001910 u8c += (unsigned)*--p << 8;
1911 u8c += (unsigned)*--p << 16;
1912 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001913 }
1914 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001915 else // UTF-8
Bram Moolenaar071d4272004-06-13 20:20:40 +00001916 {
1917 if (*--p < 0x80)
1918 u8c = *p;
1919 else
1920 {
1921 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001922 p -= len;
1923 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001924 if (len == 0)
1925 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001926 // Not a valid UTF-8 character, retry with
1927 // another fenc when possible, otherwise just
1928 // report the error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 if (can_retry)
1930 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001931 if (conv_error == 0)
1932 conv_error = readfile_linenr(linecnt,
1933 ptr, p);
1934 if (bad_char_behavior == BAD_DROP)
1935 continue;
1936 if (bad_char_behavior != BAD_KEEP)
1937 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001938 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001939 }
1940 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001941 if (enc_utf8) // produce UTF-8
Bram Moolenaar071d4272004-06-13 20:20:40 +00001942 {
1943 dest -= utf_char2len(u8c);
1944 (void)utf_char2bytes(u8c, dest);
1945 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001946 else // produce Latin1
Bram Moolenaar071d4272004-06-13 20:20:40 +00001947 {
1948 --dest;
1949 if (u8c >= 0x100)
1950 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001951 // character doesn't fit in latin1, retry with
1952 // another fenc when possible, otherwise just
1953 // report the error.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001954 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001955 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001956 if (conv_error == 0)
1957 conv_error = readfile_linenr(linecnt, ptr, p);
1958 if (bad_char_behavior == BAD_DROP)
1959 ++dest;
1960 else if (bad_char_behavior == BAD_KEEP)
1961 *dest = u8c;
1962 else if (eap != NULL && eap->bad_char != 0)
1963 *dest = bad_char_behavior;
1964 else
1965 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001966 }
1967 else
1968 *dest = u8c;
1969 }
1970 }
1971
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001972 // move the linerest to before the converted characters
Bram Moolenaar071d4272004-06-13 20:20:40 +00001973 line_start = dest - linerest;
1974 mch_memmove(line_start, buffer, (size_t)linerest);
1975 size = (long)((ptr + real_size) - dest);
1976 ptr = dest;
1977 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001978 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001979 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001980 int incomplete_tail = FALSE;
1981
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001982 // Reading UTF-8: Check if the bytes are valid UTF-8.
Bram Moolenaarf453d352008-06-04 17:37:34 +00001983 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001984 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001985 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001986 int l;
1987
1988 if (todo <= 0)
1989 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001990 if (*p >= 0x80)
1991 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001992 // A length of 1 means it's an illegal byte. Accept
1993 // an incomplete character at the end though, the next
1994 // read() will get the next bytes, we'll check it
1995 // then.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001996 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00001997 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001998 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01001999 // Avoid retrying with a different encoding when
2000 // a truncated file is more likely, or attempting
2001 // to read the rest of an incomplete sequence when
2002 // we have already done so.
Bram Moolenaarf453d352008-06-04 17:37:34 +00002003 if (p > ptr || filesize > 0)
2004 incomplete_tail = TRUE;
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002005 // Incomplete byte sequence, move it to conv_rest[]
2006 // and try to read the rest of it, unless we've
2007 // already done so.
Bram Moolenaarf453d352008-06-04 17:37:34 +00002008 if (p > ptr)
2009 {
2010 conv_restlen = todo;
2011 mch_memmove(conv_rest, p, conv_restlen);
2012 size -= conv_restlen;
2013 break;
2014 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002015 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002016 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002017 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002018 // Illegal byte. If we can try another encoding
2019 // do that, unless at EOF where a truncated
2020 // file is more likely than a conversion error.
Bram Moolenaarf453d352008-06-04 17:37:34 +00002021 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002022 break;
Bram Moolenaar13505972019-01-24 15:04:48 +01002023#ifdef USE_ICONV
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002024 // When we did a conversion report an error.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002025 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
2026 conv_error = readfile_linenr(linecnt, ptr, p);
Bram Moolenaar13505972019-01-24 15:04:48 +01002027#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002028 // Remember the first linenr with an illegal byte
Bram Moolenaarf453d352008-06-04 17:37:34 +00002029 if (conv_error == 0 && illegal_byte == 0)
2030 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002031
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002032 // Drop, keep or replace the bad byte.
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002033 if (bad_char_behavior == BAD_DROP)
2034 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00002035 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002036 --p;
2037 --size;
2038 }
2039 else if (bad_char_behavior != BAD_KEEP)
2040 *p = bad_char_behavior;
2041 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002042 else
2043 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002044 }
2045 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00002046 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002047 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002048 // Detected a UTF-8 error.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002049rewind_retry:
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002050 // Retry reading with another conversion.
Bram Moolenaar13505972019-01-24 15:04:48 +01002051#if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002052 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002053 // iconv() failed, try 'charconvert'
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002054 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002055 else
Bram Moolenaar13505972019-01-24 15:04:48 +01002056#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002057 // use next item from 'fileencodings'
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002058 advance_fenc = TRUE;
2059 file_rewind = TRUE;
2060 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002061 }
2062 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002063
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002064 // count the number of characters (after conversion!)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002065 filesize += size;
2066
2067 /*
2068 * when reading the first part of a file: guess EOL type
2069 */
2070 if (fileformat == EOL_UNKNOWN)
2071 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002072 // First try finding a NL, for Dos and Unix
Bram Moolenaar071d4272004-06-13 20:20:40 +00002073 if (try_dos || try_unix)
2074 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002075 // Reset the carriage return counter.
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002076 if (try_mac)
2077 try_mac = 1;
2078
Bram Moolenaar071d4272004-06-13 20:20:40 +00002079 for (p = ptr; p < ptr + size; ++p)
2080 {
2081 if (*p == NL)
2082 {
2083 if (!try_unix
2084 || (try_dos && p > ptr && p[-1] == CAR))
2085 fileformat = EOL_DOS;
2086 else
2087 fileformat = EOL_UNIX;
2088 break;
2089 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002090 else if (*p == CAR && try_mac)
2091 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002092 }
2093
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002094 // Don't give in to EOL_UNIX if EOL_MAC is more likely
Bram Moolenaar071d4272004-06-13 20:20:40 +00002095 if (fileformat == EOL_UNIX && try_mac)
2096 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002097 // Need to reset the counters when retrying fenc.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002098 try_mac = 1;
2099 try_unix = 1;
2100 for (; p >= ptr && *p != CAR; p--)
2101 ;
2102 if (p >= ptr)
2103 {
2104 for (p = ptr; p < ptr + size; ++p)
2105 {
2106 if (*p == NL)
2107 try_unix++;
2108 else if (*p == CAR)
2109 try_mac++;
2110 }
2111 if (try_mac > try_unix)
2112 fileformat = EOL_MAC;
2113 }
2114 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002115 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002116 // Looking for CR but found no end-of-line markers at
2117 // all: use the default format.
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002118 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002119 }
2120
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002121 // No NL found: may use Mac format
Bram Moolenaar071d4272004-06-13 20:20:40 +00002122 if (fileformat == EOL_UNKNOWN && try_mac)
2123 fileformat = EOL_MAC;
2124
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002125 // Still nothing found? Use first format in 'ffs'
Bram Moolenaar071d4272004-06-13 20:20:40 +00002126 if (fileformat == EOL_UNKNOWN)
2127 fileformat = default_fileformat();
2128
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002129 // if editing a new file: may set p_tx and p_ff
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002130 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131 set_fileformat(fileformat, OPT_LOCAL);
2132 }
2133 }
2134
2135 /*
2136 * This loop is executed once for every character read.
2137 * Keep it fast!
2138 */
2139 if (fileformat == EOL_MAC)
2140 {
2141 --ptr;
2142 while (++ptr, --size >= 0)
2143 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002144 // catch most common case first
Bram Moolenaar071d4272004-06-13 20:20:40 +00002145 if ((c = *ptr) != NUL && c != CAR && c != NL)
2146 continue;
2147 if (c == NUL)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002148 *ptr = NL; // NULs are replaced by newlines!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002149 else if (c == NL)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002150 *ptr = CAR; // NLs are replaced by CRs!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002151 else
2152 {
2153 if (skip_count == 0)
2154 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002155 *ptr = NUL; // end of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00002156 len = (colnr_T) (ptr - line_start + 1);
2157 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2158 {
2159 error = TRUE;
2160 break;
2161 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002162#ifdef FEAT_PERSISTENT_UNDO
2163 if (read_undo_file)
2164 sha256_update(&sha_ctx, line_start, len);
2165#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002166 ++lnum;
2167 if (--read_count == 0)
2168 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002169 error = TRUE; // break loop
2170 line_start = ptr; // nothing left to write
Bram Moolenaar071d4272004-06-13 20:20:40 +00002171 break;
2172 }
2173 }
2174 else
2175 --skip_count;
2176 line_start = ptr + 1;
2177 }
2178 }
2179 }
2180 else
2181 {
2182 --ptr;
2183 while (++ptr, --size >= 0)
2184 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002185 if ((c = *ptr) != NUL && c != NL) // catch most common case
Bram Moolenaar071d4272004-06-13 20:20:40 +00002186 continue;
2187 if (c == NUL)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002188 *ptr = NL; // NULs are replaced by newlines!
Bram Moolenaar071d4272004-06-13 20:20:40 +00002189 else
2190 {
2191 if (skip_count == 0)
2192 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002193 *ptr = NUL; // end of line
Bram Moolenaar071d4272004-06-13 20:20:40 +00002194 len = (colnr_T)(ptr - line_start + 1);
2195 if (fileformat == EOL_DOS)
2196 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002197 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002198 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002199 // remove CR before NL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002200 ptr[-1] = NUL;
2201 --len;
2202 }
2203 /*
2204 * Reading in Dos format, but no CR-LF found!
2205 * When 'fileformats' includes "unix", delete all
2206 * the lines read so far and start all over again.
2207 * Otherwise give an error message later.
2208 */
2209 else if (ff_error != EOL_DOS)
2210 {
2211 if ( try_unix
2212 && !read_stdin
2213 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002214 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2215 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216 {
2217 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002218 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002219 set_fileformat(EOL_UNIX, OPT_LOCAL);
2220 file_rewind = TRUE;
2221 keep_fileformat = TRUE;
2222 goto retry;
2223 }
2224 ff_error = EOL_DOS;
2225 }
2226 }
2227 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2228 {
2229 error = TRUE;
2230 break;
2231 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002232#ifdef FEAT_PERSISTENT_UNDO
2233 if (read_undo_file)
2234 sha256_update(&sha_ctx, line_start, len);
2235#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002236 ++lnum;
2237 if (--read_count == 0)
2238 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002239 error = TRUE; // break loop
2240 line_start = ptr; // nothing left to write
Bram Moolenaar071d4272004-06-13 20:20:40 +00002241 break;
2242 }
2243 }
2244 else
2245 --skip_count;
2246 line_start = ptr + 1;
2247 }
2248 }
2249 }
2250 linerest = (long)(ptr - line_start);
2251 ui_breakcheck();
2252 }
2253
2254failed:
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002255 // not an error, max. number of lines reached
Bram Moolenaar071d4272004-06-13 20:20:40 +00002256 if (error && read_count == 0)
2257 error = FALSE;
2258
2259 /*
2260 * If we get EOF in the middle of a line, note the fact and
2261 * complete the line ourselves.
2262 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2263 */
2264 if (!error
2265 && !got_int
2266 && linerest != 0
2267 && !(!curbuf->b_p_bin
2268 && fileformat == EOL_DOS
2269 && *line_start == Ctrl_Z
2270 && ptr == line_start + 1))
2271 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002272 // remember for when writing
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002273 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002274 curbuf->b_p_eol = FALSE;
2275 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002276 len = (colnr_T)(ptr - line_start + 1);
2277 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002278 error = TRUE;
2279 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002280 {
2281#ifdef FEAT_PERSISTENT_UNDO
2282 if (read_undo_file)
2283 sha256_update(&sha_ctx, line_start, len);
2284#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002285 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002286 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002287 }
2288
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002289 if (set_options)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002290 save_file_ff(curbuf); // remember the current file format
Bram Moolenaar071d4272004-06-13 20:20:40 +00002291
2292#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002293 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002294 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002295 crypt_free_state(curbuf->b_cryptstate);
2296 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002297 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002298 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2299 crypt_free_key(cryptkey);
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002300 // Don't set cryptkey to NULL, it's used below as a flag that
2301 // encryption was used.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002302#endif
2303
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002304 // If editing a new file: set 'fenc' for the current buffer.
2305 // Also for ":read ++edit file".
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002306 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002307 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002308 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002309 if (fenc_alloced)
2310 vim_free(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01002311#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312 if (iconv_fd != (iconv_t)-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002313 iconv_close(iconv_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002314#endif
2315
2316 if (!read_buffer && !read_stdin)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002317 close(fd); // errors are ignored
Bram Moolenaarf05da212009-11-17 16:13:15 +00002318#ifdef HAVE_FD_CLOEXEC
2319 else
2320 {
2321 int fdflags = fcntl(fd, F_GETFD);
Bram Moolenaara7251492021-01-02 16:53:13 +01002322
Bram Moolenaarf05da212009-11-17 16:13:15 +00002323 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002324 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002325 }
2326#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002327 vim_free(buffer);
2328
2329#ifdef HAVE_DUP
2330 if (read_stdin)
2331 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002332 // Use stderr for stdin, makes shell commands work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002333 close(0);
Bram Moolenaar42335f52018-09-13 15:33:43 +02002334 vim_ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002335 }
2336#endif
2337
Bram Moolenaar071d4272004-06-13 20:20:40 +00002338 if (tmpname != NULL)
2339 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002340 mch_remove(tmpname); // delete converted file
Bram Moolenaar071d4272004-06-13 20:20:40 +00002341 vim_free(tmpname);
2342 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002343 --no_wait_return; // may wait for return now
Bram Moolenaar071d4272004-06-13 20:20:40 +00002344
2345 /*
2346 * In recovery mode everything but autocommands is skipped.
2347 */
2348 if (!recoverymode)
2349 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002350 // need to delete the last line, which comes from the empty buffer
Bram Moolenaar071d4272004-06-13 20:20:40 +00002351 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2352 {
2353#ifdef FEAT_NETBEANS_INTG
2354 netbeansFireChanges = 0;
2355#endif
Bram Moolenaarca70c072020-05-30 20:30:46 +02002356 ml_delete(curbuf->b_ml.ml_line_count);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002357#ifdef FEAT_NETBEANS_INTG
2358 netbeansFireChanges = 1;
2359#endif
2360 --linecnt;
2361 }
2362 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2363 if (filesize == 0)
2364 linecnt = 0;
2365 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002366 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002367 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002368#ifdef FEAT_DIFF
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002369 // After reading the text into the buffer the diff info needs to
2370 // be updated.
Bram Moolenaar7263a772007-05-10 17:35:54 +00002371 diff_invalidate(curbuf);
2372#endif
2373#ifdef FEAT_FOLDING
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002374 // All folds in the window are invalid now. Mark them for update
2375 // before triggering autocommands.
Bram Moolenaar7263a772007-05-10 17:35:54 +00002376 foldUpdateAll(curwin);
2377#endif
2378 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002379 else if (linecnt) // appended at least one line
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380 appended_lines_mark(from, linecnt);
2381
Bram Moolenaar071d4272004-06-13 20:20:40 +00002382#ifndef ALWAYS_USE_GUI
2383 /*
2384 * If we were reading from the same terminal as where messages go,
2385 * the screen will have been messed up.
2386 * Switch on raw mode now and clear the screen.
2387 */
2388 if (read_stdin)
2389 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002390 settmode(TMODE_RAW); // set to raw mode
Bram Moolenaar071d4272004-06-13 20:20:40 +00002391 starttermcap();
2392 screenclear();
2393 }
2394#endif
2395
2396 if (got_int)
2397 {
2398 if (!(flags & READ_DUMMY))
2399 {
2400 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2401 if (newfile)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002402 curbuf->b_p_ro = TRUE; // must use "w!" now
Bram Moolenaar071d4272004-06-13 20:20:40 +00002403 }
2404 msg_scroll = msg_save;
2405#ifdef FEAT_VIMINFO
2406 check_marks_read();
2407#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002408 return OK; // an interrupt isn't really an error
Bram Moolenaar071d4272004-06-13 20:20:40 +00002409 }
2410
2411 if (!filtering && !(flags & READ_DUMMY))
2412 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002413 msg_add_fname(curbuf, sfname); // fname in IObuff with quotes
Bram Moolenaar071d4272004-06-13 20:20:40 +00002414 c = FALSE;
2415
2416#ifdef UNIX
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002417 if (S_ISFIFO(perm)) // fifo
Bram Moolenaar071d4272004-06-13 20:20:40 +00002418 {
2419 STRCAT(IObuff, _("[fifo]"));
2420 c = TRUE;
2421 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002422 if (S_ISSOCK(perm)) // or socket
Bram Moolenaar071d4272004-06-13 20:20:40 +00002423 {
2424 STRCAT(IObuff, _("[socket]"));
2425 c = TRUE;
2426 }
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002427# ifdef OPEN_CHR_FILES
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002428 if (S_ISCHR(perm)) // or character special
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002429 {
2430 STRCAT(IObuff, _("[character special]"));
2431 c = TRUE;
2432 }
2433# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002434#endif
2435 if (curbuf->b_p_ro)
2436 {
2437 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2438 c = TRUE;
2439 }
2440 if (read_no_eol_lnum)
2441 {
2442 msg_add_eol();
2443 c = TRUE;
2444 }
2445 if (ff_error == EOL_DOS)
2446 {
2447 STRCAT(IObuff, _("[CR missing]"));
2448 c = TRUE;
2449 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002450 if (split)
2451 {
2452 STRCAT(IObuff, _("[long lines split]"));
2453 c = TRUE;
2454 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002455 if (notconverted)
2456 {
2457 STRCAT(IObuff, _("[NOT converted]"));
2458 c = TRUE;
2459 }
2460 else if (converted)
2461 {
2462 STRCAT(IObuff, _("[converted]"));
2463 c = TRUE;
2464 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002465#ifdef FEAT_CRYPT
2466 if (cryptkey != NULL)
2467 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002468 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002469 c = TRUE;
2470 }
2471#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002472 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002473 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002474 sprintf((char *)IObuff + STRLEN(IObuff),
2475 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002476 c = TRUE;
2477 }
2478 else if (illegal_byte > 0)
2479 {
2480 sprintf((char *)IObuff + STRLEN(IObuff),
2481 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2482 c = TRUE;
2483 }
Bram Moolenaar13505972019-01-24 15:04:48 +01002484 else if (error)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002485 {
2486 STRCAT(IObuff, _("[READ ERRORS]"));
2487 c = TRUE;
2488 }
2489 if (msg_add_fileformat(fileformat))
2490 c = TRUE;
2491#ifdef FEAT_CRYPT
2492 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002493 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002494 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002495 else
2496#endif
2497 msg_add_lines(c, (long)linecnt, filesize);
2498
Bram Moolenaard23a8232018-02-10 18:45:26 +01002499 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002500 msg_scrolled_ign = TRUE;
2501#ifdef ALWAYS_USE_GUI
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002502 // Don't show the message when reading stdin, it would end up in a
2503 // message box (which might be shown when exiting!)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002504 if (read_stdin || read_buffer)
2505 p = msg_may_trunc(FALSE, IObuff);
2506 else
2507#endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002508 {
2509 if (msg_col > 0)
2510 msg_putchar('\r'); // overwrite previous message
Bram Moolenaar32526b32019-01-19 17:43:09 +01002511 p = (char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002512 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002513 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002514 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002515 // Need to repeat the message after redrawing when:
2516 // - When reading from stdin (the screen will be cleared next).
2517 // - When restart_edit is set (otherwise there will be a delay
2518 // before redrawing).
2519 // - When the screen was scrolled but there is no wait-return
2520 // prompt.
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002521 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002522 msg_scrolled_ign = FALSE;
2523 }
2524
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002525 // with errors writing the file requires ":w!"
Bram Moolenaar071d4272004-06-13 20:20:40 +00002526 if (newfile && (error
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002527 || conv_error != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01002528 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002529 curbuf->b_p_ro = TRUE;
2530
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002531 u_clearline(); // cannot use "U" command after adding lines
Bram Moolenaar071d4272004-06-13 20:20:40 +00002532
2533 /*
2534 * In Ex mode: cursor at last new line.
2535 * Otherwise: cursor at first new line.
2536 */
2537 if (exmode_active)
2538 curwin->w_cursor.lnum = from + linecnt;
2539 else
2540 curwin->w_cursor.lnum = from + 1;
2541 check_cursor_lnum();
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002542 beginline(BL_WHITE | BL_FIX); // on first non-blank
Bram Moolenaar071d4272004-06-13 20:20:40 +00002543
Bram Moolenaare1004402020-10-24 20:49:43 +02002544 if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +01002545 {
2546 // Set '[ and '] marks to the newly read lines.
2547 curbuf->b_op_start.lnum = from + 1;
2548 curbuf->b_op_start.col = 0;
2549 curbuf->b_op_end.lnum = from + linecnt;
2550 curbuf->b_op_end.col = 0;
2551 }
Bram Moolenaar03f48552006-02-28 23:52:23 +00002552
Bram Moolenaar4f974752019-02-17 17:44:42 +01002553#ifdef MSWIN
Bram Moolenaar03f48552006-02-28 23:52:23 +00002554 /*
2555 * Work around a weird problem: When a file has two links (only
2556 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002557 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002558 * It's correct again after reading the file, thus reset the timestamp
2559 * here.
2560 */
2561 if (newfile && !read_stdin && !read_buffer
2562 && mch_stat((char *)fname, &st) >= 0)
2563 {
2564 buf_store_time(curbuf, &st, fname);
2565 curbuf->b_mtime_read = curbuf->b_mtime;
2566 }
2567#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002568 }
2569 msg_scroll = msg_save;
2570
2571#ifdef FEAT_VIMINFO
2572 /*
2573 * Get the marks before executing autocommands, so they can be used there.
2574 */
2575 check_marks_read();
2576#endif
2577
Bram Moolenaar071d4272004-06-13 20:20:40 +00002578 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002579 * We remember if the last line of the read didn't have
2580 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2581 * or writing the read again with 'binary' on. The latter is required
2582 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002583 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002584 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002585
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002586 // When reloading a buffer put the cursor at the first line that is
2587 // different.
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002588 if (flags & READ_KEEP_UNDO)
2589 u_find_first_changed();
2590
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002591#ifdef FEAT_PERSISTENT_UNDO
2592 /*
2593 * When opening a new file locate undo info and read it.
2594 */
2595 if (read_undo_file)
2596 {
2597 char_u hash[UNDO_HASH_SIZE];
2598
2599 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002600 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002601 }
2602#endif
2603
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002604 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002605 {
2606 int m = msg_scroll;
2607 int n = msg_scrolled;
2608
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002609 // Save the fileformat now, otherwise the buffer will be considered
2610 // modified if the format/encoding was automatically detected.
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002611 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002612 save_file_ff(curbuf);
2613
2614 /*
2615 * The output from the autocommands should not overwrite anything and
2616 * should not be overwritten: Set msg_scroll, restore its value if no
2617 * output was done.
2618 */
2619 msg_scroll = TRUE;
2620 if (filtering)
2621 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2622 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002623 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002624 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002625 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2626 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002627 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2628 /*
2629 * EVENT_FILETYPE was not triggered but the buffer already has a
2630 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2631 */
2632 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2633 TRUE, curbuf);
2634 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002635 else
2636 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2637 FALSE, NULL, eap);
2638 if (msg_scrolled == n)
2639 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002640# ifdef FEAT_EVAL
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002641 if (aborting()) // autocmds may abort script processing
Bram Moolenaar071d4272004-06-13 20:20:40 +00002642 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002643# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002644 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002645
2646 if (recoverymode && error)
2647 return FAIL;
2648 return OK;
2649}
2650
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002651#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002652/*
2653 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2654 * which is the name of files used for process substitution output by
2655 * some shells on some operating systems, e.g., bash on SunOS.
2656 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2657 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002658 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002659is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002660{
2661 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2662 && VIM_ISDIGIT(fname[8])
2663 && *skipdigits(fname + 9) == NUL
2664 && (fname[9] != NUL
2665 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2666}
2667#endif
2668
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002669/*
2670 * From the current line count and characters read after that, estimate the
2671 * line number where we are now.
2672 * Used for error messages that include a line number.
2673 */
2674 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002675readfile_linenr(
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002676 linenr_T linecnt, // line count before reading more bytes
2677 char_u *p, // start of more bytes read
2678 char_u *endp) // end of more bytes read
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002679{
2680 char_u *s;
2681 linenr_T lnum;
2682
2683 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2684 for (s = p; s < endp; ++s)
2685 if (*s == '\n')
2686 ++lnum;
2687 return lnum;
2688}
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002689
Bram Moolenaar071d4272004-06-13 20:20:40 +00002690/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002691 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2692 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002693 * Returns OK or FAIL.
2694 */
2695 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002696prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002697{
Bram Moolenaar13505972019-01-24 15:04:48 +01002698 eap->cmd = alloc(15 + (unsigned)STRLEN(buf->b_p_fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699 if (eap->cmd == NULL)
2700 return FAIL;
2701
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002702 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2703 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002704 eap->bad_char = buf->b_bad_char;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002705 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002706
2707 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002708 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002709 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002710 return OK;
2711}
2712
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002713/*
2714 * Set default or forced 'fileformat' and 'binary'.
2715 */
2716 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002717set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002718{
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002719 // set default 'fileformat'
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002720 if (set_options)
2721 {
2722 if (eap != NULL && eap->force_ff != 0)
2723 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2724 else if (*p_ffs != NUL)
2725 set_fileformat(default_fileformat(), OPT_LOCAL);
2726 }
2727
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002728 // set or reset 'binary'
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002729 if (eap != NULL && eap->force_bin != 0)
2730 {
2731 int oldval = curbuf->b_p_bin;
2732
2733 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2734 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2735 }
2736}
2737
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002738/*
2739 * Set forced 'fileencoding'.
2740 */
2741 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002742set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002743{
2744 if (eap->force_enc != 0)
2745 {
2746 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2747
2748 if (fenc != NULL)
2749 set_string_option_direct((char_u *)"fenc", -1,
2750 fenc, OPT_FREE|OPT_LOCAL, 0);
2751 vim_free(fenc);
2752 }
2753}
2754
Bram Moolenaar071d4272004-06-13 20:20:40 +00002755/*
2756 * Find next fileencoding to use from 'fileencodings'.
2757 * "pp" points to fenc_next. It's advanced to the next item.
2758 * When there are no more items, an empty string is returned and *pp is set to
2759 * NULL.
Bram Moolenaarf077db22019-08-13 00:18:24 +02002760 * When *pp is not set to NULL, the result is in allocated memory and "alloced"
2761 * is set to TRUE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002762 */
2763 static char_u *
Bram Moolenaarf077db22019-08-13 00:18:24 +02002764next_fenc(char_u **pp, int *alloced)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002765{
2766 char_u *p;
2767 char_u *r;
2768
Bram Moolenaarf077db22019-08-13 00:18:24 +02002769 *alloced = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 if (**pp == NUL)
2771 {
2772 *pp = NULL;
2773 return (char_u *)"";
2774 }
2775 p = vim_strchr(*pp, ',');
2776 if (p == NULL)
2777 {
2778 r = enc_canonize(*pp);
2779 *pp += STRLEN(*pp);
2780 }
2781 else
2782 {
Bram Moolenaar71ccd032020-06-12 22:59:11 +02002783 r = vim_strnsave(*pp, p - *pp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002784 *pp = p + 1;
2785 if (r != NULL)
2786 {
2787 p = enc_canonize(r);
2788 vim_free(r);
2789 r = p;
2790 }
2791 }
Bram Moolenaarf077db22019-08-13 00:18:24 +02002792 if (r != NULL)
2793 *alloced = TRUE;
2794 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002795 {
Bram Moolenaarf077db22019-08-13 00:18:24 +02002796 // out of memory
Bram Moolenaar071d4272004-06-13 20:20:40 +00002797 r = (char_u *)"";
2798 *pp = NULL;
2799 }
2800 return r;
2801}
2802
Bram Moolenaar13505972019-01-24 15:04:48 +01002803#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002804/*
2805 * Convert a file with the 'charconvert' expression.
2806 * This closes the file which is to be read, converts it and opens the
2807 * resulting file for reading.
2808 * Returns name of the resulting converted file (the caller should delete it
2809 * after reading it).
2810 * Returns NULL if the conversion failed ("*fdp" is not set) .
2811 */
2812 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002813readfile_charconvert(
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002814 char_u *fname, // name of input file
2815 char_u *fenc, // converted from
2816 int *fdp) // in/out: file descriptor of file
Bram Moolenaar071d4272004-06-13 20:20:40 +00002817{
2818 char_u *tmpname;
Bram Moolenaar32526b32019-01-19 17:43:09 +01002819 char *errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002820
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002821 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002822 if (tmpname == NULL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002823 errmsg = _("Can't find temp file for conversion");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002824 else
2825 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002826 close(*fdp); // close the input file, ignore errors
Bram Moolenaar071d4272004-06-13 20:20:40 +00002827 *fdp = -1;
2828 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2829 fname, tmpname) == FAIL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002830 errmsg = _("Conversion with 'charconvert' failed");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002831 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2832 O_RDONLY | O_EXTRA, 0)) < 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002833 errmsg = _("can't read output of 'charconvert'");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002834 }
2835
2836 if (errmsg != NULL)
2837 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002838 // Don't use emsg(), it breaks mappings, the retry with
2839 // another type of conversion might still work.
Bram Moolenaar32526b32019-01-19 17:43:09 +01002840 msg(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002841 if (tmpname != NULL)
2842 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002843 mch_remove(tmpname); // delete converted file
Bram Moolenaard23a8232018-02-10 18:45:26 +01002844 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002845 }
2846 }
2847
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002848 // If the input file is closed, open it (caller should check for error).
Bram Moolenaar071d4272004-06-13 20:20:40 +00002849 if (*fdp < 0)
2850 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2851
2852 return tmpname;
2853}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002854#endif
2855
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002856#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002857/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002858 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002859 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2860 * *filesizep are updated.
2861 * Return the (new) encryption key, NULL for no encryption.
2862 */
2863 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002864check_for_cryptkey(
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002865 char_u *cryptkey, // previous encryption key or NULL
2866 char_u *ptr, // pointer to read bytes
2867 long *sizep, // length of read bytes
2868 off_T *filesizep, // nr of bytes used from file
2869 int newfile, // editing a new buffer
2870 char_u *fname, // file name to display
2871 int *did_ask) // flag: whether already asked for key
Bram Moolenaar071d4272004-06-13 20:20:40 +00002872{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002873 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002874 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002875
2876 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002877 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002878 // Mark the buffer as read-only until the decryption has taken place.
2879 // Avoids accidentally overwriting the file with garbage.
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002880 curbuf->b_p_ro = TRUE;
2881
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002882 // Set the cryptmethod local to the buffer.
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002883 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002884 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002885 {
2886 if (*curbuf->b_p_key)
2887 cryptkey = curbuf->b_p_key;
2888 else
2889 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002890 // When newfile is TRUE, store the typed key in the 'key'
2891 // option and don't free it. bf needs hash of the key saved.
2892 // Don't ask for the key again when first time Enter was hit.
2893 // Happens when retrying to detect encoding.
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002894 smsg(_(need_key_msg), fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002895 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002896 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002897 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002898 *did_ask = TRUE;
2899
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002900 // check if empty key entered
Bram Moolenaar071d4272004-06-13 20:20:40 +00002901 if (cryptkey != NULL && *cryptkey == NUL)
2902 {
2903 if (cryptkey != curbuf->b_p_key)
2904 vim_free(cryptkey);
2905 cryptkey = NULL;
2906 }
2907 }
2908 }
2909
2910 if (cryptkey != NULL)
2911 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002912 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002913
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002914 curbuf->b_cryptstate = crypt_create_from_header(
2915 method, cryptkey, ptr);
2916 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002917
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002918 // Remove cryptmethod specific header from the text.
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002919 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02002920 if (*sizep <= header_len)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002921 // invalid header, buffer can't be encrypted
Bram Moolenaar680e0152016-09-25 20:54:11 +02002922 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002923 *filesizep += header_len;
2924 *sizep -= header_len;
2925 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
2926
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002927 // Restore the read-only flag.
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002928 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002929 }
2930 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002931 // When starting to edit a new file which does not have encryption, clear
2932 // the 'key' option, except when starting up (called with -x argument)
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002933 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002934 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2935
2936 return cryptkey;
2937}
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002938#endif // FEAT_CRYPT
Bram Moolenaar80794b12010-06-13 05:20:42 +02002939
Bram Moolenaar071d4272004-06-13 20:20:40 +00002940/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00002941 * Return TRUE if a file appears to be read-only from the file permissions.
2942 */
2943 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002944check_file_readonly(
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002945 char_u *fname, // full path to file
2946 int perm UNUSED) // known permissions on file
Bram Moolenaar5386a122007-06-28 20:02:32 +00002947{
2948#ifndef USE_MCH_ACCESS
2949 int fd = 0;
2950#endif
2951
2952 return (
2953#ifdef USE_MCH_ACCESS
2954# ifdef UNIX
2955 (perm & 0222) == 0 ||
2956# endif
2957 mch_access((char *)fname, W_OK)
2958#else
2959 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
2960 ? TRUE : (close(fd), FALSE)
2961#endif
2962 );
2963}
2964
Bram Moolenaara7870192019-02-14 12:56:36 +01002965#if defined(HAVE_FSYNC) || defined(PROTO)
2966/*
2967 * Call fsync() with Mac-specific exception.
2968 * Return fsync() result: zero for success.
2969 */
2970 int
2971vim_fsync(int fd)
2972{
2973 int r;
2974
2975# ifdef MACOS_X
2976 r = fcntl(fd, F_FULLFSYNC);
Bram Moolenaar91668382019-02-21 12:16:12 +01002977 if (r != 0) // F_FULLFSYNC not working or not supported
Bram Moolenaara7870192019-02-14 12:56:36 +01002978# endif
2979 r = fsync(fd);
2980 return r;
2981}
2982#endif
2983
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002985 * Set the name of the current buffer. Use when the buffer doesn't have a
2986 * name and a ":r" or ":w" command with a file name is used.
2987 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02002988 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002989set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002990{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00002991 buf_T *buf = curbuf;
2992
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002993 // It's like the unnamed buffer is deleted....
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002994 if (curbuf->b_p_bl)
2995 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
2996 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01002997#ifdef FEAT_EVAL
Bram Moolenaar217e1b82019-12-01 21:41:28 +01002998 if (aborting()) // autocmds may abort script processing
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002999 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01003000#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00003001 if (curbuf != buf)
3002 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003003 // We are in another buffer now, don't do the renaming.
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003004 emsg(_(e_auchangedbuf));
Bram Moolenaar8b38e242009-06-16 13:35:20 +00003005 return FAIL;
3006 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003007
3008 if (setfname(curbuf, fname, sfname, FALSE) == OK)
3009 curbuf->b_flags |= BF_NOTEDITED;
3010
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003011 // ....and a new named one is created
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003012 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
3013 if (curbuf->b_p_bl)
3014 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01003015#ifdef FEAT_EVAL
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003016 if (aborting()) // autocmds may abort script processing
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003017 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01003018#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003019
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003020 // Do filetype detection now if 'filetype' is empty.
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003021 if (*curbuf->b_p_ft == NUL)
3022 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00003023 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02003024 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00003025 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003026 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00003027
3028 return OK;
3029}
3030
3031/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032 * Put file name into IObuff with quotes.
3033 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00003034 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003035msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003036{
3037 if (fname == NULL)
3038 fname = (char_u *)"-stdin-";
3039 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
3040 IObuff[0] = '"';
3041 STRCAT(IObuff, "\" ");
3042}
3043
3044/*
3045 * Append message for text mode to IObuff.
3046 * Return TRUE if something appended.
3047 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003048 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003049msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003050{
3051#ifndef USE_CRNL
3052 if (eol_type == EOL_DOS)
3053 {
3054 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
3055 return TRUE;
3056 }
3057#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003058 if (eol_type == EOL_MAC)
3059 {
3060 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
3061 return TRUE;
3062 }
Bram Moolenaar00590742019-02-15 21:06:09 +01003063#ifdef USE_CRNL
Bram Moolenaar071d4272004-06-13 20:20:40 +00003064 if (eol_type == EOL_UNIX)
3065 {
3066 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
3067 return TRUE;
3068 }
3069#endif
3070 return FALSE;
3071}
3072
3073/*
3074 * Append line and character count to IObuff.
3075 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00003076 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003077msg_add_lines(
3078 int insert_space,
3079 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02003080 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003081{
3082 char_u *p;
3083
3084 p = IObuff + STRLEN(IObuff);
3085
3086 if (insert_space)
3087 *p++ = ' ';
3088 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02003089 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaar3f40ce72020-07-05 14:10:13 +02003090 "%ldL, %lldB", lnum, (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091 else
3092 {
Bram Moolenaarda6e8912018-08-21 15:12:14 +02003093 sprintf((char *)p, NGETTEXT("%ld line, ", "%ld lines, ", lnum), lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003094 p += STRLEN(p);
Bram Moolenaarda6e8912018-08-21 15:12:14 +02003095 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaar3f40ce72020-07-05 14:10:13 +02003096 NGETTEXT("%lld byte", "%lld bytes", nchars),
Bram Moolenaarf9706e92020-02-22 14:27:04 +01003097 (varnumber_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003098 }
3099}
3100
3101/*
3102 * Append message for missing line separator to IObuff.
3103 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003104 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003105msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003106{
3107 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
3108}
3109
Bram Moolenaar473952e2019-09-28 16:30:04 +02003110 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003111time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003112{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003113#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003114 // On a FAT filesystem, esp. under Linux, there are only 5 bits to store
3115 // the seconds. Since the roundoff is done when flushing the inode, the
3116 // time may change unexpectedly by one second!!!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003117 return (t1 - t2 > 1 || t2 - t1 > 1);
3118#else
3119 return (t1 != t2);
3120#endif
3121}
3122
3123/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003124 * Return TRUE if file encoding "fenc" requires conversion from or to
3125 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003126 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003127 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003128need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003129{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003130 int same_encoding;
3131 int enc_flags;
3132 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003133
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003134 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02003135 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003136 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02003137 fenc_flags = 0;
3138 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003139 else
3140 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003141 // Ignore difference between "ansi" and "latin1", "ucs-4" and
3142 // "ucs-4be", etc.
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003143 enc_flags = get_fio_flags(p_enc);
3144 fenc_flags = get_fio_flags(fenc);
3145 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
3146 }
3147 if (same_encoding)
3148 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003149 // Specified encoding matches with 'encoding'. This requires
3150 // conversion when 'encoding' is Unicode but not UTF-8.
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003151 return enc_unicode != 0;
3152 }
3153
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003154 // Encodings differ. However, conversion is not needed when 'enc' is any
3155 // Unicode encoding and the file is UTF-8.
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003156 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003157}
3158
3159/*
3160 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
3161 * internal conversion.
3162 * if "ptr" is an empty string, use 'encoding'.
3163 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003164 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003165get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003166{
3167 int prop;
3168
3169 if (*ptr == NUL)
3170 ptr = p_enc;
3171
3172 prop = enc_canon_props(ptr);
3173 if (prop & ENC_UNICODE)
3174 {
3175 if (prop & ENC_2BYTE)
3176 {
3177 if (prop & ENC_ENDIAN_L)
3178 return FIO_UCS2 | FIO_ENDIAN_L;
3179 return FIO_UCS2;
3180 }
3181 if (prop & ENC_4BYTE)
3182 {
3183 if (prop & ENC_ENDIAN_L)
3184 return FIO_UCS4 | FIO_ENDIAN_L;
3185 return FIO_UCS4;
3186 }
3187 if (prop & ENC_2WORD)
3188 {
3189 if (prop & ENC_ENDIAN_L)
3190 return FIO_UTF16 | FIO_ENDIAN_L;
3191 return FIO_UTF16;
3192 }
3193 return FIO_UTF8;
3194 }
3195 if (prop & ENC_LATIN1)
3196 return FIO_LATIN1;
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003197 // must be ENC_DBCS, requires iconv()
Bram Moolenaar071d4272004-06-13 20:20:40 +00003198 return 0;
3199}
3200
Bram Moolenaar473952e2019-09-28 16:30:04 +02003201#if defined(MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003202/*
3203 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
3204 * for the conversion MS-Windows can do for us. Also accept "utf-8".
3205 * Used for conversion between 'encoding' and 'fileencoding'.
3206 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003207 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003208get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003209{
3210 int cp;
3211
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003212 // Cannot do this when 'encoding' is not utf-8 and not a codepage.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 if (!enc_utf8 && enc_codepage <= 0)
3214 return 0;
3215
3216 cp = encname2codepage(ptr);
3217 if (cp == 0)
3218 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003219# ifdef CP_UTF8 // VC 4.1 doesn't define CP_UTF8
Bram Moolenaar071d4272004-06-13 20:20:40 +00003220 if (STRCMP(ptr, "utf-8") == 0)
3221 cp = CP_UTF8;
3222 else
3223# endif
3224 return 0;
3225 }
3226 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
3227}
3228#endif
3229
Bram Moolenaar473952e2019-09-28 16:30:04 +02003230#if defined(MACOS_CONVERT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003231/*
3232 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
3233 * needed for the internal conversion to/from utf-8 or latin1.
3234 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003235 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003236get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003237{
3238 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
3239 && (enc_canon_props(ptr) & ENC_MACROMAN))
3240 return FIO_MACROMAN;
3241 return 0;
3242}
3243#endif
3244
3245/*
3246 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
3247 * "size" must be at least 2.
3248 * Return the name of the encoding and set "*lenp" to the length.
3249 * Returns NULL when no BOM found.
3250 */
3251 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003252check_for_bom(
3253 char_u *p,
3254 long size,
3255 int *lenp,
3256 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003257{
3258 char *name = NULL;
3259 int len = 2;
3260
3261 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00003262 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003263 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003264 name = "utf-8"; // EF BB BF
Bram Moolenaar071d4272004-06-13 20:20:40 +00003265 len = 3;
3266 }
3267 else if (p[0] == 0xff && p[1] == 0xfe)
3268 {
3269 if (size >= 4 && p[2] == 0 && p[3] == 0
3270 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
3271 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003272 name = "ucs-4le"; // FF FE 00 00
Bram Moolenaar071d4272004-06-13 20:20:40 +00003273 len = 4;
3274 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00003275 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003276 name = "ucs-2le"; // FF FE
Bram Moolenaar223a1892008-11-11 20:57:11 +00003277 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003278 // utf-16le is preferred, it also works for ucs-2le text
3279 name = "utf-16le"; // FF FE
Bram Moolenaar071d4272004-06-13 20:20:40 +00003280 }
3281 else if (p[0] == 0xfe && p[1] == 0xff
3282 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
3283 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003284 // Default to utf-16, it works also for ucs-2 text.
Bram Moolenaarffd82c52008-02-20 17:15:26 +00003285 if (flags == FIO_UCS2)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003286 name = "ucs-2"; // FE FF
Bram Moolenaarffd82c52008-02-20 17:15:26 +00003287 else
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003288 name = "utf-16"; // FE FF
Bram Moolenaar071d4272004-06-13 20:20:40 +00003289 }
3290 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
3291 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
3292 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003293 name = "ucs-4"; // 00 00 FE FF
Bram Moolenaar071d4272004-06-13 20:20:40 +00003294 len = 4;
3295 }
3296
3297 *lenp = len;
3298 return (char_u *)name;
3299}
3300
3301/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003302 * Try to find a shortname by comparing the fullname with the current
3303 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003304 * Returns "full_path" or pointer into "full_path" if shortened.
3305 */
3306 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003307shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003308{
Bram Moolenaard9462e32011-04-11 21:35:11 +02003309 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003310 char_u *p = full_path;
3311
Bram Moolenaard9462e32011-04-11 21:35:11 +02003312 dirname = alloc(MAXPATHL);
3313 if (dirname == NULL)
3314 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003315 if (mch_dirname(dirname, MAXPATHL) == OK)
3316 {
3317 p = shorten_fname(full_path, dirname);
3318 if (p == NULL || *p == NUL)
3319 p = full_path;
3320 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02003321 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003322 return p;
3323}
3324
3325/*
3326 * Try to find a shortname by comparing the fullname with the current
3327 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003328 * Returns NULL if not shorter name possible, pointer into "full_path"
3329 * otherwise.
3330 */
3331 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003332shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003333{
3334 int len;
3335 char_u *p;
3336
3337 if (full_path == NULL)
3338 return NULL;
3339 len = (int)STRLEN(dir_name);
3340 if (fnamencmp(dir_name, full_path, len) == 0)
3341 {
3342 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003343#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003344 /*
Bram Moolenaar4f974752019-02-17 17:44:42 +01003345 * MS-Windows: when a file is in the root directory, dir_name will end
3346 * in a slash, since C: by itself does not define a specific dir. In
3347 * this case p may already be correct. <negri>
Bram Moolenaar071d4272004-06-13 20:20:40 +00003348 */
3349 if (!((len > 2) && (*(p - 2) == ':')))
3350#endif
3351 {
3352 if (vim_ispathsep(*p))
3353 ++p;
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003354#ifndef VMS // the path separator is always part of the path
Bram Moolenaar071d4272004-06-13 20:20:40 +00003355 else
3356 p = NULL;
3357#endif
3358 }
3359 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003360#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003361 /*
3362 * When using a file in the current drive, remove the drive name:
3363 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
3364 * a floppy from "A:\dir" to "B:\dir".
3365 */
3366 else if (len > 3
3367 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
3368 && full_path[1] == ':'
3369 && vim_ispathsep(full_path[2]))
3370 p = full_path + 2;
3371#endif
3372 else
3373 p = NULL;
3374 return p;
3375}
3376
3377/*
Bram Moolenaara796d462018-05-01 14:30:36 +02003378 * Shorten filename of a buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003379 * When "force" is TRUE: Use full path from now on for files currently being
3380 * edited, both for file name and swap file name. Try to shorten the file
3381 * names a bit, if safe to do so.
3382 * When "force" is FALSE: Only try to shorten absolute file names.
3383 * For buffers that have buftype "nofile" or "scratch": never change the file
3384 * name.
3385 */
3386 void
Bram Moolenaara796d462018-05-01 14:30:36 +02003387shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
3388{
3389 char_u *p;
3390
3391 if (buf->b_fname != NULL
3392#ifdef FEAT_QUICKFIX
Bram Moolenaar26910de2019-06-15 19:37:15 +02003393 && !bt_nofilename(buf)
Bram Moolenaara796d462018-05-01 14:30:36 +02003394#endif
3395 && !path_with_url(buf->b_fname)
3396 && (force
3397 || buf->b_sfname == NULL
3398 || mch_isFullName(buf->b_sfname)))
3399 {
Bram Moolenaar3d6014f2018-10-11 19:27:47 +02003400 if (buf->b_sfname != buf->b_ffname)
3401 VIM_CLEAR(buf->b_sfname);
Bram Moolenaara796d462018-05-01 14:30:36 +02003402 p = shorten_fname(buf->b_ffname, dirname);
3403 if (p != NULL)
3404 {
3405 buf->b_sfname = vim_strsave(p);
3406 buf->b_fname = buf->b_sfname;
3407 }
3408 if (p == NULL || buf->b_fname == NULL)
3409 buf->b_fname = buf->b_ffname;
3410 }
3411}
3412
3413/*
3414 * Shorten filenames for all buffers.
3415 */
3416 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003417shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003418{
3419 char_u dirname[MAXPATHL];
3420 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003421
3422 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02003423 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003424 {
Bram Moolenaara796d462018-05-01 14:30:36 +02003425 shorten_buf_fname(buf, dirname, force);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003426
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003427 // Always make the swap file name a full path, a "nofile" buffer may
3428 // also have a swap file.
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003429 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003430 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00003432 redraw_tabline = TRUE;
Bram Moolenaar5a4c3082019-12-01 15:23:11 +01003433#if defined(FEAT_PROP_POPUP) && defined(FEAT_QUICKFIX)
Bram Moolenaar90f3e7a2019-08-01 22:40:44 +02003434 popup_update_preview_title();
3435#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003436}
3437
3438#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
3439 || defined(FEAT_GUI_MSWIN) \
Bram Moolenaarb3f74062020-02-26 16:16:53 +01003440 || defined(FEAT_GUI_HAIKU) \
Bram Moolenaar071d4272004-06-13 20:20:40 +00003441 || defined(PROTO)
3442/*
3443 * Shorten all filenames in "fnames[count]" by current directory.
3444 */
3445 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003446shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447{
3448 int i;
3449 char_u dirname[MAXPATHL];
3450 char_u *p;
3451
3452 if (fnames == NULL || count < 1)
3453 return;
3454 mch_dirname(dirname, sizeof(dirname));
3455 for (i = 0; i < count; ++i)
3456 {
3457 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
3458 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003459 // shorten_fname() returns pointer in given "fnames[i]". If free
3460 // "fnames[i]" first, "p" becomes invalid. So we need to copy
3461 // "p" first then free fnames[i].
Bram Moolenaar071d4272004-06-13 20:20:40 +00003462 p = vim_strsave(p);
3463 vim_free(fnames[i]);
3464 fnames[i] = p;
3465 }
3466 }
3467}
3468#endif
3469
3470/*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003471 * Add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00003472 * fo_o_h.ext for MSDOS or when shortname option set.
3473 *
3474 * Assumed that fname is a valid name found in the filesystem we assure that
3475 * the return value is a different name and ends in 'ext'.
3476 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
3477 * characters otherwise.
3478 * Space for the returned name is allocated, must be freed later.
3479 * Returns NULL when out of memory.
3480 */
3481 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003482modname(
3483 char_u *fname,
3484 char_u *ext,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003485 int prepend_dot) // may prepend a '.' to file name
Bram Moolenaar071d4272004-06-13 20:20:40 +00003486{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003487 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488 fname, ext, prepend_dot);
3489}
3490
3491 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003492buf_modname(
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003493 int shortname, // use 8.3 file name
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003494 char_u *fname,
3495 char_u *ext,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003496 int prepend_dot) // may prepend a '.' to file name
Bram Moolenaar071d4272004-06-13 20:20:40 +00003497{
3498 char_u *retval;
3499 char_u *s;
3500 char_u *e;
3501 char_u *ptr;
3502 int fnamelen, extlen;
3503
3504 extlen = (int)STRLEN(ext);
3505
3506 /*
3507 * If there is no file name we must get the name of the current directory
3508 * (we need the full path in case :cd is used).
3509 */
3510 if (fname == NULL || *fname == NUL)
3511 {
Bram Moolenaar964b3742019-05-24 18:54:09 +02003512 retval = alloc(MAXPATHL + extlen + 3);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003513 if (retval == NULL)
3514 return NULL;
3515 if (mch_dirname(retval, MAXPATHL) == FAIL ||
3516 (fnamelen = (int)STRLEN(retval)) == 0)
3517 {
3518 vim_free(retval);
3519 return NULL;
3520 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003521 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003522 {
3523 retval[fnamelen++] = PATHSEP;
3524 retval[fnamelen] = NUL;
3525 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003526 prepend_dot = FALSE; // nothing to prepend a dot to
Bram Moolenaar071d4272004-06-13 20:20:40 +00003527 }
3528 else
3529 {
3530 fnamelen = (int)STRLEN(fname);
Bram Moolenaar964b3742019-05-24 18:54:09 +02003531 retval = alloc(fnamelen + extlen + 3);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 if (retval == NULL)
3533 return NULL;
3534 STRCPY(retval, fname);
3535#ifdef VMS
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003536 vms_remove_version(retval); // we do not need versions here
Bram Moolenaar071d4272004-06-13 20:20:40 +00003537#endif
3538 }
3539
3540 /*
3541 * search backwards until we hit a '/', '\' or ':' replacing all '.'
3542 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
3543 * Then truncate what is after the '/', '\' or ':' to 8 characters for
3544 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
3545 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01003546 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003547 {
Bram Moolenaar00f148d2019-02-12 22:37:27 +01003548 if (*ext == '.' && shortname)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003549 if (*ptr == '.') // replace '.' by '_'
Bram Moolenaar071d4272004-06-13 20:20:40 +00003550 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00003552 {
3553 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003554 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00003555 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003556 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003557
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003558 // the file name has at most BASENAMELEN characters.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
3560 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00003561
3562 s = ptr + STRLEN(ptr);
3563
3564 /*
3565 * For 8.3 file names we may have to reduce the length.
3566 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003567 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003568 {
3569 /*
3570 * If there is no file name, or the file name ends in '/', and the
3571 * extension starts with '.', put a '_' before the dot, because just
3572 * ".ext" is invalid.
3573 */
3574 if (fname == NULL || *fname == NUL
3575 || vim_ispathsep(fname[STRLEN(fname) - 1]))
3576 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003577 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003578 *s++ = '_';
3579 }
3580 /*
3581 * If the extension starts with '.', truncate the base name at 8
3582 * characters
3583 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003584 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003585 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00003586 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003587 {
3588 s = ptr + 8;
3589 *s = '\0';
3590 }
3591 }
3592 /*
3593 * If the extension doesn't start with '.', and the file name
3594 * doesn't have an extension yet, append a '.'
3595 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003596 else if ((e = vim_strchr(ptr, '.')) == NULL)
3597 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 /*
3599 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00003600 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00003601 */
3602 else if ((int)STRLEN(e) + extlen > 4)
3603 s = e + 4 - extlen;
3604 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003605#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003606 /*
3607 * If there is no file name, and the extension starts with '.', put a
3608 * '_' before the dot, because just ".ext" may be invalid if it's on a
3609 * FAT partition, and on HPFS it doesn't matter.
3610 */
3611 else if ((fname == NULL || *fname == NUL) && *ext == '.')
3612 *s++ = '_';
3613#endif
3614
3615 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003616 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003617 * ext can start with '.' and cannot exceed 3 more characters.
3618 */
3619 STRCPY(s, ext);
3620
Bram Moolenaar071d4272004-06-13 20:20:40 +00003621 /*
3622 * Prepend the dot.
3623 */
Bram Moolenaar00f148d2019-02-12 22:37:27 +01003624 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003625 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003626 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003627 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00003628 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003629
3630 /*
3631 * Check that, after appending the extension, the file name is really
3632 * different.
3633 */
3634 if (fname != NULL && STRCMP(fname, retval) == 0)
3635 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003636 // we search for a character that can be replaced by '_'
Bram Moolenaar071d4272004-06-13 20:20:40 +00003637 while (--s >= ptr)
3638 {
3639 if (*s != '_')
3640 {
3641 *s = '_';
3642 break;
3643 }
3644 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003645 if (s < ptr) // fname was "________.<ext>", how tricky!
Bram Moolenaar071d4272004-06-13 20:20:40 +00003646 *ptr = 'v';
3647 }
3648 return retval;
3649}
3650
3651/*
3652 * Like fgets(), but if the file line is too long, it is truncated and the
3653 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01003654 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003655 */
3656 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003657vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003658{
3659 char *eof;
3660#define FGETS_SIZE 200
3661 char tbuf[FGETS_SIZE];
3662
3663 buf[size - 2] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003664 eof = fgets((char *)buf, size, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003665 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
3666 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003667 buf[size - 1] = NUL; // Truncate the line
Bram Moolenaar071d4272004-06-13 20:20:40 +00003668
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003669 // Now throw away the rest of the line:
Bram Moolenaar071d4272004-06-13 20:20:40 +00003670 do
3671 {
3672 tbuf[FGETS_SIZE - 2] = NUL;
Bram Moolenaar42335f52018-09-13 15:33:43 +02003673 vim_ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003674 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
3675 }
3676 return (eof == NULL);
3677}
3678
Bram Moolenaar071d4272004-06-13 20:20:40 +00003679/*
3680 * rename() only works if both files are on the same file system, this
3681 * function will (attempts to?) copy the file across if rename fails -- webb
3682 * Return -1 for failure, 0 for success.
3683 */
3684 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003685vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003686{
3687 int fd_in;
3688 int fd_out;
3689 int n;
3690 char *errmsg = NULL;
3691 char *buffer;
3692#ifdef AMIGA
3693 BPTR flock;
3694#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02003695 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00003696 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003697#ifdef HAVE_ACL
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003698 vim_acl_T acl; // ACL from original file
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003699#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003700 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003701
3702 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003703 * When the names are identical, there is nothing to do. When they refer
3704 * to the same file (ignoring case and slash/backslash differences) but
3705 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003706 */
3707 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003708 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01003709 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003710 use_tmp_file = TRUE;
3711 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003712 return 0;
3713 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003714
3715 /*
3716 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
3717 */
3718 if (mch_stat((char *)from, &st) < 0)
3719 return -1;
3720
Bram Moolenaar3576da72008-12-30 15:15:57 +00003721#ifdef UNIX
3722 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02003723 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00003724
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003725 // It's possible for the source and destination to be the same file.
3726 // This happens when "from" and "to" differ in case and are on a FAT32
3727 // filesystem. In that case go through a temp file name.
Bram Moolenaar3576da72008-12-30 15:15:57 +00003728 if (mch_stat((char *)to, &st_to) >= 0
3729 && st.st_dev == st_to.st_dev
3730 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003731 use_tmp_file = TRUE;
3732 }
3733#endif
Bram Moolenaar4f974752019-02-17 17:44:42 +01003734#ifdef MSWIN
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003735 {
3736 BY_HANDLE_FILE_INFORMATION info1, info2;
3737
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003738 // It's possible for the source and destination to be the same file.
3739 // In that case go through a temp file name. This makes rename("foo",
3740 // "./foo") a no-op (in a complicated way).
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003741 if (win32_fileinfo(from, &info1) == FILEINFO_OK
3742 && win32_fileinfo(to, &info2) == FILEINFO_OK
3743 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
3744 && info1.nFileIndexHigh == info2.nFileIndexHigh
3745 && info1.nFileIndexLow == info2.nFileIndexLow)
3746 use_tmp_file = TRUE;
3747 }
3748#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003749
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003750 if (use_tmp_file)
3751 {
3752 char tempname[MAXPATHL + 1];
3753
3754 /*
3755 * Find a name that doesn't exist and is in the same directory.
3756 * Rename "from" to "tempname" and then rename "tempname" to "to".
3757 */
3758 if (STRLEN(from) >= MAXPATHL - 5)
3759 return -1;
3760 STRCPY(tempname, from);
3761 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00003762 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003763 sprintf((char *)gettail((char_u *)tempname), "%d", n);
3764 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00003765 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003766 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00003767 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003768 if (mch_rename(tempname, (char *)to) == 0)
3769 return 0;
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003770 // Strange, the second step failed. Try moving the
3771 // file back and return failure.
Bram Moolenaar97a6c6a2021-05-03 19:49:51 +02003772 (void)mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00003773 return -1;
3774 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003775 // If it fails for one temp name it will most likely fail
3776 // for any temp name, give up.
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003777 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00003778 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00003779 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003780 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00003781 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00003782
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 /*
3784 * Delete the "to" file, this is required on some systems to make the
3785 * mch_rename() work, on other systems it makes sure that we don't have
3786 * two files when the mch_rename() fails.
3787 */
3788
3789#ifdef AMIGA
3790 /*
3791 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
3792 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00003793 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00003794 * deleting the "from" file (horror!) we lock it during the remove.
3795 *
3796 * When used for making a backup before writing the file: This should not
3797 * happen with ":w", because startscript() should detect this problem and
3798 * set buf->b_shortname, causing modname() to return a correct ".bak" file
3799 * name. This problem does exist with ":w filename", but then the
3800 * original file will be somewhere else so the backup isn't really
3801 * important. If autoscripting is off the rename may fail.
3802 */
3803 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
3804#endif
3805 mch_remove(to);
3806#ifdef AMIGA
3807 if (flock)
3808 UnLock(flock);
3809#endif
3810
3811 /*
3812 * First try a normal rename, return if it works.
3813 */
3814 if (mch_rename((char *)from, (char *)to) == 0)
3815 return 0;
3816
3817 /*
3818 * Rename() failed, try copying the file.
3819 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00003820 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003821#ifdef HAVE_ACL
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003822 // For systems that support ACL: get the ACL from the original file.
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003823 acl = mch_get_acl(from);
3824#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003825 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
3826 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003827 {
3828#ifdef HAVE_ACL
3829 mch_free_acl(acl);
3830#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003831 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003832 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00003833
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003834 // Create the new file with same permissions as the original.
Bram Moolenaara5792f52005-11-23 21:25:05 +00003835 fd_out = mch_open((char *)to,
3836 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003837 if (fd_out == -1)
3838 {
3839 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003840#ifdef HAVE_ACL
3841 mch_free_acl(acl);
3842#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003843 return -1;
3844 }
3845
Bram Moolenaar473952e2019-09-28 16:30:04 +02003846 buffer = alloc(WRITEBUFSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003847 if (buffer == NULL)
3848 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003849 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003850 close(fd_in);
3851#ifdef HAVE_ACL
3852 mch_free_acl(acl);
3853#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003854 return -1;
3855 }
3856
Bram Moolenaar473952e2019-09-28 16:30:04 +02003857 while ((n = read_eintr(fd_in, buffer, WRITEBUFSIZE)) > 0)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003858 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003859 {
3860 errmsg = _("E208: Error writing to \"%s\"");
3861 break;
3862 }
3863
3864 vim_free(buffer);
3865 close(fd_in);
3866 if (close(fd_out) < 0)
3867 errmsg = _("E209: Error closing \"%s\"");
3868 if (n < 0)
3869 {
3870 errmsg = _("E210: Error reading \"%s\"");
3871 to = from;
3872 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003873#ifndef UNIX // for Unix mch_open() already set the permission
Bram Moolenaar9be038d2005-03-08 22:34:32 +00003874 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00003875#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003876#ifdef HAVE_ACL
3877 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003878 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003879#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003880#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01003881 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01003882#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003883 if (errmsg != NULL)
3884 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003885 semsg(errmsg, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003886 return -1;
3887 }
3888 mch_remove(from);
3889 return 0;
3890}
3891
3892static int already_warned = FALSE;
3893
3894/*
3895 * Check if any not hidden buffer has been changed.
3896 * Postpone the check if there are characters in the stuff buffer, a global
3897 * command is being executed, a mapping is being executed or an autocommand is
3898 * busy.
3899 * Returns TRUE if some message was written (screen should be redrawn and
3900 * cursor positioned).
3901 */
3902 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003903check_timestamps(
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003904 int focus) // called for GUI focus event
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905{
3906 buf_T *buf;
3907 int didit = 0;
3908 int n;
3909
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003910 // Don't check timestamps while system() or another low-level function may
3911 // cause us to lose and gain focus.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003912 if (no_check_timestamps > 0)
3913 return FALSE;
3914
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003915 // Avoid doing a check twice. The OK/Reload dialog can cause a focus
3916 // event and we would keep on checking if the file is steadily growing.
3917 // Do check again after typing something.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003918 if (focus && did_check_timestamps)
3919 {
3920 need_check_timestamps = TRUE;
3921 return FALSE;
3922 }
3923
3924 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01003925 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003926 need_check_timestamps = TRUE; // check later
Bram Moolenaar071d4272004-06-13 20:20:40 +00003927 else
3928 {
3929 ++no_wait_return;
3930 did_check_timestamps = TRUE;
3931 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02003932 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003933 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003934 // Only check buffers in a window.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003935 if (buf->b_nwindows > 0)
3936 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003937 bufref_T bufref;
3938
3939 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003940 n = buf_check_timestamp(buf, focus);
3941 if (didit < n)
3942 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003943 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003944 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003945 // Autocommands have removed the buffer, start at the
3946 // first one again.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003947 buf = firstbuf;
3948 continue;
3949 }
3950 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003951 }
3952 --no_wait_return;
3953 need_check_timestamps = FALSE;
3954 if (need_wait_return && didit == 2)
3955 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003956 // make sure msg isn't overwritten
Bram Moolenaar32526b32019-01-19 17:43:09 +01003957 msg_puts("\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003958 out_flush();
3959 }
3960 }
3961 return didit;
3962}
3963
3964/*
3965 * Move all the lines from buffer "frombuf" to buffer "tobuf".
3966 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
3967 * empty.
3968 */
3969 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003970move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003971{
3972 buf_T *tbuf = curbuf;
3973 int retval = OK;
3974 linenr_T lnum;
3975 char_u *p;
3976
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003977 // Copy the lines in "frombuf" to "tobuf".
Bram Moolenaar071d4272004-06-13 20:20:40 +00003978 curbuf = tobuf;
3979 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
3980 {
3981 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
3982 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
3983 {
3984 vim_free(p);
3985 retval = FAIL;
3986 break;
3987 }
3988 vim_free(p);
3989 }
3990
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003991 // Delete all the lines in "frombuf".
Bram Moolenaar071d4272004-06-13 20:20:40 +00003992 if (retval != FAIL)
3993 {
3994 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00003995 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
Bram Moolenaarca70c072020-05-30 20:30:46 +02003996 if (ml_delete(lnum) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003997 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01003998 // Oops! We could try putting back the saved lines, but that
3999 // might fail again...
Bram Moolenaar071d4272004-06-13 20:20:40 +00004000 retval = FAIL;
4001 break;
4002 }
4003 }
4004
4005 curbuf = tbuf;
4006 return retval;
4007}
4008
4009/*
4010 * Check if buffer "buf" has been changed.
4011 * Also check if the file for a new buffer unexpectedly appeared.
4012 * return 1 if a changed buffer was found.
4013 * return 2 if a message has been displayed.
4014 * return 0 otherwise.
4015 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004016 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004017buf_check_timestamp(
4018 buf_T *buf,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004019 int focus UNUSED) // called for GUI focus event
Bram Moolenaar071d4272004-06-13 20:20:40 +00004020{
Bram Moolenaar8767f522016-07-01 17:17:39 +02004021 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004022 int stat_res;
4023 int retval = 0;
4024 char_u *path;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004025 char *tbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004026 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00004027 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00004028 int helpmesg = FALSE;
4029 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004030 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004031#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
4032 int can_reload = FALSE;
4033#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02004034 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004035 int orig_mode = buf->b_orig_mode;
4036#ifdef FEAT_GUI
4037 int save_mouse_correct = need_mouse_correct;
4038#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004039 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004040 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004041#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004042 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004043#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004044 bufref_T bufref;
4045
4046 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004047
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004048 // If there is no file name, the buffer is not loaded, 'buftype' is
4049 // set, we are in the middle of a save or being called recursively: ignore
4050 // this buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004051 if (buf->b_ffname == NULL
4052 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar91335e52018-08-01 17:53:12 +02004053 || !bt_normal(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004054 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00004055 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00004056#ifdef FEAT_NETBEANS_INTG
4057 || isNetbeansBuffer(buf)
4058#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02004059#ifdef FEAT_TERMINAL
4060 || buf->b_term != NULL
4061#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004062 )
4063 return 0;
4064
4065 if ( !(buf->b_flags & BF_NOTEDITED)
4066 && buf->b_mtime != 0
4067 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
4068 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02004069 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004070#ifdef HAVE_ST_MODE
4071 || (int)st.st_mode != buf->b_orig_mode
4072#else
4073 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
4074#endif
4075 ))
4076 {
Bram Moolenaar674e2bd2019-07-31 20:21:01 +02004077 long prev_b_mtime = buf->b_mtime;
4078
Bram Moolenaar071d4272004-06-13 20:20:40 +00004079 retval = 1;
4080
Bram Moolenaar386bc822018-07-07 18:34:12 +02004081 // set b_mtime to stop further warnings (e.g., when executing
4082 // FileChangedShell autocmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004083 if (stat_res < 0)
4084 {
Bram Moolenaar8239c622019-05-24 16:46:01 +02004085 // Check the file again later to see if it re-appears.
4086 buf->b_mtime = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004087 buf->b_orig_size = 0;
4088 buf->b_orig_mode = 0;
4089 }
4090 else
4091 buf_store_time(buf, &st, buf->b_ffname);
4092
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004093 // Don't do anything for a directory. Might contain the file
4094 // explorer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 if (mch_isdir(buf->b_fname))
4096 ;
4097
4098 /*
4099 * If 'autoread' is set, the buffer has no changes and the file still
4100 * exists, reload the buffer. Use the buffer-local option value if it
4101 * was set, the global option value otherwise.
4102 */
4103 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
4104 && !bufIsChanged(buf) && stat_res >= 0)
4105 reload = TRUE;
4106 else
4107 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004108 if (stat_res < 0)
4109 reason = "deleted";
4110 else if (bufIsChanged(buf))
4111 reason = "conflict";
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01004112 /*
4113 * Check if the file contents really changed to avoid giving a
4114 * warning when only the timestamp was set (e.g., checked out of
4115 * CVS). Always warn when the buffer was changed.
4116 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004117 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
4118 reason = "changed";
4119 else if (orig_mode != buf->b_orig_mode)
4120 reason = "mode";
4121 else
4122 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00004123
4124 /*
4125 * Only give the warning if there are no FileChangedShell
4126 * autocommands.
4127 * Avoid being called recursively by setting "busy".
4128 */
4129 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004130#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004131 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
4132 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004133#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00004134 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004135 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
4136 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00004137 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004138 busy = FALSE;
4139 if (n)
4140 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004141 if (!bufref_valid(&bufref))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004142 emsg(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004143#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004144 s = get_vim_var_str(VV_FCS_CHOICE);
4145 if (STRCMP(s, "reload") == 0 && *reason != 'd')
4146 reload = TRUE;
4147 else if (STRCMP(s, "ask") == 0)
4148 n = FALSE;
4149 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004150#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004151 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004152 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004153 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004154 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004155 if (*reason == 'd')
Bram Moolenaar674e2bd2019-07-31 20:21:01 +02004156 {
4157 // Only give the message once.
4158 if (prev_b_mtime != -1)
4159 mesg = _("E211: File \"%s\" no longer available");
4160 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 else
4162 {
4163 helpmesg = TRUE;
4164#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
4165 can_reload = TRUE;
4166#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004167 if (reason[2] == 'n')
4168 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004169 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004170 mesg2 = _("See \":help W12\" for more info.");
4171 }
4172 else if (reason[1] == 'h')
4173 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004174 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004175 mesg2 = _("See \":help W11\" for more info.");
4176 }
4177 else if (*reason == 'm')
4178 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004179 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004180 mesg2 = _("See \":help W16\" for more info.");
4181 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00004182 else
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004183 // Only timestamp changed, store it to avoid a warning
4184 // in check_mtime() later.
Bram Moolenaar85388b52009-06-24 09:58:32 +00004185 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004186 }
4187 }
4188 }
4189
4190 }
4191 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
4192 && vim_fexists(buf->b_ffname))
4193 {
4194 retval = 1;
4195 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
4196 buf->b_flags |= BF_NEW_W;
4197#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
4198 can_reload = TRUE;
4199#endif
4200 }
4201
4202 if (mesg != NULL)
4203 {
4204 path = home_replace_save(buf, buf->b_fname);
4205 if (path != NULL)
4206 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004207 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004208 mesg2 = "";
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004209 tbuf = alloc(STRLEN(path) + STRLEN(mesg) + STRLEN(mesg2) + 2);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004210 sprintf(tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00004211#ifdef FEAT_EVAL
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004212 // Set warningmsg here, before the unimportant and output-specific
4213 // mesg2 has been appended.
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004214 set_vim_var_string(VV_WARNINGMSG, (char_u *)tbuf, -1);
Bram Moolenaar496c5262009-03-18 14:42:00 +00004215#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004216#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
4217 if (can_reload)
4218 {
4219 if (*mesg2 != NUL)
4220 {
4221 STRCAT(tbuf, "\n");
4222 STRCAT(tbuf, mesg2);
4223 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004224 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"),
4225 (char_u *)tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01004226 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004227 reload = TRUE;
4228 }
4229 else
4230#endif
4231 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
4232 {
4233 if (*mesg2 != NUL)
4234 {
4235 STRCAT(tbuf, "; ");
4236 STRCAT(tbuf, mesg2);
4237 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004238 emsg(tbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004239 retval = 2;
4240 }
4241 else
4242 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004243 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004244 {
4245 msg_start();
Bram Moolenaar32526b32019-01-19 17:43:09 +01004246 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004247 if (*mesg2 != NUL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01004248 msg_puts_attr(mesg2, HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004249 msg_clr_eos();
4250 (void)msg_end();
Bram Moolenaar28ee8922020-10-28 20:20:00 +01004251 if (emsg_silent == 0 && !in_assert_fails)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004252 {
4253 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004254#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004255 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004256#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004257 // give the user some time to think about it
Bram Moolenaareda1da02019-11-17 17:06:33 +01004258 ui_delay(1004L, TRUE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004259
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004260 // don't redraw and erase the message
Bram Moolenaar071d4272004-06-13 20:20:40 +00004261 redraw_cmdline = FALSE;
4262 }
4263 }
4264 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004265 }
4266
4267 vim_free(path);
4268 vim_free(tbuf);
4269 }
4270 }
4271
4272 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02004273 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004274 // Reload the buffer.
Bram Moolenaar316059c2006-01-14 21:18:42 +00004275 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02004276#ifdef FEAT_PERSISTENT_UNDO
4277 if (buf->b_p_udf && buf->b_ffname != NULL)
4278 {
4279 char_u hash[UNDO_HASH_SIZE];
4280 buf_T *save_curbuf = curbuf;
4281
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004282 // Any existing undo file is unusable, write it now.
Bram Moolenaar465748e2012-08-29 18:50:54 +02004283 curbuf = buf;
4284 u_compute_hash(hash);
4285 u_write_undo(NULL, FALSE, buf, hash);
4286 curbuf = save_curbuf;
4287 }
4288#endif
4289 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004290
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004291 // Trigger FileChangedShell when the file was changed in any way.
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004292 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00004293 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
4294 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004295#ifdef FEAT_GUI
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004296 // restore this in case an autocommand has set it; it would break
4297 // 'mousefocus'
Bram Moolenaar071d4272004-06-13 20:20:40 +00004298 need_mouse_correct = save_mouse_correct;
4299#endif
4300
4301 return retval;
4302}
4303
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004304/*
4305 * Reload a buffer that is already loaded.
4306 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00004307 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
4308 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004309 */
4310 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004311buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004312{
4313 exarg_T ea;
4314 pos_T old_cursor;
4315 linenr_T old_topline;
4316 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004317 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004318 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004319 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004320 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004321 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004322
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004323 // set curwin/curbuf for "buf" and save some things
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004324 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004325
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004326 // We only want to read the text from the file, not reset the syntax
4327 // highlighting, clear marks, diff status, etc. Force the fileformat
4328 // and encoding to be the same.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004329 if (prep_exarg(&ea, buf) == OK)
4330 {
4331 old_cursor = curwin->w_cursor;
4332 old_topline = curwin->w_topline;
4333
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02004334 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004335 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004336 // Save all the text, so that the reload can be undone.
4337 // Sync first so that this is a separate undo-able action.
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004338 u_sync(FALSE);
4339 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
4340 flags |= READ_KEEP_UNDO;
4341 }
4342
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004343 /*
4344 * To behave like when a new file is edited (matters for
4345 * BufReadPost autocommands) we first need to delete the current
4346 * buffer contents. But if reading the file fails we should keep
4347 * the old contents. Can't use memory only, the file might be
4348 * too big. Use a hidden buffer to move the buffer contents to.
4349 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01004350 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004351 savebuf = NULL;
4352 else
4353 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004354 // Allocate a buffer without putting it in the buffer list.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004355 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004356 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00004357 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004358 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004359 // Open the memline.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004360 curbuf = savebuf;
4361 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00004362 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004363 curbuf = buf;
4364 curwin->w_buffer = buf;
4365 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00004366 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004367 || move_lines(buf, savebuf) == FAIL)
4368 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004369 semsg(_("E462: Could not prepare for reloading \"%s\""),
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004370 buf->b_fname);
4371 saved = FAIL;
4372 }
4373 }
4374
4375 if (saved == OK)
4376 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004377 curbuf->b_flags |= BF_CHECK_RO; // check for RO again
4378 keep_filetype = TRUE; // don't detect 'filetype'
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004379 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
4380 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01004381 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004382 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004383#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004384 if (!aborting())
4385#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004386 semsg(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004387 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004388 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004389 // Put the text back from the save buffer. First
4390 // delete any lines that readfile() added.
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01004391 while (!BUFEMPTY())
Bram Moolenaarca70c072020-05-30 20:30:46 +02004392 if (ml_delete(buf->b_ml.ml_line_count) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004393 break;
4394 (void)move_lines(savebuf, buf);
4395 }
4396 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004397 else if (buf == curbuf) // "buf" still valid
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004398 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004399 // Mark the buffer as unmodified and free undo info.
Bram Moolenaarc024b462019-06-08 18:07:21 +02004400 unchanged(buf, TRUE, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004401 if ((flags & READ_KEEP_UNDO) == 0)
4402 {
4403 u_blockfree(buf);
4404 u_clearall(buf);
4405 }
4406 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02004407 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004408 // Mark all undo states as changed.
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004409 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02004410 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004411 }
4412 }
4413 vim_free(ea.cmd);
4414
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004415 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004416 wipe_buffer(savebuf, FALSE);
4417
4418#ifdef FEAT_DIFF
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004419 // Invalidate diff info if necessary.
Bram Moolenaar8424a622006-04-19 21:23:36 +00004420 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004421#endif
4422
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004423 // Restore the topline and cursor position and check it (lines may
4424 // have been removed).
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004425 if (old_topline > curbuf->b_ml.ml_line_count)
4426 curwin->w_topline = curbuf->b_ml.ml_line_count;
4427 else
4428 curwin->w_topline = old_topline;
4429 curwin->w_cursor = old_cursor;
4430 check_cursor();
4431 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004432 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004433#ifdef FEAT_FOLDING
4434 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00004435 win_T *wp;
4436 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004437
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004438 // Update folds unless they are defined manually.
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00004439 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004440 if (wp->w_buffer == curwin->w_buffer
4441 && !foldmethodIsManual(wp))
4442 foldUpdateAll(wp);
4443 }
4444#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004445 // If the mode didn't change and 'readonly' was set, keep the old
4446 // value; the user probably used the ":view" command. But don't
4447 // reset it, might have had a read error.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004448 if (orig_mode == curbuf->b_orig_mode)
4449 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01004450
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004451 // Modelines must override settings done by autocommands.
Bram Moolenaar52f85b72013-01-30 14:13:56 +01004452 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004453 }
4454
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004455 // restore curwin/curbuf and a few other things
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004456 aucmd_restbuf(&aco);
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004457 // Careful: autocommands may have made "buf" invalid!
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004458}
4459
Bram Moolenaar071d4272004-06-13 20:20:40 +00004460 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02004461buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004462{
4463 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02004464 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004465#ifdef HAVE_ST_MODE
4466 buf->b_orig_mode = (int)st->st_mode;
4467#else
4468 buf->b_orig_mode = mch_getperm(fname);
4469#endif
4470}
4471
4472/*
4473 * Adjust the line with missing eol, used for the next write.
4474 * Used for do_filter(), when the input lines for the filter are deleted.
4475 */
4476 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004477write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004478{
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004479 if (curbuf->b_no_eol_lnum != 0) // only if there is a missing eol
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004480 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004481}
4482
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004483// Subfuncions for readdirex()
4484#ifdef FEAT_EVAL
4485# ifdef MSWIN
4486 static char_u *
4487getfpermwfd(WIN32_FIND_DATAW *wfd, char_u *perm)
4488{
4489 stat_T st;
4490 unsigned short st_mode;
4491 DWORD flag = wfd->dwFileAttributes;
4492 WCHAR *wp;
4493
4494 st_mode = (flag & FILE_ATTRIBUTE_DIRECTORY)
4495 ? (_S_IFDIR | _S_IEXEC) : _S_IFREG;
4496 st_mode |= (flag & FILE_ATTRIBUTE_READONLY)
4497 ? _S_IREAD : (_S_IREAD | _S_IWRITE);
4498
4499 wp = wcsrchr(wfd->cFileName, L'.');
4500 if (wp != NULL)
4501 {
4502 if (_wcsicmp(wp, L".exe") == 0 ||
4503 _wcsicmp(wp, L".com") == 0 ||
4504 _wcsicmp(wp, L".cmd") == 0 ||
4505 _wcsicmp(wp, L".bat") == 0)
4506 st_mode |= _S_IEXEC;
4507 }
4508
4509 // Copy user bits to group/other.
4510 st_mode |= (st_mode & 0700) >> 3;
4511 st_mode |= (st_mode & 0700) >> 6;
4512
4513 st.st_mode = st_mode;
4514 return getfpermst(&st, perm);
4515}
4516
4517 static char_u *
4518getftypewfd(WIN32_FIND_DATAW *wfd)
4519{
4520 DWORD flag = wfd->dwFileAttributes;
4521 DWORD tag = wfd->dwReserved0;
4522
4523 if (flag & FILE_ATTRIBUTE_REPARSE_POINT)
4524 {
4525 if (tag == IO_REPARSE_TAG_MOUNT_POINT)
4526 return (char_u*)"junction";
4527 else if (tag == IO_REPARSE_TAG_SYMLINK)
4528 {
4529 if (flag & FILE_ATTRIBUTE_DIRECTORY)
4530 return (char_u*)"linkd";
4531 else
4532 return (char_u*)"link";
4533 }
4534 return (char_u*)"reparse"; // unknown reparse point type
4535 }
4536 if (flag & FILE_ATTRIBUTE_DIRECTORY)
4537 return (char_u*)"dir";
4538 else
4539 return (char_u*)"file";
4540}
4541
4542 static dict_T *
4543create_readdirex_item(WIN32_FIND_DATAW *wfd)
4544{
4545 dict_T *item;
4546 char_u *p;
4547 varnumber_T size, time;
4548 char_u permbuf[] = "---------";
4549
4550 item = dict_alloc();
4551 if (item == NULL)
4552 return NULL;
4553 item->dv_refcount++;
4554
4555 p = utf16_to_enc(wfd->cFileName, NULL);
4556 if (p == NULL)
4557 goto theend;
4558 if (dict_add_string(item, "name", p) == FAIL)
4559 {
4560 vim_free(p);
4561 goto theend;
4562 }
4563 vim_free(p);
4564
4565 size = (((varnumber_T)wfd->nFileSizeHigh) << 32) | wfd->nFileSizeLow;
4566 if (dict_add_number(item, "size", size) == FAIL)
4567 goto theend;
4568
4569 // Convert FILETIME to unix time.
4570 time = (((((varnumber_T)wfd->ftLastWriteTime.dwHighDateTime) << 32) |
4571 wfd->ftLastWriteTime.dwLowDateTime)
4572 - 116444736000000000) / 10000000;
4573 if (dict_add_number(item, "time", time) == FAIL)
4574 goto theend;
4575
4576 if (dict_add_string(item, "type", getftypewfd(wfd)) == FAIL)
4577 goto theend;
4578 if (dict_add_string(item, "perm", getfpermwfd(wfd, permbuf)) == FAIL)
4579 goto theend;
4580
4581 if (dict_add_string(item, "user", (char_u*)"") == FAIL)
4582 goto theend;
4583 if (dict_add_string(item, "group", (char_u*)"") == FAIL)
4584 goto theend;
4585
4586 return item;
4587
4588theend:
4589 dict_unref(item);
4590 return NULL;
4591}
4592# else
4593 static dict_T *
4594create_readdirex_item(char_u *path, char_u *name)
4595{
4596 dict_T *item;
4597 char *p;
4598 size_t len;
4599 stat_T st;
4600 int ret, link = FALSE;
4601 varnumber_T size;
4602 char_u permbuf[] = "---------";
Bram Moolenaarab540322020-06-10 15:55:36 +02004603 char_u *q = NULL;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004604 struct passwd *pw;
4605 struct group *gr;
4606
4607 item = dict_alloc();
4608 if (item == NULL)
4609 return NULL;
4610 item->dv_refcount++;
4611
4612 len = STRLEN(path) + 1 + STRLEN(name) + 1;
4613 p = alloc(len);
4614 if (p == NULL)
4615 goto theend;
4616 vim_snprintf(p, len, "%s/%s", path, name);
4617 ret = mch_lstat(p, &st);
4618 if (ret >= 0 && S_ISLNK(st.st_mode))
4619 {
4620 link = TRUE;
4621 ret = mch_stat(p, &st);
Bram Moolenaarab540322020-06-10 15:55:36 +02004622 if (ret < 0)
4623 q = (char_u*)"link";
4624
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004625 }
4626 vim_free(p);
4627
4628 if (dict_add_string(item, "name", name) == FAIL)
4629 goto theend;
4630
4631 if (ret >= 0)
4632 {
4633 size = (varnumber_T)st.st_size;
4634 if (S_ISDIR(st.st_mode))
4635 size = 0;
4636 // non-perfect check for overflow
Bram Moolenaar441d60e2020-06-02 22:19:50 +02004637 else if ((off_T)size != (off_T)st.st_size)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004638 size = -2;
4639 if (dict_add_number(item, "size", size) == FAIL)
4640 goto theend;
4641 if (dict_add_number(item, "time", (varnumber_T)st.st_mtime) == FAIL)
4642 goto theend;
4643
4644 if (link)
4645 {
4646 if (S_ISDIR(st.st_mode))
4647 q = (char_u*)"linkd";
4648 else
4649 q = (char_u*)"link";
4650 }
4651 else
4652 q = getftypest(&st);
4653 if (dict_add_string(item, "type", q) == FAIL)
4654 goto theend;
4655 if (dict_add_string(item, "perm", getfpermst(&st, permbuf)) == FAIL)
4656 goto theend;
4657
4658 pw = getpwuid(st.st_uid);
4659 if (pw == NULL)
4660 q = (char_u*)"";
4661 else
4662 q = (char_u*)pw->pw_name;
4663 if (dict_add_string(item, "user", q) == FAIL)
4664 goto theend;
Bram Moolenaar82c38fe2021-01-04 10:47:26 +01004665# if !defined(VMS) || (defined(VMS) && defined(HAVE_XOS_R_H))
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004666 gr = getgrgid(st.st_gid);
4667 if (gr == NULL)
4668 q = (char_u*)"";
4669 else
4670 q = (char_u*)gr->gr_name;
Bram Moolenaar82c38fe2021-01-04 10:47:26 +01004671# endif
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004672 if (dict_add_string(item, "group", q) == FAIL)
4673 goto theend;
4674 }
4675 else
4676 {
4677 if (dict_add_number(item, "size", -1) == FAIL)
4678 goto theend;
4679 if (dict_add_number(item, "time", -1) == FAIL)
4680 goto theend;
Bram Moolenaarab540322020-06-10 15:55:36 +02004681 if (dict_add_string(item, "type", q == NULL ? (char_u*)"" : q) == FAIL)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004682 goto theend;
4683 if (dict_add_string(item, "perm", (char_u*)"") == FAIL)
4684 goto theend;
4685 if (dict_add_string(item, "user", (char_u*)"") == FAIL)
4686 goto theend;
4687 if (dict_add_string(item, "group", (char_u*)"") == FAIL)
4688 goto theend;
4689 }
4690 return item;
4691
4692theend:
4693 dict_unref(item);
4694 return NULL;
4695}
4696# endif
4697
4698 static int
4699compare_readdirex_item(const void *p1, const void *p2)
4700{
4701 char_u *name1, *name2;
4702
4703 name1 = dict_get_string(*(dict_T**)p1, (char_u*)"name", FALSE);
4704 name2 = dict_get_string(*(dict_T**)p2, (char_u*)"name", FALSE);
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02004705 if (readdirex_sort == READDIR_SORT_BYTE)
4706 return STRCMP(name1, name2);
4707 else if (readdirex_sort == READDIR_SORT_IC)
4708 return STRICMP(name1, name2);
4709 else
4710 return STRCOLL(name1, name2);
4711}
4712
4713 static int
4714compare_readdir_item(const void *s1, const void *s2)
4715{
4716 if (readdirex_sort == READDIR_SORT_BYTE)
4717 return STRCMP(*(char **)s1, *(char **)s2);
4718 else if (readdirex_sort == READDIR_SORT_IC)
4719 return STRICMP(*(char **)s1, *(char **)s2);
4720 else
4721 return STRCOLL(*(char **)s1, *(char **)s2);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004722}
4723#endif
4724
Bram Moolenaarda440d22016-01-16 21:27:23 +01004725#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
4726/*
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004727 * Core part of "readdir()" and "readdirex()" function.
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004728 * Retrieve the list of files/directories of "path" into "gap".
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004729 * If "withattr" is TRUE, retrieve the names and their attributes.
4730 * If "withattr" is FALSE, retrieve the names only.
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004731 * Return OK for success, FAIL for failure.
4732 */
4733 int
4734readdir_core(
4735 garray_T *gap,
4736 char_u *path,
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004737 int withattr UNUSED,
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004738 void *context,
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02004739 int (*checkitem)(void *context, void *item),
4740 int sort)
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004741{
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004742 int failed = FALSE;
4743 char_u *p;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01004744# ifdef MSWIN
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004745 char_u *buf;
4746 int ok;
4747 HANDLE hFind = INVALID_HANDLE_VALUE;
4748 WIN32_FIND_DATAW wfd;
4749 WCHAR *wn = NULL; // UTF-16 name, NULL when not used.
Bram Moolenaar80147dd2020-02-04 22:32:59 +01004750# else
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004751 DIR *dirp;
4752 struct dirent *dp;
Bram Moolenaar80147dd2020-02-04 22:32:59 +01004753# endif
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004754
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004755 ga_init2(gap, (int)sizeof(void *), 20);
4756
4757# ifdef FEAT_EVAL
4758# define FREE_ITEM(item) do { \
4759 if (withattr) \
4760 dict_unref((dict_T*)item); \
4761 else \
4762 vim_free(item); \
4763 } while (0)
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02004764
4765 readdirex_sort = READDIR_SORT_BYTE;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004766# else
4767# define FREE_ITEM(item) vim_free(item)
4768# endif
4769
4770# ifdef MSWIN
4771 buf = alloc(MAXPATHL);
4772 if (buf == NULL)
4773 return FAIL;
4774 STRNCPY(buf, path, MAXPATHL-5);
4775 p = buf + STRLEN(buf);
4776 MB_PTR_BACK(buf, p);
4777 if (*p == '\\' || *p == '/')
4778 *p = NUL;
4779 STRCAT(p, "\\*");
4780
4781 wn = enc_to_utf16(buf, NULL);
4782 if (wn != NULL)
4783 hFind = FindFirstFileW(wn, &wfd);
4784 ok = (hFind != INVALID_HANDLE_VALUE);
4785 if (!ok)
4786 {
4787 failed = TRUE;
Bram Moolenaaraab9fad2020-10-11 14:28:11 +02004788 semsg(_(e_notopen), path);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004789 }
4790 else
4791 {
4792 while (ok)
4793 {
4794 int ignore;
4795 void *item;
4796 WCHAR *wp;
4797
4798 wp = wfd.cFileName;
4799 ignore = wp[0] == L'.' &&
4800 (wp[1] == NUL ||
4801 (wp[1] == L'.' && wp[2] == NUL));
Bram Moolenaarab540322020-06-10 15:55:36 +02004802 if (ignore)
4803 {
4804 ok = FindNextFileW(hFind, &wfd);
4805 continue;
4806 }
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004807# ifdef FEAT_EVAL
4808 if (withattr)
4809 item = (void*)create_readdirex_item(&wfd);
4810 else
4811# endif
4812 item = (void*)utf16_to_enc(wfd.cFileName, NULL);
4813 if (item == NULL)
4814 {
4815 failed = TRUE;
4816 break;
4817 }
4818
4819 if (!ignore && checkitem != NULL)
4820 {
4821 int r = checkitem(context, item);
4822
4823 if (r < 0)
4824 {
4825 FREE_ITEM(item);
4826 break;
4827 }
4828 if (r == 0)
4829 ignore = TRUE;
4830 }
4831
4832 if (!ignore)
4833 {
4834 if (ga_grow(gap, 1) == OK)
4835 ((void**)gap->ga_data)[gap->ga_len++] = item;
4836 else
4837 {
4838 failed = TRUE;
4839 FREE_ITEM(item);
4840 break;
4841 }
4842 }
4843 else
4844 FREE_ITEM(item);
4845
4846 ok = FindNextFileW(hFind, &wfd);
4847 }
4848 FindClose(hFind);
4849 }
4850
4851 vim_free(buf);
4852 vim_free(wn);
4853# else // MSWIN
4854 dirp = opendir((char *)path);
4855 if (dirp == NULL)
4856 {
4857 failed = TRUE;
Bram Moolenaaraab9fad2020-10-11 14:28:11 +02004858 semsg(_(e_notopen), path);
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004859 }
4860 else
4861 {
4862 for (;;)
4863 {
4864 int ignore;
4865 void *item;
4866
4867 dp = readdir(dirp);
4868 if (dp == NULL)
4869 break;
4870 p = (char_u *)dp->d_name;
4871
4872 ignore = p[0] == '.' &&
4873 (p[1] == NUL ||
4874 (p[1] == '.' && p[2] == NUL));
Bram Moolenaarab540322020-06-10 15:55:36 +02004875 if (ignore)
4876 continue;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004877# ifdef FEAT_EVAL
4878 if (withattr)
4879 item = (void*)create_readdirex_item(path, p);
4880 else
4881# endif
4882 item = (void*)vim_strsave(p);
4883 if (item == NULL)
4884 {
4885 failed = TRUE;
4886 break;
4887 }
4888
4889 if (!ignore && checkitem != NULL)
4890 {
4891 int r = checkitem(context, item);
4892
4893 if (r < 0)
4894 {
4895 FREE_ITEM(item);
4896 break;
4897 }
4898 if (r == 0)
4899 ignore = TRUE;
4900 }
4901
4902 if (!ignore)
4903 {
4904 if (ga_grow(gap, 1) == OK)
4905 ((void**)gap->ga_data)[gap->ga_len++] = item;
4906 else
4907 {
4908 failed = TRUE;
4909 FREE_ITEM(item);
4910 break;
4911 }
4912 }
4913 else
4914 FREE_ITEM(item);
4915 }
4916
4917 closedir(dirp);
4918 }
4919# endif // MSWIN
4920
4921# undef FREE_ITEM
4922
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02004923 if (!failed && gap->ga_len > 0 && sort > READDIR_SORT_NONE)
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004924 {
4925# ifdef FEAT_EVAL
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02004926 readdirex_sort = sort;
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004927 if (withattr)
4928 qsort((void*)gap->ga_data, (size_t)gap->ga_len, sizeof(dict_T*),
4929 compare_readdirex_item);
4930 else
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02004931 qsort((void*)gap->ga_data, (size_t)gap->ga_len, sizeof(char_u *),
4932 compare_readdir_item);
4933# else
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004934 sort_strings((char_u **)gap->ga_data, gap->ga_len);
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02004935# endif
Bram Moolenaar6c9ba042020-06-01 16:09:41 +02004936 }
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004937
4938 return failed ? FAIL : OK;
4939}
4940
4941/*
Bram Moolenaarda440d22016-01-16 21:27:23 +01004942 * Delete "name" and everything in it, recursively.
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004943 * return 0 for success, -1 if some file was not deleted.
Bram Moolenaarda440d22016-01-16 21:27:23 +01004944 */
4945 int
4946delete_recursive(char_u *name)
4947{
4948 int result = 0;
Bram Moolenaarda440d22016-01-16 21:27:23 +01004949 int i;
4950 char_u *exp;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004951 garray_T ga;
Bram Moolenaarda440d22016-01-16 21:27:23 +01004952
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004953 // A symbolic link to a directory itself is deleted, not the directory it
4954 // points to.
Bram Moolenaar43a34f92016-01-17 15:56:34 +01004955 if (
Bram Moolenaar4f974752019-02-17 17:44:42 +01004956# if defined(UNIX) || defined(MSWIN)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01004957 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01004958# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01004959 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01004960# endif
4961 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01004962 {
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004963 exp = vim_strsave(name);
Bram Moolenaarda440d22016-01-16 21:27:23 +01004964 if (exp == NULL)
4965 return -1;
Bram Moolenaar84cf6bd2020-06-16 20:03:43 +02004966 if (readdir_core(&ga, exp, FALSE, NULL, NULL, READDIR_SORT_NONE) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01004967 {
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004968 for (i = 0; i < ga.ga_len; ++i)
4969 {
4970 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/%s", exp,
4971 ((char_u **)ga.ga_data)[i]);
4972 if (delete_recursive(NameBuff) != 0)
Bram Moolenaarda440d22016-01-16 21:27:23 +01004973 result = -1;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004974 }
4975 ga_clear_strings(&ga);
Bram Moolenaarda440d22016-01-16 21:27:23 +01004976 }
4977 else
4978 result = -1;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004979 (void)mch_rmdir(exp);
Bram Moolenaarda440d22016-01-16 21:27:23 +01004980 vim_free(exp);
Bram Moolenaarda440d22016-01-16 21:27:23 +01004981 }
4982 else
4983 result = mch_remove(name) == 0 ? 0 : -1;
4984
4985 return result;
4986}
4987#endif
4988
Bram Moolenaar071d4272004-06-13 20:20:40 +00004989#if defined(TEMPDIRNAMES) || defined(PROTO)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01004990static long temp_count = 0; // Temp filename counter.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004991
Bram Moolenaarb2d0e512020-05-07 18:37:03 +02004992# if defined(UNIX) && defined(HAVE_FLOCK) && defined(HAVE_DIRFD)
4993/*
4994 * Open temporary directory and take file lock to prevent
4995 * to be auto-cleaned.
4996 */
4997 static void
4998vim_opentempdir(void)
4999{
5000 DIR *dp = NULL;
5001
5002 if (vim_tempdir_dp != NULL)
5003 return;
5004
5005 dp = opendir((const char*)vim_tempdir);
5006
5007 if (dp != NULL)
5008 {
5009 vim_tempdir_dp = dp;
5010 flock(dirfd(vim_tempdir_dp), LOCK_SH);
5011 }
5012}
5013
5014/*
5015 * Close temporary directory - it automatically release file lock.
5016 */
5017 static void
5018vim_closetempdir(void)
5019{
5020 if (vim_tempdir_dp != NULL)
5021 {
5022 closedir(vim_tempdir_dp);
5023 vim_tempdir_dp = NULL;
5024 }
5025}
5026# endif
5027
Bram Moolenaar071d4272004-06-13 20:20:40 +00005028/*
5029 * Delete the temp directory and all files it contains.
5030 */
5031 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005032vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005033{
Bram Moolenaar071d4272004-06-13 20:20:40 +00005034 if (vim_tempdir != NULL)
5035 {
Bram Moolenaarb2d0e512020-05-07 18:37:03 +02005036# if defined(UNIX) && defined(HAVE_FLOCK) && defined(HAVE_DIRFD)
5037 vim_closetempdir();
5038# endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005039 // remove the trailing path separator
Bram Moolenaarda440d22016-01-16 21:27:23 +01005040 gettail(vim_tempdir)[-1] = NUL;
5041 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01005042 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005043 }
5044}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005045
5046/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00005047 * Directory "tempdir" was created. Expand this name to a full path and put
5048 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
5049 * "tempdir" must be no longer than MAXPATHL.
5050 */
5051 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005052vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00005053{
5054 char_u *buf;
5055
Bram Moolenaar964b3742019-05-24 18:54:09 +02005056 buf = alloc(MAXPATHL + 2);
Bram Moolenaareaf03392009-11-17 11:08:52 +00005057 if (buf != NULL)
5058 {
5059 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
5060 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02005061 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00005062 vim_tempdir = vim_strsave(buf);
Bram Moolenaarb2d0e512020-05-07 18:37:03 +02005063# if defined(UNIX) && defined(HAVE_FLOCK) && defined(HAVE_DIRFD)
5064 vim_opentempdir();
5065# endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00005066 vim_free(buf);
5067 }
5068}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00005069#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00005070
5071/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00005072 * vim_tempname(): Return a unique name that can be used for a temp file.
5073 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02005074 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
5075 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005076 *
5077 * The returned pointer is to allocated memory.
5078 * The returned pointer is NULL if no valid name was found.
5079 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005080 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005081vim_tempname(
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005082 int extra_char UNUSED, // char to use in the name instead of '?'
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005083 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005084{
5085#ifdef USE_TMPNAM
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005086 char_u itmp[L_tmpnam]; // use tmpnam()
Bram Moolenaar4f974752019-02-17 17:44:42 +01005087#elif defined(MSWIN)
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01005088 WCHAR itmp[TEMPNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00005089#else
5090 char_u itmp[TEMPNAMELEN];
5091#endif
5092
5093#ifdef TEMPDIRNAMES
5094 static char *(tempdirs[]) = {TEMPDIRNAMES};
5095 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005096# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02005097 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005098# endif
5099
5100 /*
5101 * This will create a directory for private use by this instance of Vim.
5102 * This is done once, and the same directory is used for all temp files.
5103 * This method avoids security problems because of symlink attacks et al.
5104 * It's also a bit faster, because we only need to check for an existing
5105 * file when creating the directory and not for each temp file.
5106 */
5107 if (vim_tempdir == NULL)
5108 {
5109 /*
5110 * Try the entries in TEMPDIRNAMES to create the temp directory.
5111 */
K.Takataeeec2542021-06-02 13:28:16 +02005112 for (i = 0; i < (int)ARRAY_LENGTH(tempdirs); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005113 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00005114# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01005115 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00005116 long nr;
5117 long off;
5118# endif
5119
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005120 // Expand $TMP, leave room for "/v1100000/999999999".
5121 // Skip the directory check if the expansion fails.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005122 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01005123 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005124 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005125 // directory exists
Bram Moolenaara06ecab2016-07-16 14:47:36 +02005126 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005127
Bram Moolenaareaf03392009-11-17 11:08:52 +00005128# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02005129 {
5130# if defined(UNIX) || defined(VMS)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005131 // Make sure the umask doesn't remove the executable bit.
5132 // "repl" has been reported to use "177".
Bram Moolenaar35d88f42016-06-04 14:52:00 +02005133 mode_t umask_save = umask(077);
5134# endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005135 // Leave room for filename
Bram Moolenaar35d88f42016-06-04 14:52:00 +02005136 STRCAT(itmp, "vXXXXXX");
5137 if (mkdtemp((char *)itmp) != NULL)
5138 vim_settempdir(itmp);
5139# if defined(UNIX) || defined(VMS)
5140 (void)umask(umask_save);
5141# endif
5142 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00005143# else
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005144 // Get an arbitrary number of up to 6 digits. When it's
5145 // unlikely that it already exists it will be faster,
5146 // otherwise it doesn't matter. The use of mkdir() avoids any
5147 // security problems because of the predictable number.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005148 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01005149 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005150
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005151 // Try up to 10000 different values until we find a name that
5152 // doesn't exist.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005153 for (off = 0; off < 10000L; ++off)
5154 {
5155 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00005156# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005157 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00005158# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005159
Bram Moolenaareaf03392009-11-17 11:08:52 +00005160 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
5161# ifndef EEXIST
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005162 // If mkdir() does not set errno to EEXIST, check for
5163 // existing file here. There is a race condition then,
5164 // although it's fail-safe.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005165 if (mch_stat((char *)itmp, &st) >= 0)
5166 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00005167# endif
5168# if defined(UNIX) || defined(VMS)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005169 // Make sure the umask doesn't remove the executable bit.
5170 // "repl" has been reported to use "177".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005171 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00005172# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005173 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00005174# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005175 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00005176# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005177 if (r == 0)
5178 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00005179 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005180 break;
5181 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00005182# ifdef EEXIST
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005183 // If the mkdir() didn't fail because the file/dir exists,
5184 // we probably can't create any dir here, try another
5185 // place.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005186 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00005187# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00005188 break;
5189 }
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005190# endif // HAVE_MKDTEMP
Bram Moolenaar071d4272004-06-13 20:20:40 +00005191 if (vim_tempdir != NULL)
5192 break;
5193 }
5194 }
5195 }
5196
5197 if (vim_tempdir != NULL)
5198 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005199 // There is no need to check if the file exists, because we own the
5200 // directory and nobody else creates a file in it.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005201 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
5202 return vim_strsave(itmp);
5203 }
5204
5205 return NULL;
5206
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005207#else // TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00005208
Bram Moolenaar4f974752019-02-17 17:44:42 +01005209# ifdef MSWIN
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01005210 WCHAR wszTempFile[_MAX_PATH + 1];
5211 WCHAR buf4[4];
Bram Moolenaar2472a742020-11-26 19:47:28 +01005212 WCHAR *chartab = L"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
Bram Moolenaar071d4272004-06-13 20:20:40 +00005213 char_u *retval;
5214 char_u *p;
Bram Moolenaar2472a742020-11-26 19:47:28 +01005215 long i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005216
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01005217 wcscpy(itmp, L"");
5218 if (GetTempPathW(_MAX_PATH, wszTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01005219 {
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01005220 wszTempFile[0] = L'.'; // GetTempPathW() failed, use current dir
Bram Moolenaar2472a742020-11-26 19:47:28 +01005221 wszTempFile[1] = L'\\';
5222 wszTempFile[2] = NUL;
Bram Moolenaarb1891912011-02-09 14:47:03 +01005223 }
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01005224 wcscpy(buf4, L"VIM");
Bram Moolenaar2472a742020-11-26 19:47:28 +01005225
5226 // randomize the name to avoid collisions
5227 i = mch_get_pid() + extra_char;
5228 buf4[1] = chartab[i % 36];
5229 buf4[2] = chartab[101 * i % 36];
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01005230 if (GetTempFileNameW(wszTempFile, buf4, 0, itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005231 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02005232 if (!keep)
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01005233 // GetTempFileName() will create the file, we don't want that
5234 (void)DeleteFileW(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005235
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01005236 // Backslashes in a temp file name cause problems when filtering with
5237 // "sh". NOTE: This also checks 'shellcmdflag' to help those people who
5238 // didn't set 'shellslash'.
5239 retval = utf16_to_enc(itmp, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005240 if (*p_shcf == '-' || p_ssl)
5241 for (p = retval; *p; ++p)
5242 if (*p == '\\')
5243 *p = '/';
5244 return retval;
5245
Bram Moolenaar4f974752019-02-17 17:44:42 +01005246# else // MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00005247
5248# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01005249 char_u *p;
5250
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005251 // tmpnam() will make its own name
Bram Moolenaar95474ca2011-02-09 16:44:51 +01005252 p = tmpnam((char *)itmp);
5253 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005254 return NULL;
5255# else
5256 char_u *p;
5257
5258# ifdef VMS_TEMPNAM
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005259 // mktemp() is not working on VMS. It seems to be
5260 // a do-nothing function. Therefore we use tempnam().
Bram Moolenaar071d4272004-06-13 20:20:40 +00005261 sprintf((char *)itmp, "VIM%c", extra_char);
5262 p = (char_u *)tempnam("tmp:", (char *)itmp);
5263 if (p != NULL)
5264 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005265 // VMS will use '.LIS' if we don't explicitly specify an extension,
5266 // and VIM will then be unable to find the file later
Bram Moolenaar071d4272004-06-13 20:20:40 +00005267 STRCPY(itmp, p);
5268 STRCAT(itmp, ".txt");
5269 free(p);
5270 }
5271 else
5272 return NULL;
5273# else
5274 STRCPY(itmp, TEMPNAME);
5275 if ((p = vim_strchr(itmp, '?')) != NULL)
5276 *p = extra_char;
5277 if (mktemp((char *)itmp) == NULL)
5278 return NULL;
5279# endif
5280# endif
5281
5282 return vim_strsave(itmp);
Bram Moolenaar4f974752019-02-17 17:44:42 +01005283# endif // MSWIN
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005284#endif // TEMPDIRNAMES
Bram Moolenaar071d4272004-06-13 20:20:40 +00005285}
5286
5287#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
5288/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02005289 * Convert all backslashes in fname to forward slashes in-place, unless when
5290 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005291 */
5292 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005293forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005294{
5295 char_u *p;
5296
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02005297 if (path_with_url(fname))
5298 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005299 for (p = fname; *p != NUL; ++p)
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005300 // The Big5 encoding can have '\' in the trail byte.
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005301 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005302 ++p;
Bram Moolenaar13505972019-01-24 15:04:48 +01005303 else if (*p == '\\')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005304 *p = '/';
5305}
5306#endif
5307
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00005308/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00005309 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
5310 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
5311 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00005312 * Used for autocommands and 'wildignore'.
5313 * Returns TRUE if there is a match, FALSE otherwise.
5314 */
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01005315 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005316match_file_pat(
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005317 char_u *pattern, // pattern to match with
5318 regprog_T **prog, // pre-compiled regprog or NULL
5319 char_u *fname, // full path of file name
5320 char_u *sfname, // short file name or NULL
5321 char_u *tail, // tail of path
5322 int allow_dirs) // allow matching with dir
Bram Moolenaar071d4272004-06-13 20:20:40 +00005323{
5324 regmatch_T regmatch;
5325 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005326
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005327 regmatch.rm_ic = p_fic; // ignore case if 'fileignorecase' is set
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01005328 if (prog != NULL)
5329 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005330 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01005331 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005332
5333 /*
5334 * Try for a match with the pattern with:
5335 * 1. the full file name, when the pattern has a '/'.
5336 * 2. the short file name, when the pattern has a '/'.
5337 * 3. the tail of the file name, when the pattern has no '/'.
5338 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01005339 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00005340 && ((allow_dirs
5341 && (vim_regexec(&regmatch, fname, (colnr_T)0)
5342 || (sfname != NULL
5343 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01005344 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005345 result = TRUE;
5346
Bram Moolenaardffa5b82014-11-19 16:38:07 +01005347 if (prog != NULL)
5348 *prog = regmatch.regprog;
5349 else
Bram Moolenaar473de612013-06-08 18:19:48 +02005350 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005351 return result;
5352}
Bram Moolenaar071d4272004-06-13 20:20:40 +00005353
5354#if defined(FEAT_WILDIGN) || defined(PROTO)
5355/*
5356 * Return TRUE if a file matches with a pattern in "list".
5357 * "list" is a comma-separated list of patterns, like 'wildignore'.
5358 * "sfname" is the short file name or NULL, "ffname" the long file name.
5359 */
5360 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005361match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005362{
5363 char_u buf[100];
5364 char_u *tail;
5365 char_u *regpat;
5366 char allow_dirs;
5367 int match;
5368 char_u *p;
5369
5370 tail = gettail(sfname);
5371
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005372 // try all patterns in 'wildignore'
Bram Moolenaar071d4272004-06-13 20:20:40 +00005373 p = list;
5374 while (*p)
5375 {
5376 copy_option_part(&p, buf, 100, ",");
5377 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
5378 if (regpat == NULL)
5379 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00005380 match = match_file_pat(regpat, NULL, ffname, sfname,
5381 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005382 vim_free(regpat);
5383 if (match)
5384 return TRUE;
5385 }
5386 return FALSE;
5387}
5388#endif
5389
5390/*
5391 * Convert the given pattern "pat" which has shell style wildcards in it, into
5392 * a regular expression, and return the result in allocated memory. If there
5393 * is a directory path separator to be matched, then TRUE is put in
5394 * allow_dirs, otherwise FALSE is put there -- webb.
5395 * Handle backslashes before special characters, like "\*" and "\ ".
5396 *
Bram Moolenaar071d4272004-06-13 20:20:40 +00005397 * Returns NULL when out of memory.
5398 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005399 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005400file_pat_to_reg_pat(
5401 char_u *pat,
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005402 char_u *pat_end, // first char after pattern or NULL
5403 char *allow_dirs, // Result passed back out in here
5404 int no_bslash UNUSED) // Don't use a backward slash as pathsep
Bram Moolenaar071d4272004-06-13 20:20:40 +00005405{
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005406 int size = 2; // '^' at start, '$' at end
Bram Moolenaar071d4272004-06-13 20:20:40 +00005407 char_u *endp;
5408 char_u *reg_pat;
5409 char_u *p;
5410 int i;
5411 int nested = 0;
5412 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005413
5414 if (allow_dirs != NULL)
5415 *allow_dirs = FALSE;
5416 if (pat_end == NULL)
5417 pat_end = pat + STRLEN(pat);
5418
Bram Moolenaar071d4272004-06-13 20:20:40 +00005419 for (p = pat; p < pat_end; p++)
5420 {
5421 switch (*p)
5422 {
5423 case '*':
5424 case '.':
5425 case ',':
5426 case '{':
5427 case '}':
5428 case '~':
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005429 size += 2; // extra backslash
Bram Moolenaar071d4272004-06-13 20:20:40 +00005430 break;
5431#ifdef BACKSLASH_IN_FILENAME
5432 case '\\':
5433 case '/':
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005434 size += 4; // could become "[\/]"
Bram Moolenaar071d4272004-06-13 20:20:40 +00005435 break;
5436#endif
5437 default:
5438 size++;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005439 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005440 {
5441 ++p;
5442 ++size;
5443 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005444 break;
5445 }
5446 }
5447 reg_pat = alloc(size + 1);
5448 if (reg_pat == NULL)
5449 return NULL;
5450
Bram Moolenaar071d4272004-06-13 20:20:40 +00005451 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005452
5453 if (pat[0] == '*')
5454 while (pat[0] == '*' && pat < pat_end - 1)
5455 pat++;
5456 else
5457 reg_pat[i++] = '^';
5458 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +02005459 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005460 {
5461 while (endp - pat > 0 && *endp == '*')
5462 endp--;
5463 add_dollar = FALSE;
5464 }
5465 for (p = pat; *p && nested >= 0 && p <= endp; p++)
5466 {
5467 switch (*p)
5468 {
5469 case '*':
5470 reg_pat[i++] = '.';
5471 reg_pat[i++] = '*';
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005472 while (p[1] == '*') // "**" matches like "*"
Bram Moolenaar02743632005-07-25 20:42:36 +00005473 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005474 break;
5475 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +00005476 case '~':
5477 reg_pat[i++] = '\\';
5478 reg_pat[i++] = *p;
5479 break;
5480 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +00005481 reg_pat[i++] = '.';
5482 break;
5483 case '\\':
5484 if (p[1] == NUL)
5485 break;
5486#ifdef BACKSLASH_IN_FILENAME
5487 if (!no_bslash)
5488 {
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005489 // translate:
5490 // "\x" to "\\x" e.g., "dir\file"
5491 // "\*" to "\\.*" e.g., "dir\*.c"
5492 // "\?" to "\\." e.g., "dir\??.c"
5493 // "\+" to "\+" e.g., "fileX\+.c"
Bram Moolenaar071d4272004-06-13 20:20:40 +00005494 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
5495 && p[1] != '+')
5496 {
5497 reg_pat[i++] = '[';
5498 reg_pat[i++] = '\\';
5499 reg_pat[i++] = '/';
5500 reg_pat[i++] = ']';
5501 if (allow_dirs != NULL)
5502 *allow_dirs = TRUE;
5503 break;
5504 }
5505 }
5506#endif
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005507 // Undo escaping from ExpandEscape():
5508 // foo\?bar -> foo?bar
5509 // foo\%bar -> foo%bar
5510 // foo\,bar -> foo,bar
5511 // foo\ bar -> foo bar
5512 // Don't unescape \, * and others that are also special in a
5513 // regexp.
5514 // An escaped { must be unescaped since we use magic not
5515 // verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaar071d4272004-06-13 20:20:40 +00005516 if (*++p == '?'
5517#ifdef BACKSLASH_IN_FILENAME
5518 && no_bslash
5519#endif
5520 )
5521 reg_pat[i++] = '?';
5522 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +02005523 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +02005524 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +02005525 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +02005526 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
5527 {
5528 reg_pat[i++] = '\\';
5529 reg_pat[i++] = '{';
5530 p += 2;
5531 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005532 else
5533 {
5534 if (allow_dirs != NULL && vim_ispathsep(*p)
5535#ifdef BACKSLASH_IN_FILENAME
5536 && (!no_bslash || *p != '\\')
5537#endif
5538 )
5539 *allow_dirs = TRUE;
5540 reg_pat[i++] = '\\';
5541 reg_pat[i++] = *p;
5542 }
5543 break;
5544#ifdef BACKSLASH_IN_FILENAME
5545 case '/':
5546 reg_pat[i++] = '[';
5547 reg_pat[i++] = '\\';
5548 reg_pat[i++] = '/';
5549 reg_pat[i++] = ']';
5550 if (allow_dirs != NULL)
5551 *allow_dirs = TRUE;
5552 break;
5553#endif
5554 case '{':
5555 reg_pat[i++] = '\\';
5556 reg_pat[i++] = '(';
5557 nested++;
5558 break;
5559 case '}':
5560 reg_pat[i++] = '\\';
5561 reg_pat[i++] = ')';
5562 --nested;
5563 break;
5564 case ',':
5565 if (nested)
5566 {
5567 reg_pat[i++] = '\\';
5568 reg_pat[i++] = '|';
5569 }
5570 else
5571 reg_pat[i++] = ',';
5572 break;
5573 default:
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005574 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005575 reg_pat[i++] = *p++;
Bram Moolenaar13505972019-01-24 15:04:48 +01005576 else if (allow_dirs != NULL && vim_ispathsep(*p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005577 *allow_dirs = TRUE;
5578 reg_pat[i++] = *p;
5579 break;
5580 }
5581 }
5582 if (add_dollar)
5583 reg_pat[i++] = '$';
5584 reg_pat[i] = NUL;
5585 if (nested != 0)
5586 {
5587 if (nested < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005588 emsg(_("E219: Missing {."));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005589 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005590 emsg(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +01005591 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005592 }
5593 return reg_pat;
5594}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005595
5596#if defined(EINTR) || defined(PROTO)
5597/*
5598 * Version of read() that retries when interrupted by EINTR (possibly
5599 * by a SIGWINCH).
5600 */
5601 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005602read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005603{
5604 long ret;
5605
5606 for (;;)
5607 {
5608 ret = vim_read(fd, buf, bufsize);
5609 if (ret >= 0 || errno != EINTR)
5610 break;
5611 }
5612 return ret;
5613}
5614
5615/*
5616 * Version of write() that retries when interrupted by EINTR (possibly
5617 * by a SIGWINCH).
5618 */
5619 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005620write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005621{
5622 long ret = 0;
5623 long wlen;
5624
Bram Moolenaar217e1b82019-12-01 21:41:28 +01005625 // Repeat the write() so long it didn't fail, other than being interrupted
5626 // by a signal.
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005627 while (ret < (long)bufsize)
5628 {
Bram Moolenaar9c263032010-12-17 18:06:06 +01005629 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005630 if (wlen < 0)
5631 {
5632 if (errno != EINTR)
5633 break;
5634 }
5635 else
5636 ret += wlen;
5637 }
5638 return ret;
5639}
5640#endif