blob: 0c2238be6b51b963657d6a97a1edf01fb5437494 [file] [log] [blame]
Bram Moolenaaredf3f972016-08-29 22:49:24 +02001/* vi:set ts=8 sts=4 sw=4 noet:
Bram Moolenaar071d4272004-06-13 20:20:40 +00002 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * fileio.c: read from and write to a file
12 */
13
Bram Moolenaar071d4272004-06-13 20:20:40 +000014#include "vim.h"
15
Bram Moolenaarf4888d02009-12-02 12:31:27 +000016#if defined(__TANDEM) || defined(__MINT__)
Bram Moolenaar071d4272004-06-13 20:20:40 +000017# include <limits.h> /* for SSIZE_MAX */
18#endif
19
Bram Moolenaar071d4272004-06-13 20:20:40 +000020/* Is there any system that doesn't have access()? */
Bram Moolenaar9372a112005-12-06 19:59:18 +000021#define USE_MCH_ACCESS
Bram Moolenaar071d4272004-06-13 20:20:40 +000022
Bram Moolenaarf077db22019-08-13 00:18:24 +020023static char_u *next_fenc(char_u **pp, int *alloced);
Bram Moolenaar13505972019-01-24 15:04:48 +010024#ifdef FEAT_EVAL
Bram Moolenaard25c16e2016-01-29 22:13:30 +010025static char_u *readfile_charconvert(char_u *fname, char_u *fenc, int *fdp);
Bram Moolenaar071d4272004-06-13 20:20:40 +000026#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +000027#ifdef FEAT_CRYPT
Bram Moolenaar8767f522016-07-01 17:17:39 +020028static 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 +000029#endif
Bram Moolenaard25c16e2016-01-29 22:13:30 +010030static linenr_T readfile_linenr(linenr_T linecnt, char_u *p, char_u *endp);
Bram Moolenaard25c16e2016-01-29 22:13:30 +010031static char_u *check_for_bom(char_u *p, long size, int *lenp, int flags);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +000032static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
Bram Moolenaarb0bf8582005-12-13 20:02:15 +000033
Bram Moolenaar473952e2019-09-28 16:30:04 +020034 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010035filemess(
36 buf_T *buf,
37 char_u *name,
38 char_u *s,
39 int attr)
Bram Moolenaar071d4272004-06-13 20:20:40 +000040{
41 int msg_scroll_save;
Bram Moolenaar473952e2019-09-28 16:30:04 +020042 int prev_msg_col = msg_col;
Bram Moolenaar071d4272004-06-13 20:20:40 +000043
44 if (msg_silent != 0)
45 return;
46 msg_add_fname(buf, name); /* put file name in IObuff with quotes */
47 /* If it's extremely long, truncate it. */
48 if (STRLEN(IObuff) > IOSIZE - 80)
49 IObuff[IOSIZE - 80] = NUL;
50 STRCAT(IObuff, s);
51 /*
52 * For the first message may have to start a new line.
53 * For further ones overwrite the previous one, reset msg_scroll before
54 * calling filemess().
55 */
56 msg_scroll_save = msg_scroll;
57 if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0)
58 msg_scroll = FALSE;
59 if (!msg_scroll) /* wait a bit when overwriting an error msg */
60 check_for_delay(FALSE);
61 msg_start();
Bram Moolenaar473952e2019-09-28 16:30:04 +020062 if (prev_msg_col != 0 && msg_col == 0)
63 msg_putchar('\r'); // overwrite any previous message.
Bram Moolenaar071d4272004-06-13 20:20:40 +000064 msg_scroll = msg_scroll_save;
65 msg_scrolled_ign = TRUE;
66 /* may truncate the message to avoid a hit-return prompt */
67 msg_outtrans_attr(msg_may_trunc(FALSE, IObuff), attr);
68 msg_clr_eos();
69 out_flush();
70 msg_scrolled_ign = FALSE;
71}
72
73/*
74 * Read lines from file "fname" into the buffer after line "from".
75 *
76 * 1. We allocate blocks with lalloc, as big as possible.
77 * 2. Each block is filled with characters from the file with a single read().
78 * 3. The lines are inserted in the buffer with ml_append().
79 *
80 * (caller must check that fname != NULL, unless READ_STDIN is used)
81 *
82 * "lines_to_skip" is the number of lines that must be skipped
83 * "lines_to_read" is the number of lines that are appended
84 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
85 *
86 * flags:
87 * READ_NEW starting to edit a new buffer
88 * READ_FILTER reading filter output
89 * READ_STDIN read from stdin instead of a file
90 * READ_BUFFER read from curbuf instead of a file (converting after reading
91 * stdin)
92 * READ_DUMMY read into a dummy buffer (to check if file contents changed)
Bram Moolenaar59f931e2010-07-24 20:27:03 +020093 * READ_KEEP_UNDO don't clear undo info or read it from a file
Bram Moolenaarf71d7b92016-08-09 22:14:05 +020094 * READ_FIFO read from fifo/socket instead of a file
Bram Moolenaar071d4272004-06-13 20:20:40 +000095 *
Bram Moolenaare13b9af2017-01-13 22:01:02 +010096 * return FAIL for failure, NOTDONE for directory (failure), or OK
Bram Moolenaar071d4272004-06-13 20:20:40 +000097 */
98 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +010099readfile(
100 char_u *fname,
101 char_u *sfname,
102 linenr_T from,
103 linenr_T lines_to_skip,
104 linenr_T lines_to_read,
105 exarg_T *eap, /* can be NULL! */
106 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000107{
108 int fd = 0;
109 int newfile = (flags & READ_NEW);
110 int check_readonly;
111 int filtering = (flags & READ_FILTER);
112 int read_stdin = (flags & READ_STDIN);
113 int read_buffer = (flags & READ_BUFFER);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200114 int read_fifo = (flags & READ_FIFO);
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000115 int set_options = newfile || read_buffer
116 || (eap != NULL && eap->read_edit);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000117 linenr_T read_buf_lnum = 1; /* next line to read from curbuf */
118 colnr_T read_buf_col = 0; /* next char to read from this line */
119 char_u c;
120 linenr_T lnum = from;
121 char_u *ptr = NULL; /* pointer into read buffer */
122 char_u *buffer = NULL; /* read buffer */
123 char_u *new_buffer = NULL; /* init to shut up gcc */
124 char_u *line_start = NULL; /* init to shut up gcc */
125 int wasempty; /* buffer was empty before reading */
126 colnr_T len;
127 long size = 0;
128 char_u *p;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200129 off_T filesize = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000130 int skip_read = FALSE;
131#ifdef FEAT_CRYPT
132 char_u *cryptkey = NULL;
Bram Moolenaarf50a2532010-05-21 15:36:08 +0200133 int did_ask_for_key = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000134#endif
Bram Moolenaar55debbe2010-05-23 23:34:36 +0200135#ifdef FEAT_PERSISTENT_UNDO
136 context_sha256_T sha_ctx;
137 int read_undo_file = FALSE;
138#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000139 int split = 0; /* number of split lines */
140#define UNKNOWN 0x0fffffff /* file size is unknown */
141 linenr_T linecnt;
142 int error = FALSE; /* errors encountered */
143 int ff_error = EOL_UNKNOWN; /* file format with errors */
144 long linerest = 0; /* remaining chars in line */
145#ifdef UNIX
146 int perm = 0;
147 int swap_mode = -1; /* protection bits for swap file */
148#else
149 int perm;
150#endif
151 int fileformat = 0; /* end-of-line format */
152 int keep_fileformat = FALSE;
Bram Moolenaar8767f522016-07-01 17:17:39 +0200153 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000154 int file_readonly;
155 linenr_T skip_count = 0;
156 linenr_T read_count = 0;
157 int msg_save = msg_scroll;
158 linenr_T read_no_eol_lnum = 0; /* non-zero lnum when last line of
159 * last read was missing the eol */
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100160 int try_mac;
161 int try_dos;
162 int try_unix;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000163 int file_rewind = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000164 int can_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000165 linenr_T conv_error = 0; /* line nr with conversion error */
166 linenr_T illegal_byte = 0; /* line nr with illegal byte */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000167 int keep_dest_enc = FALSE; /* don't retry when char doesn't fit
168 in destination encoding */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000169 int bad_char_behavior = BAD_REPLACE;
170 /* BAD_KEEP, BAD_DROP or character to
171 * replace with */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000172 char_u *tmpname = NULL; /* name of 'charconvert' output file */
173 int fio_flags = 0;
174 char_u *fenc; /* fileencoding to use */
175 int fenc_alloced; /* fenc_next is in allocated memory */
176 char_u *fenc_next = NULL; /* next item in 'fencs' or NULL */
177 int advance_fenc = FALSE;
178 long real_size = 0;
Bram Moolenaar13505972019-01-24 15:04:48 +0100179#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000180 iconv_t iconv_fd = (iconv_t)-1; /* descriptor for iconv() or -1 */
Bram Moolenaar13505972019-01-24 15:04:48 +0100181# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000182 int did_iconv = FALSE; /* TRUE when iconv() failed and trying
183 'charconvert' next */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000184# endif
Bram Moolenaar13505972019-01-24 15:04:48 +0100185#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000186 int converted = FALSE; /* TRUE if conversion done */
187 int notconverted = FALSE; /* TRUE if conversion wanted but it
188 wasn't possible */
189 char_u conv_rest[CONV_RESTLEN];
190 int conv_restlen = 0; /* nr of bytes in conv_rest[] */
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200191 buf_T *old_curbuf;
192 char_u *old_b_ffname;
193 char_u *old_b_fname;
194 int using_b_ffname;
195 int using_b_fname;
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200196
Bram Moolenaarc3691332016-04-20 12:49:49 +0200197 au_did_filetype = FALSE; /* reset before triggering any autocommands */
Bram Moolenaarc3691332016-04-20 12:49:49 +0200198
Bram Moolenaarcab35ad2011-02-15 17:39:22 +0100199 curbuf->b_no_eol_lnum = 0; /* in case it was set by the previous read */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000200
201 /*
202 * If there is no file name yet, use the one for the read file.
203 * BF_NOTEDITED is set to reflect this.
204 * Don't do this for a read from a filter.
205 * Only do this when 'cpoptions' contains the 'f' flag.
206 */
207 if (curbuf->b_ffname == NULL
208 && !filtering
209 && fname != NULL
210 && vim_strchr(p_cpo, CPO_FNAMER) != NULL
211 && !(flags & READ_DUMMY))
212 {
Bram Moolenaar2d3f4892006-01-20 23:02:51 +0000213 if (set_rw_fname(fname, sfname) == FAIL)
214 return FAIL;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000215 }
216
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200217 /* Remember the initial values of curbuf, curbuf->b_ffname and
218 * curbuf->b_fname to detect whether they are altered as a result of
219 * executing nasty autocommands. Also check if "fname" and "sfname"
220 * point to one of these values. */
221 old_curbuf = curbuf;
222 old_b_ffname = curbuf->b_ffname;
223 old_b_fname = curbuf->b_fname;
224 using_b_ffname = (fname == curbuf->b_ffname)
225 || (sfname == curbuf->b_ffname);
226 using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
Bram Moolenaarbb3d5dc2010-08-14 14:32:54 +0200227
Bram Moolenaardf177f62005-02-22 08:39:57 +0000228 /* After reading a file the cursor line changes but we don't want to
229 * display the line. */
230 ex_no_reprint = TRUE;
231
Bram Moolenaar55b7cf82006-09-09 12:52:42 +0000232 /* don't display the file info for another buffer now */
233 need_fileinfo = FALSE;
234
Bram Moolenaar071d4272004-06-13 20:20:40 +0000235 /*
236 * For Unix: Use the short file name whenever possible.
237 * Avoids problems with networks and when directory names are changed.
238 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
239 * another directory, which we don't detect.
240 */
241 if (sfname == NULL)
242 sfname = fname;
Bram Moolenaara06ecab2016-07-16 14:47:36 +0200243#if defined(UNIX)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000244 fname = sfname;
245#endif
246
Bram Moolenaar071d4272004-06-13 20:20:40 +0000247 /*
248 * The BufReadCmd and FileReadCmd events intercept the reading process by
249 * executing the associated commands instead.
250 */
251 if (!filtering && !read_stdin && !read_buffer)
252 {
253 pos_T pos;
254
255 pos = curbuf->b_op_start;
256
257 /* Set '[ mark to the line above where the lines go (line 1 if zero). */
258 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
259 curbuf->b_op_start.col = 0;
260
261 if (newfile)
262 {
263 if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
264 FALSE, curbuf, eap))
265#ifdef FEAT_EVAL
266 return aborting() ? FAIL : OK;
267#else
268 return OK;
269#endif
270 }
271 else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
272 FALSE, NULL, eap))
273#ifdef FEAT_EVAL
274 return aborting() ? FAIL : OK;
275#else
276 return OK;
277#endif
278
279 curbuf->b_op_start = pos;
280 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000281
282 if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0)
283 msg_scroll = FALSE; /* overwrite previous file message */
284 else
285 msg_scroll = TRUE; /* don't overwrite previous file message */
286
287 /*
288 * If the name ends in a path separator, we can't open it. Check here,
289 * because reading the file may actually work, but then creating the swap
290 * file may destroy it! Reported on MS-DOS and Win 95.
291 * If the name is too long we might crash further on, quit here.
292 */
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000293 if (fname != NULL && *fname != NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000294 {
Bram Moolenaar1cd871b2004-12-19 22:46:22 +0000295 p = fname + STRLEN(fname);
296 if (after_pathsep(fname, p) || STRLEN(fname) >= MAXPATHL)
Bram Moolenaar15d0a8c2004-09-06 17:44:46 +0000297 {
298 filemess(curbuf, fname, (char_u *)_("Illegal file name"), 0);
299 msg_end();
300 msg_scroll = msg_save;
301 return FAIL;
302 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000303 }
304
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200305 if (!read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000306 {
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200307#ifdef UNIX
308 /*
309 * On Unix it is possible to read a directory, so we have to
310 * check for it before the mch_open().
311 */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000312 perm = mch_getperm(fname);
313 if (perm >= 0 && !S_ISREG(perm) /* not a regular file ... */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000314 && !S_ISFIFO(perm) /* ... or fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000315 && !S_ISSOCK(perm) /* ... or socket */
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +0000316# ifdef OPEN_CHR_FILES
317 && !(S_ISCHR(perm) && is_dev_fd_file(fname))
318 /* ... or a character special file named /dev/fd/<n> */
319# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000320 )
321 {
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100322 int retval = FAIL;
323
Bram Moolenaar071d4272004-06-13 20:20:40 +0000324 if (S_ISDIR(perm))
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100325 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000326 filemess(curbuf, fname, (char_u *)_("is a directory"), 0);
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100327 retval = NOTDONE;
328 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000329 else
330 filemess(curbuf, fname, (char_u *)_("is not a file"), 0);
331 msg_end();
332 msg_scroll = msg_save;
Bram Moolenaare13b9af2017-01-13 22:01:02 +0100333 return retval;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000334 }
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200335#endif
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100336#if defined(MSWIN)
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000337 /*
338 * MS-Windows allows opening a device, but we will probably get stuck
339 * trying to read it.
340 */
341 if (!p_odev && mch_nodetype(fname) == NODE_WRITABLE)
342 {
Bram Moolenaar5386a122007-06-28 20:02:32 +0000343 filemess(curbuf, fname, (char_u *)_("is a device (disabled with 'opendevice' option)"), 0);
Bram Moolenaarc67764a2006-10-12 19:14:26 +0000344 msg_end();
345 msg_scroll = msg_save;
346 return FAIL;
347 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000348#endif
Bram Moolenaar4e4f5292013-08-30 17:07:01 +0200349 }
Bram Moolenaar043545e2006-10-10 16:44:07 +0000350
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200351 /* Set default or forced 'fileformat' and 'binary'. */
352 set_file_options(set_options, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000353
354 /*
355 * When opening a new file we take the readonly flag from the file.
356 * Default is r/w, can be set to r/o below.
357 * Don't reset it when in readonly mode
358 * Only set/reset b_p_ro when BF_CHECK_RO is set.
359 */
360 check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
Bram Moolenaar4399ef42005-02-12 14:29:27 +0000361 if (check_readonly && !readonlymode)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000362 curbuf->b_p_ro = FALSE;
363
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200364 if (newfile && !read_stdin && !read_buffer && !read_fifo)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000365 {
Bram Moolenaare60acc12011-05-10 16:41:25 +0200366 /* Remember time of file. */
Bram Moolenaar071d4272004-06-13 20:20:40 +0000367 if (mch_stat((char *)fname, &st) >= 0)
368 {
369 buf_store_time(curbuf, &st, fname);
370 curbuf->b_mtime_read = curbuf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000371#ifdef UNIX
372 /*
373 * Use the protection bits of the original file for the swap file.
374 * This makes it possible for others to read the name of the
375 * edited file from the swapfile, but only if they can read the
376 * edited file.
377 * Remove the "write" and "execute" bits for group and others
378 * (they must not write the swapfile).
379 * Add the "read" and "write" bits for the user, otherwise we may
380 * not be able to write to the file ourselves.
381 * Setting the bits is done below, after creating the swap file.
382 */
383 swap_mode = (st.st_mode & 0644) | 0600;
384#endif
385#ifdef FEAT_CW_EDITOR
386 /* Get the FSSpec on MacOS
387 * TODO: Update it properly when the buffer name changes
388 */
389 (void)GetFSSpecFromPath(curbuf->b_ffname, &curbuf->b_FSSpec);
390#endif
391#ifdef VMS
392 curbuf->b_fab_rfm = st.st_fab_rfm;
Bram Moolenaard4755bb2004-09-02 19:12:26 +0000393 curbuf->b_fab_rat = st.st_fab_rat;
394 curbuf->b_fab_mrs = st.st_fab_mrs;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000395#endif
396 }
397 else
398 {
399 curbuf->b_mtime = 0;
400 curbuf->b_mtime_read = 0;
401 curbuf->b_orig_size = 0;
402 curbuf->b_orig_mode = 0;
403 }
404
405 /* Reset the "new file" flag. It will be set again below when the
406 * file doesn't exist. */
407 curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
408 }
409
410/*
411 * for UNIX: check readonly with perm and mch_access()
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100412 * for Amiga: check readonly by trying to open the file for writing
Bram Moolenaar071d4272004-06-13 20:20:40 +0000413 */
414 file_readonly = FALSE;
415 if (read_stdin)
416 {
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100417#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000418 /* Force binary I/O on stdin to avoid CR-LF -> LF conversion. */
419 setmode(0, O_BINARY);
420#endif
421 }
422 else if (!read_buffer)
423 {
424#ifdef USE_MCH_ACCESS
425 if (
426# ifdef UNIX
427 !(perm & 0222) ||
428# endif
429 mch_access((char *)fname, W_OK))
430 file_readonly = TRUE;
431 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
432#else
433 if (!newfile
434 || readonlymode
435 || (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0)
436 {
437 file_readonly = TRUE;
438 /* try to open ro */
439 fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
440 }
441#endif
442 }
443
444 if (fd < 0) /* cannot open at all */
445 {
446#ifndef UNIX
447 int isdir_f;
448#endif
449 msg_scroll = msg_save;
450#ifndef UNIX
451 /*
Bram Moolenaar48e330a2016-02-23 14:53:34 +0100452 * On Amiga we can't open a directory, check here.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000453 */
454 isdir_f = (mch_isdir(fname));
455 perm = mch_getperm(fname); /* check if the file exists */
456 if (isdir_f)
457 {
458 filemess(curbuf, sfname, (char_u *)_("is a directory"), 0);
459 curbuf->b_p_ro = TRUE; /* must use "w!" now */
460 }
461 else
462#endif
463 if (newfile)
464 {
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200465 if (perm < 0
466#ifdef ENOENT
467 && errno == ENOENT
468#endif
469 )
Bram Moolenaar071d4272004-06-13 20:20:40 +0000470 {
471 /*
472 * Set the 'new-file' flag, so that when the file has
473 * been created by someone else, a ":w" will complain.
474 */
475 curbuf->b_flags |= BF_NEW;
476
477 /* Create a swap file now, so that other Vims are warned
478 * that we are editing this file. Don't do this for a
479 * "nofile" or "nowrite" buffer type. */
480#ifdef FEAT_QUICKFIX
481 if (!bt_dontwrite(curbuf))
482#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000483 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000484 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000485 /* SwapExists autocommand may mess things up */
486 if (curbuf != old_curbuf
487 || (using_b_ffname
488 && (old_b_ffname != curbuf->b_ffname))
489 || (using_b_fname
490 && (old_b_fname != curbuf->b_fname)))
491 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100492 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000493 return FAIL;
494 }
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000495 }
Bram Moolenaar5b962cf2005-12-12 21:58:40 +0000496 if (dir_of_file_exists(fname))
497 filemess(curbuf, sfname, (char_u *)_("[New File]"), 0);
498 else
499 filemess(curbuf, sfname,
500 (char_u *)_("[New DIRECTORY]"), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000501#ifdef FEAT_VIMINFO
502 /* Even though this is a new file, it might have been
503 * edited before and deleted. Get the old marks. */
504 check_marks_read();
505#endif
Bram Moolenaarad875fb2013-07-24 15:02:03 +0200506 /* Set forced 'fileencoding'. */
507 if (eap != NULL)
508 set_forced_fenc(eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000509 apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
510 FALSE, curbuf, eap);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000511 /* remember the current fileformat */
512 save_file_ff(curbuf);
513
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +0100514#if defined(FEAT_EVAL)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000515 if (aborting()) /* autocmds may abort script processing */
516 return FAIL;
517#endif
518 return OK; /* a new file is not an error */
519 }
520 else
521 {
Bram Moolenaar202795b2005-10-11 20:29:39 +0000522 filemess(curbuf, sfname, (char_u *)(
523# ifdef EFBIG
524 (errno == EFBIG) ? _("[File too big]") :
525# endif
Bram Moolenaar2efbc662010-05-14 18:56:38 +0200526# ifdef EOVERFLOW
527 (errno == EOVERFLOW) ? _("[File too big]") :
528# endif
Bram Moolenaar202795b2005-10-11 20:29:39 +0000529 _("[Permission Denied]")), 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000530 curbuf->b_p_ro = TRUE; /* must use "w!" now */
531 }
532 }
533
534 return FAIL;
535 }
536
537 /*
538 * Only set the 'ro' flag for readonly files the first time they are
539 * loaded. Help files always get readonly mode
540 */
541 if ((check_readonly && file_readonly) || curbuf->b_help)
542 curbuf->b_p_ro = TRUE;
543
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000544 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000545 {
Bram Moolenaar690ffc02008-01-04 15:31:21 +0000546 /* Don't change 'eol' if reading from buffer as it will already be
547 * correctly set when reading stdin. */
548 if (!read_buffer)
549 {
550 curbuf->b_p_eol = TRUE;
551 curbuf->b_start_eol = TRUE;
552 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000553 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000554 curbuf->b_start_bomb = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000555 }
556
557 /* Create a swap file now, so that other Vims are warned that we are
558 * editing this file.
559 * Don't do this for a "nofile" or "nowrite" buffer type. */
560#ifdef FEAT_QUICKFIX
561 if (!bt_dontwrite(curbuf))
562#endif
563 {
564 check_need_swap(newfile);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000565 if (!read_stdin && (curbuf != old_curbuf
566 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
567 || (using_b_fname && (old_b_fname != curbuf->b_fname))))
568 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100569 emsg(_(e_auchangedbuf));
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000570 if (!read_buffer)
571 close(fd);
572 return FAIL;
573 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000574#ifdef UNIX
575 /* Set swap file protection bits after creating it. */
Bram Moolenaarf061e0b2009-06-24 15:32:01 +0000576 if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
577 && curbuf->b_ml.ml_mfp->mf_fname != NULL)
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100578 {
579 char_u *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
580
581 /*
582 * If the group-read bit is set but not the world-read bit, then
583 * the group must be equal to the group of the original file. If
584 * we can't make that happen then reset the group-read bit. This
585 * avoids making the swap file readable to more users when the
586 * primary group of the user is too permissive.
587 */
588 if ((swap_mode & 044) == 040)
589 {
590 stat_T swap_st;
591
592 if (mch_stat((char *)swap_fname, &swap_st) >= 0
593 && st.st_gid != swap_st.st_gid
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200594# ifdef HAVE_FCHOWN
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100595 && fchown(curbuf->b_ml.ml_mfp->mf_fd, -1, st.st_gid)
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200596 == -1
Bram Moolenaar1f131ae2018-05-21 13:39:40 +0200597# endif
Bram Moolenaar02e802b2018-04-19 21:15:27 +0200598 )
Bram Moolenaar5a73e0c2017-11-04 21:35:01 +0100599 swap_mode &= 0600;
600 }
601
602 (void)mch_setperm(swap_fname, (long)swap_mode);
603 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000604#endif
605 }
606
Bram Moolenaar67cf86b2019-04-28 22:25:38 +0200607 // If "Quit" selected at ATTENTION dialog, don't load the file
Bram Moolenaar071d4272004-06-13 20:20:40 +0000608 if (swap_exists_action == SEA_QUIT)
609 {
610 if (!read_buffer && !read_stdin)
611 close(fd);
612 return FAIL;
613 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000614
615 ++no_wait_return; /* don't wait for return yet */
616
617 /*
618 * Set '[ mark to the line above where the lines go (line 1 if zero).
619 */
620 curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
621 curbuf->b_op_start.col = 0;
622
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100623 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
624 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
625 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
626
Bram Moolenaar071d4272004-06-13 20:20:40 +0000627 if (!read_buffer)
628 {
629 int m = msg_scroll;
630 int n = msg_scrolled;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000631
632 /*
633 * The file must be closed again, the autocommands may want to change
634 * the file before reading it.
635 */
636 if (!read_stdin)
637 close(fd); /* ignore errors */
638
639 /*
640 * The output from the autocommands should not overwrite anything and
641 * should not be overwritten: Set msg_scroll, restore its value if no
642 * output was done.
643 */
644 msg_scroll = TRUE;
645 if (filtering)
646 apply_autocmds_exarg(EVENT_FILTERREADPRE, NULL, sfname,
647 FALSE, curbuf, eap);
648 else if (read_stdin)
649 apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
650 FALSE, curbuf, eap);
651 else if (newfile)
652 apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
653 FALSE, curbuf, eap);
654 else
655 apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
656 FALSE, NULL, eap);
Bram Moolenaar7a2699e2017-01-23 21:31:09 +0100657 /* autocommands may have changed it */
658 try_mac = (vim_strchr(p_ffs, 'm') != NULL);
659 try_dos = (vim_strchr(p_ffs, 'd') != NULL);
660 try_unix = (vim_strchr(p_ffs, 'x') != NULL);
661
Bram Moolenaar071d4272004-06-13 20:20:40 +0000662 if (msg_scrolled == n)
663 msg_scroll = m;
664
665#ifdef FEAT_EVAL
666 if (aborting()) /* autocmds may abort script processing */
667 {
668 --no_wait_return;
669 msg_scroll = msg_save;
670 curbuf->b_p_ro = TRUE; /* must use "w!" now */
671 return FAIL;
672 }
673#endif
674 /*
675 * Don't allow the autocommands to change the current buffer.
676 * Try to re-open the file.
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000677 *
678 * Don't allow the autocommands to change the buffer name either
679 * (cd for example) if it invalidates fname or sfname.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000680 */
681 if (!read_stdin && (curbuf != old_curbuf
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +0000682 || (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
683 || (using_b_fname && (old_b_fname != curbuf->b_fname))
Bram Moolenaar071d4272004-06-13 20:20:40 +0000684 || (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) < 0))
685 {
686 --no_wait_return;
687 msg_scroll = msg_save;
688 if (fd < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100689 emsg(_("E200: *ReadPre autocommands made the file unreadable"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000690 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +0100691 emsg(_("E201: *ReadPre autocommands must not change current buffer"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000692 curbuf->b_p_ro = TRUE; /* must use "w!" now */
693 return FAIL;
694 }
695 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000696
697 /* Autocommands may add lines to the file, need to check if it is empty */
698 wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
699
700 if (!recoverymode && !filtering && !(flags & READ_DUMMY))
701 {
702 /*
703 * Show the user that we are busy reading the input. Sometimes this
704 * may take a while. When reading from stdin another program may
705 * still be running, don't move the cursor to the last line, unless
706 * always using the GUI.
707 */
708 if (read_stdin)
709 {
Bram Moolenaar234d1622017-11-18 14:55:23 +0100710 if (!is_not_a_term())
711 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000712#ifndef ALWAYS_USE_GUI
Bram Moolenaarafde13b2019-04-28 19:46:49 +0200713# ifdef VIMDLL
714 if (!gui.in_use)
715# endif
716 mch_msg(_("Vim: Reading from stdin...\n"));
Bram Moolenaar071d4272004-06-13 20:20:40 +0000717#endif
718#ifdef FEAT_GUI
Bram Moolenaar234d1622017-11-18 14:55:23 +0100719 /* Also write a message in the GUI window, if there is one. */
720 if (gui.in_use && !gui.dying && !gui.starting)
721 {
722 p = (char_u *)_("Reading from stdin...");
723 gui_write(p, (int)STRLEN(p));
724 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000725#endif
Bram Moolenaar234d1622017-11-18 14:55:23 +0100726 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000727 }
728 else if (!read_buffer)
729 filemess(curbuf, sfname, (char_u *)"", 0);
730 }
731
732 msg_scroll = FALSE; /* overwrite the file message */
733
734 /*
735 * Set linecnt now, before the "retry" caused by a wrong guess for
736 * fileformat, and after the autocommands, which may change them.
737 */
738 linecnt = curbuf->b_ml.ml_line_count;
739
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000740 /* "++bad=" argument. */
741 if (eap != NULL && eap->bad_char != 0)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000742 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000743 bad_char_behavior = eap->bad_char;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000744 if (set_options)
Bram Moolenaar195d6352005-12-19 22:08:24 +0000745 curbuf->b_bad_char = eap->bad_char;
746 }
747 else
748 curbuf->b_bad_char = 0;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000749
Bram Moolenaar071d4272004-06-13 20:20:40 +0000750 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000751 * Decide which 'encoding' to use or use first.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000752 */
753 if (eap != NULL && eap->force_enc != 0)
754 {
755 fenc = enc_canonize(eap->cmd + eap->force_enc);
756 fenc_alloced = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000757 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000758 }
759 else if (curbuf->b_p_bin)
760 {
761 fenc = (char_u *)""; /* binary: don't convert */
762 fenc_alloced = FALSE;
763 }
764 else if (curbuf->b_help)
765 {
766 char_u firstline[80];
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000767 int fc;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000768
769 /* Help files are either utf-8 or latin1. Try utf-8 first, if this
770 * fails it must be latin1.
771 * Always do this when 'encoding' is "utf-8". Otherwise only do
772 * this when needed to avoid [converted] remarks all the time.
773 * It is needed when the first line contains non-ASCII characters.
774 * That is only in *.??x files. */
775 fenc = (char_u *)"latin1";
776 c = enc_utf8;
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000777 if (!c && !read_stdin)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000778 {
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000779 fc = fname[STRLEN(fname) - 1];
780 if (TOLOWER_ASC(fc) == 'x')
781 {
782 /* Read the first line (and a bit more). Immediately rewind to
783 * the start of the file. If the read() fails "len" is -1. */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +0100784 len = read_eintr(fd, firstline, 80);
Bram Moolenaar8767f522016-07-01 17:17:39 +0200785 vim_lseek(fd, (off_T)0L, SEEK_SET);
Bram Moolenaar75c50c42005-06-04 22:06:24 +0000786 for (p = firstline; p < firstline + len; ++p)
787 if (*p >= 0x80)
788 {
789 c = TRUE;
790 break;
791 }
792 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000793 }
794
795 if (c)
796 {
797 fenc_next = fenc;
798 fenc = (char_u *)"utf-8";
799
800 /* When the file is utf-8 but a character doesn't fit in
801 * 'encoding' don't retry. In help text editing utf-8 bytes
802 * doesn't make sense. */
Bram Moolenaarf193fff2006-04-27 00:02:13 +0000803 if (!enc_utf8)
804 keep_dest_enc = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000805 }
806 fenc_alloced = FALSE;
807 }
808 else if (*p_fencs == NUL)
809 {
810 fenc = curbuf->b_p_fenc; /* use format from buffer */
811 fenc_alloced = FALSE;
812 }
813 else
814 {
815 fenc_next = p_fencs; /* try items in 'fileencodings' */
Bram Moolenaarf077db22019-08-13 00:18:24 +0200816 fenc = next_fenc(&fenc_next, &fenc_alloced);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000817 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000818
819 /*
820 * Jump back here to retry reading the file in different ways.
821 * Reasons to retry:
822 * - encoding conversion failed: try another one from "fenc_next"
823 * - BOM detected and fenc was set, need to setup conversion
824 * - "fileformat" check failed: try another
825 *
826 * Variables set for special retry actions:
827 * "file_rewind" Rewind the file to start reading it again.
828 * "advance_fenc" Advance "fenc" using "fenc_next".
829 * "skip_read" Re-use already read bytes (BOM detected).
830 * "did_iconv" iconv() conversion failed, try 'charconvert'.
831 * "keep_fileformat" Don't reset "fileformat".
832 *
833 * Other status indicators:
834 * "tmpname" When != NULL did conversion with 'charconvert'.
835 * Output file has to be deleted afterwards.
836 * "iconv_fd" When != -1 did conversion with iconv().
837 */
838retry:
839
840 if (file_rewind)
841 {
842 if (read_buffer)
843 {
844 read_buf_lnum = 1;
845 read_buf_col = 0;
846 }
Bram Moolenaar8767f522016-07-01 17:17:39 +0200847 else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000848 {
849 /* Can't rewind the file, give up. */
850 error = TRUE;
851 goto failed;
852 }
853 /* Delete the previously read lines. */
854 while (lnum > from)
855 ml_delete(lnum--, FALSE);
856 file_rewind = FALSE;
Bram Moolenaar910f66f2006-04-05 20:41:53 +0000857 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000858 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000859 curbuf->b_p_bomb = FALSE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +0000860 curbuf->b_start_bomb = FALSE;
861 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000862 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000863 }
864
865 /*
866 * When retrying with another "fenc" and the first time "fileformat"
867 * will be reset.
868 */
869 if (keep_fileformat)
870 keep_fileformat = FALSE;
871 else
872 {
873 if (eap != NULL && eap->force_ff != 0)
Bram Moolenaar1c860362008-11-12 15:05:21 +0000874 {
Bram Moolenaar071d4272004-06-13 20:20:40 +0000875 fileformat = get_fileformat_force(curbuf, eap);
Bram Moolenaar1c860362008-11-12 15:05:21 +0000876 try_unix = try_dos = try_mac = FALSE;
877 }
Bram Moolenaar071d4272004-06-13 20:20:40 +0000878 else if (curbuf->b_p_bin)
879 fileformat = EOL_UNIX; /* binary: use Unix format */
880 else if (*p_ffs == NUL)
881 fileformat = get_fileformat(curbuf);/* use format from buffer */
882 else
883 fileformat = EOL_UNKNOWN; /* detect from file */
884 }
885
Bram Moolenaar13505972019-01-24 15:04:48 +0100886#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000887 if (iconv_fd != (iconv_t)-1)
888 {
889 /* aborted conversion with iconv(), close the descriptor */
890 iconv_close(iconv_fd);
891 iconv_fd = (iconv_t)-1;
892 }
Bram Moolenaar13505972019-01-24 15:04:48 +0100893#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000894
895 if (advance_fenc)
896 {
897 /*
898 * Try the next entry in 'fileencodings'.
899 */
900 advance_fenc = FALSE;
901
902 if (eap != NULL && eap->force_enc != 0)
903 {
904 /* Conversion given with "++cc=" wasn't possible, read
905 * without conversion. */
906 notconverted = TRUE;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +0000907 conv_error = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +0000908 if (fenc_alloced)
909 vim_free(fenc);
910 fenc = (char_u *)"";
911 fenc_alloced = FALSE;
912 }
913 else
914 {
915 if (fenc_alloced)
916 vim_free(fenc);
917 if (fenc_next != NULL)
918 {
Bram Moolenaarf077db22019-08-13 00:18:24 +0200919 fenc = next_fenc(&fenc_next, &fenc_alloced);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000920 }
921 else
922 {
923 fenc = (char_u *)"";
924 fenc_alloced = FALSE;
925 }
926 }
927 if (tmpname != NULL)
928 {
929 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +0100930 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +0000931 }
932 }
933
934 /*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000935 * Conversion may be required when the encoding of the file is different
936 * from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
Bram Moolenaar071d4272004-06-13 20:20:40 +0000937 */
938 fio_flags = 0;
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +0000939 converted = need_conversion(fenc);
940 if (converted)
Bram Moolenaar071d4272004-06-13 20:20:40 +0000941 {
942
943 /* "ucs-bom" means we need to check the first bytes of the file
944 * for a BOM. */
945 if (STRCMP(fenc, ENC_UCSBOM) == 0)
946 fio_flags = FIO_UCSBOM;
947
948 /*
949 * Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
950 * done. This is handled below after read(). Prepare the
951 * fio_flags to avoid having to parse the string each time.
952 * Also check for Unicode to Latin1 conversion, because iconv()
953 * appears not to handle this correctly. This works just like
954 * conversion to UTF-8 except how the resulting character is put in
955 * the buffer.
956 */
957 else if (enc_utf8 || STRCMP(p_enc, "latin1") == 0)
958 fio_flags = get_fio_flags(fenc);
959
Bram Moolenaar4f974752019-02-17 17:44:42 +0100960#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +0000961 /*
962 * Conversion from an MS-Windows codepage to UTF-8 or another codepage
963 * is handled with MultiByteToWideChar().
964 */
965 if (fio_flags == 0)
966 fio_flags = get_win_fio_flags(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +0100967#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000968
Bram Moolenaar13505972019-01-24 15:04:48 +0100969#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +0000970 /* Conversion from Apple MacRoman to latin1 or UTF-8 */
971 if (fio_flags == 0)
972 fio_flags = get_mac_fio_flags(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +0100973#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000974
Bram Moolenaar13505972019-01-24 15:04:48 +0100975#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000976 /*
977 * Try using iconv() if we can't convert internally.
978 */
979 if (fio_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +0100980# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000981 && !did_iconv
Bram Moolenaar13505972019-01-24 15:04:48 +0100982# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000983 )
984 iconv_fd = (iconv_t)my_iconv_open(
985 enc_utf8 ? (char_u *)"utf-8" : p_enc, fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +0100986#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000987
Bram Moolenaar13505972019-01-24 15:04:48 +0100988#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +0000989 /*
990 * Use the 'charconvert' expression when conversion is required
991 * and we can't do it internally or with iconv().
992 */
993 if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
Bram Moolenaarf71d7b92016-08-09 22:14:05 +0200994 && !read_fifo
Bram Moolenaar13505972019-01-24 15:04:48 +0100995# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +0000996 && iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +0100997# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +0000998 )
999 {
Bram Moolenaar13505972019-01-24 15:04:48 +01001000# ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001001 did_iconv = FALSE;
Bram Moolenaar13505972019-01-24 15:04:48 +01001002# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001003 /* Skip conversion when it's already done (retry for wrong
1004 * "fileformat"). */
1005 if (tmpname == NULL)
1006 {
1007 tmpname = readfile_charconvert(fname, fenc, &fd);
1008 if (tmpname == NULL)
1009 {
1010 /* Conversion failed. Try another one. */
1011 advance_fenc = TRUE;
1012 if (fd < 0)
1013 {
1014 /* Re-opening the original file failed! */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01001015 emsg(_("E202: Conversion made file unreadable!"));
Bram Moolenaar071d4272004-06-13 20:20:40 +00001016 error = TRUE;
1017 goto failed;
1018 }
1019 goto retry;
1020 }
1021 }
1022 }
1023 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001024#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001025 {
1026 if (fio_flags == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001027#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001028 && iconv_fd == (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001029#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001030 )
1031 {
1032 /* Conversion wanted but we can't.
1033 * Try the next conversion in 'fileencodings' */
1034 advance_fenc = TRUE;
1035 goto retry;
1036 }
1037 }
1038 }
1039
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001040 /* Set "can_retry" when it's possible to rewind the file and try with
Bram Moolenaar071d4272004-06-13 20:20:40 +00001041 * another "fenc" value. It's FALSE when no other "fenc" to try, reading
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001042 * stdin or fixed at a specific encoding. */
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001043 can_retry = (*fenc != NUL && !read_stdin && !read_fifo && !keep_dest_enc);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001044
1045 if (!skip_read)
1046 {
1047 linerest = 0;
1048 filesize = 0;
1049 skip_count = lines_to_skip;
1050 read_count = lines_to_read;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001051 conv_restlen = 0;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001052#ifdef FEAT_PERSISTENT_UNDO
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001053 read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
1054 && curbuf->b_ffname != NULL
1055 && curbuf->b_p_udf
1056 && !filtering
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02001057 && !read_fifo
Bram Moolenaar59f931e2010-07-24 20:27:03 +02001058 && !read_stdin
1059 && !read_buffer);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02001060 if (read_undo_file)
1061 sha256_start(&sha_ctx);
1062#endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001063#ifdef FEAT_CRYPT
1064 if (curbuf->b_cryptstate != NULL)
1065 {
1066 /* Need to free the state, but keep the key, don't want to ask for
1067 * it again. */
1068 crypt_free_state(curbuf->b_cryptstate);
1069 curbuf->b_cryptstate = NULL;
1070 }
1071#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001072 }
1073
1074 while (!error && !got_int)
1075 {
1076 /*
1077 * We allocate as much space for the file as we can get, plus
1078 * space for the old line plus room for one terminating NUL.
1079 * The amount is limited by the fact that read() only can read
1080 * upto max_unsigned characters (and other things).
1081 */
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001082 if (!skip_read)
1083 {
Bram Moolenaar30276f22019-01-24 17:59:39 +01001084#if defined(SSIZE_MAX) && (SSIZE_MAX < 0x10000L)
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001085 size = SSIZE_MAX; /* use max I/O size, 52K */
Bram Moolenaar30276f22019-01-24 17:59:39 +01001086#else
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001087 /* Use buffer >= 64K. Add linerest to double the size if the
1088 * line gets very long, to avoid a lot of copying. But don't
1089 * read more than 1 Mbyte at a time, so we can be interrupted.
1090 */
1091 size = 0x10000L + linerest;
1092 if (size > 0x100000L)
1093 size = 0x100000L;
Bram Moolenaar13d3b052018-04-29 13:34:47 +02001094#endif
1095 }
1096
1097 /* Protect against the argument of lalloc() going negative. */
Bram Moolenaar30276f22019-01-24 17:59:39 +01001098 if (size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001099 {
1100 ++split;
1101 *ptr = NL; /* split line by inserting a NL */
1102 size = 1;
1103 }
1104 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00001105 {
1106 if (!skip_read)
1107 {
Bram Moolenaarc1e37902006-04-18 21:55:01 +00001108 for ( ; size >= 10; size = (long)((long_u)size >> 1))
Bram Moolenaar071d4272004-06-13 20:20:40 +00001109 {
Bram Moolenaar18a4ba22019-05-24 19:39:03 +02001110 if ((new_buffer = lalloc(size + linerest + 1,
Bram Moolenaar071d4272004-06-13 20:20:40 +00001111 FALSE)) != NULL)
1112 break;
1113 }
1114 if (new_buffer == NULL)
1115 {
1116 do_outofmem_msg((long_u)(size * 2 + linerest + 1));
1117 error = TRUE;
1118 break;
1119 }
1120 if (linerest) /* copy characters from the previous buffer */
1121 mch_memmove(new_buffer, ptr - linerest, (size_t)linerest);
1122 vim_free(buffer);
1123 buffer = new_buffer;
1124 ptr = buffer + linerest;
1125 line_start = buffer;
1126
Bram Moolenaar071d4272004-06-13 20:20:40 +00001127 /* May need room to translate into.
1128 * For iconv() we don't really know the required space, use a
1129 * factor ICONV_MULT.
1130 * latin1 to utf-8: 1 byte becomes up to 2 bytes
1131 * utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
1132 * become up to 4 bytes, size must be multiple of 2
1133 * ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
1134 * multiple of 2
1135 * ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
1136 * multiple of 4 */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001137 real_size = (int)size;
Bram Moolenaar13505972019-01-24 15:04:48 +01001138#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001139 if (iconv_fd != (iconv_t)-1)
1140 size = size / ICONV_MULT;
1141 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001142#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001143 if (fio_flags & FIO_LATIN1)
1144 size = size / 2;
1145 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1146 size = (size * 2 / 3) & ~1;
1147 else if (fio_flags & FIO_UCS4)
1148 size = (size * 2 / 3) & ~3;
1149 else if (fio_flags == FIO_UCSBOM)
1150 size = size / ICONV_MULT; /* worst case */
Bram Moolenaar4f974752019-02-17 17:44:42 +01001151#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001152 else if (fio_flags & FIO_CODEPAGE)
1153 size = size / ICONV_MULT; /* also worst case */
Bram Moolenaar13505972019-01-24 15:04:48 +01001154#endif
1155#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001156 else if (fio_flags & FIO_MACROMAN)
1157 size = size / ICONV_MULT; /* also worst case */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001158#endif
1159
Bram Moolenaar071d4272004-06-13 20:20:40 +00001160 if (conv_restlen > 0)
1161 {
1162 /* Insert unconverted bytes from previous line. */
1163 mch_memmove(ptr, conv_rest, conv_restlen);
1164 ptr += conv_restlen;
1165 size -= conv_restlen;
1166 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001167
1168 if (read_buffer)
1169 {
1170 /*
1171 * Read bytes from curbuf. Used for converting text read
1172 * from stdin.
1173 */
1174 if (read_buf_lnum > from)
1175 size = 0;
1176 else
1177 {
1178 int n, ni;
1179 long tlen;
1180
1181 tlen = 0;
1182 for (;;)
1183 {
1184 p = ml_get(read_buf_lnum) + read_buf_col;
1185 n = (int)STRLEN(p);
1186 if ((int)tlen + n + 1 > size)
1187 {
1188 /* Filled up to "size", append partial line.
1189 * Change NL to NUL to reverse the effect done
1190 * below. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001191 n = (int)(size - tlen);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001192 for (ni = 0; ni < n; ++ni)
1193 {
1194 if (p[ni] == NL)
1195 ptr[tlen++] = NUL;
1196 else
1197 ptr[tlen++] = p[ni];
1198 }
1199 read_buf_col += n;
1200 break;
1201 }
1202 else
1203 {
1204 /* Append whole line and new-line. Change NL
1205 * to NUL to reverse the effect done below. */
1206 for (ni = 0; ni < n; ++ni)
1207 {
1208 if (p[ni] == NL)
1209 ptr[tlen++] = NUL;
1210 else
1211 ptr[tlen++] = p[ni];
1212 }
1213 ptr[tlen++] = NL;
1214 read_buf_col = 0;
1215 if (++read_buf_lnum > from)
1216 {
1217 /* When the last line didn't have an
1218 * end-of-line don't add it now either. */
1219 if (!curbuf->b_p_eol)
1220 --tlen;
1221 size = tlen;
1222 break;
1223 }
1224 }
1225 }
1226 }
1227 }
1228 else
1229 {
1230 /*
1231 * Read bytes from the file.
1232 */
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01001233 size = read_eintr(fd, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001234 }
1235
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001236#ifdef FEAT_CRYPT
1237 /*
1238 * At start of file: Check for magic number of encryption.
1239 */
1240 if (filesize == 0 && size > 0)
1241 cryptkey = check_for_cryptkey(cryptkey, ptr, &size,
1242 &filesize, newfile, sfname,
1243 &did_ask_for_key);
1244 /*
1245 * Decrypt the read bytes. This is done before checking for
1246 * EOF because the crypt layer may be buffering.
1247 */
Bram Moolenaar829aa642017-08-23 22:32:35 +02001248 if (cryptkey != NULL && curbuf->b_cryptstate != NULL
1249 && size > 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001250 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001251# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001252 if (crypt_works_inplace(curbuf->b_cryptstate))
1253 {
Bram Moolenaar987411d2019-01-18 22:48:34 +01001254# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001255 crypt_decode_inplace(curbuf->b_cryptstate, ptr, size);
Bram Moolenaar987411d2019-01-18 22:48:34 +01001256# ifdef CRYPT_NOT_INPLACE
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001257 }
1258 else
1259 {
1260 char_u *newptr = NULL;
1261 int decrypted_size;
1262
1263 decrypted_size = crypt_decode_alloc(
1264 curbuf->b_cryptstate, ptr, size, &newptr);
1265
1266 /* If the crypt layer is buffering, not producing
1267 * anything yet, need to read more. */
Bram Moolenaar1c17ffa2018-04-24 15:19:04 +02001268 if (decrypted_size == 0)
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001269 continue;
1270
1271 if (linerest == 0)
1272 {
1273 /* Simple case: reuse returned buffer (may be
1274 * NULL, checked later). */
1275 new_buffer = newptr;
1276 }
1277 else
1278 {
1279 long_u new_size;
1280
1281 /* Need new buffer to add bytes carried over. */
1282 new_size = (long_u)(decrypted_size + linerest + 1);
1283 new_buffer = lalloc(new_size, FALSE);
1284 if (new_buffer == NULL)
1285 {
1286 do_outofmem_msg(new_size);
1287 error = TRUE;
1288 break;
1289 }
1290
1291 mch_memmove(new_buffer, buffer, linerest);
1292 if (newptr != NULL)
1293 mch_memmove(new_buffer + linerest, newptr,
1294 decrypted_size);
1295 }
1296
1297 if (new_buffer != NULL)
1298 {
1299 vim_free(buffer);
1300 buffer = new_buffer;
1301 new_buffer = NULL;
1302 line_start = buffer;
1303 ptr = buffer + linerest;
1304 }
1305 size = decrypted_size;
1306 }
Bram Moolenaar987411d2019-01-18 22:48:34 +01001307# endif
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001308 }
1309#endif
1310
Bram Moolenaar071d4272004-06-13 20:20:40 +00001311 if (size <= 0)
1312 {
1313 if (size < 0) /* read error */
1314 error = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001315 else if (conv_restlen > 0)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001316 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001317 /*
1318 * Reached end-of-file but some trailing bytes could
1319 * not be converted. Truncated file?
1320 */
1321
1322 /* When we did a conversion report an error. */
1323 if (fio_flags != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001324#ifdef USE_ICONV
Bram Moolenaarf453d352008-06-04 17:37:34 +00001325 || iconv_fd != (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001326#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001327 )
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001328 {
Bram Moolenaare8d95302013-04-24 16:34:02 +02001329 if (can_retry)
1330 goto rewind_retry;
Bram Moolenaarf453d352008-06-04 17:37:34 +00001331 if (conv_error == 0)
1332 conv_error = curbuf->b_ml.ml_line_count
1333 - linecnt + 1;
1334 }
1335 /* Remember the first linenr with an illegal byte */
1336 else if (illegal_byte == 0)
1337 illegal_byte = curbuf->b_ml.ml_line_count
1338 - linecnt + 1;
1339 if (bad_char_behavior == BAD_DROP)
1340 {
1341 *(ptr - conv_restlen) = NUL;
1342 conv_restlen = 0;
1343 }
1344 else
1345 {
1346 /* Replace the trailing bytes with the replacement
1347 * character if we were converting; if we weren't,
1348 * leave the UTF8 checking code to do it, as it
1349 * works slightly differently. */
1350 if (bad_char_behavior != BAD_KEEP && (fio_flags != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001351#ifdef USE_ICONV
Bram Moolenaarf453d352008-06-04 17:37:34 +00001352 || iconv_fd != (iconv_t)-1
Bram Moolenaar13505972019-01-24 15:04:48 +01001353#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001354 ))
1355 {
1356 while (conv_restlen > 0)
1357 {
1358 *(--ptr) = bad_char_behavior;
1359 --conv_restlen;
1360 }
1361 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001362 fio_flags = 0; /* don't convert this */
Bram Moolenaar13505972019-01-24 15:04:48 +01001363#ifdef USE_ICONV
Bram Moolenaarb21e5842006-04-16 18:30:08 +00001364 if (iconv_fd != (iconv_t)-1)
1365 {
1366 iconv_close(iconv_fd);
1367 iconv_fd = (iconv_t)-1;
1368 }
Bram Moolenaar13505972019-01-24 15:04:48 +01001369#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001370 }
1371 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001372 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001373 }
1374 skip_read = FALSE;
1375
Bram Moolenaar071d4272004-06-13 20:20:40 +00001376 /*
1377 * At start of file (or after crypt magic number): Check for BOM.
1378 * Also check for a BOM for other Unicode encodings, but not after
1379 * converting with 'charconvert' or when a BOM has already been
1380 * found.
1381 */
1382 if ((filesize == 0
Bram Moolenaar13505972019-01-24 15:04:48 +01001383#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02001384 || (cryptkey != NULL
1385 && filesize == crypt_get_header_len(
1386 crypt_get_method_nr(curbuf)))
Bram Moolenaar13505972019-01-24 15:04:48 +01001387#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001388 )
1389 && (fio_flags == FIO_UCSBOM
1390 || (!curbuf->b_p_bomb
1391 && tmpname == NULL
1392 && (*fenc == 'u' || (*fenc == NUL && enc_utf8)))))
1393 {
1394 char_u *ccname;
1395 int blen;
1396
1397 /* no BOM detection in a short file or in binary mode */
1398 if (size < 2 || curbuf->b_p_bin)
1399 ccname = NULL;
1400 else
1401 ccname = check_for_bom(ptr, size, &blen,
1402 fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
1403 if (ccname != NULL)
1404 {
1405 /* Remove BOM from the text */
1406 filesize += blen;
1407 size -= blen;
1408 mch_memmove(ptr, ptr + blen, (size_t)size);
Bram Moolenaar910f66f2006-04-05 20:41:53 +00001409 if (set_options)
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001410 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001411 curbuf->b_p_bomb = TRUE;
Bram Moolenaar83eb8852007-08-12 13:51:26 +00001412 curbuf->b_start_bomb = TRUE;
1413 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001414 }
1415
1416 if (fio_flags == FIO_UCSBOM)
1417 {
1418 if (ccname == NULL)
1419 {
1420 /* No BOM detected: retry with next encoding. */
1421 advance_fenc = TRUE;
1422 }
1423 else
1424 {
1425 /* BOM detected: set "fenc" and jump back */
1426 if (fenc_alloced)
1427 vim_free(fenc);
1428 fenc = ccname;
1429 fenc_alloced = FALSE;
1430 }
1431 /* retry reading without getting new bytes or rewinding */
1432 skip_read = TRUE;
1433 goto retry;
1434 }
1435 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001436
1437 /* Include not converted bytes. */
1438 ptr -= conv_restlen;
1439 size += conv_restlen;
1440 conv_restlen = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001441 /*
1442 * Break here for a read error or end-of-file.
1443 */
1444 if (size <= 0)
1445 break;
1446
Bram Moolenaar071d4272004-06-13 20:20:40 +00001447
Bram Moolenaar13505972019-01-24 15:04:48 +01001448#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00001449 if (iconv_fd != (iconv_t)-1)
1450 {
1451 /*
1452 * Attempt conversion of the read bytes to 'encoding' using
1453 * iconv().
1454 */
1455 const char *fromp;
1456 char *top;
1457 size_t from_size;
1458 size_t to_size;
1459
1460 fromp = (char *)ptr;
1461 from_size = size;
1462 ptr += size;
1463 top = (char *)ptr;
1464 to_size = real_size - size;
1465
1466 /*
1467 * If there is conversion error or not enough room try using
Bram Moolenaar19a09a12005-03-04 23:39:37 +00001468 * another conversion. Except for when there is no
1469 * alternative (help files).
Bram Moolenaar071d4272004-06-13 20:20:40 +00001470 */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001471 while ((iconv(iconv_fd, (void *)&fromp, &from_size,
1472 &top, &to_size)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001473 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
1474 || from_size > CONV_RESTLEN)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001475 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001476 if (can_retry)
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001477 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001478 if (conv_error == 0)
1479 conv_error = readfile_linenr(linecnt,
1480 ptr, (char_u *)top);
Bram Moolenaar42eeac32005-06-29 22:40:58 +00001481
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001482 /* Deal with a bad byte and continue with the next. */
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001483 ++fromp;
1484 --from_size;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001485 if (bad_char_behavior == BAD_KEEP)
1486 {
1487 *top++ = *(fromp - 1);
1488 --to_size;
1489 }
1490 else if (bad_char_behavior != BAD_DROP)
1491 {
1492 *top++ = bad_char_behavior;
1493 --to_size;
1494 }
Bram Moolenaar8cd06ca2005-02-28 22:44:58 +00001495 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001496
1497 if (from_size > 0)
1498 {
1499 /* Some remaining characters, keep them for the next
1500 * round. */
1501 mch_memmove(conv_rest, (char_u *)fromp, from_size);
1502 conv_restlen = (int)from_size;
1503 }
1504
1505 /* move the linerest to before the converted characters */
1506 line_start = ptr - linerest;
1507 mch_memmove(line_start, buffer, (size_t)linerest);
1508 size = (long)((char_u *)top - ptr);
1509 }
Bram Moolenaar13505972019-01-24 15:04:48 +01001510#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001511
Bram Moolenaar4f974752019-02-17 17:44:42 +01001512#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00001513 if (fio_flags & FIO_CODEPAGE)
1514 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001515 char_u *src, *dst;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001516 WCHAR ucs2buf[3];
1517 int ucs2len;
1518 int codepage = FIO_GET_CP(fio_flags);
1519 int bytelen;
1520 int found_bad;
1521 char replstr[2];
1522
Bram Moolenaar071d4272004-06-13 20:20:40 +00001523 /*
1524 * Conversion from an MS-Windows codepage or UTF-8 to UTF-8 or
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001525 * a codepage, using standard MS-Windows functions. This
1526 * requires two steps:
1527 * 1. convert from 'fileencoding' to ucs-2
1528 * 2. convert from ucs-2 to 'encoding'
Bram Moolenaar071d4272004-06-13 20:20:40 +00001529 *
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001530 * Because there may be illegal bytes AND an incomplete byte
1531 * sequence at the end, we may have to do the conversion one
1532 * character at a time to get it right.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001533 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001534
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001535 /* Replacement string for WideCharToMultiByte(). */
1536 if (bad_char_behavior > 0)
1537 replstr[0] = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001538 else
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001539 replstr[0] = '?';
1540 replstr[1] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001541
1542 /*
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001543 * Move the bytes to the end of the buffer, so that we have
1544 * room to put the result at the start.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001545 */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001546 src = ptr + real_size - size;
1547 mch_memmove(src, ptr, size);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001548
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001549 /*
1550 * Do the conversion.
1551 */
1552 dst = ptr;
1553 size = size;
1554 while (size > 0)
1555 {
1556 found_bad = FALSE;
1557
1558# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
1559 if (codepage == CP_UTF8)
1560 {
1561 /* Handle CP_UTF8 input ourselves to be able to handle
1562 * trailing bytes properly.
1563 * Get one UTF-8 character from src. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001564 bytelen = (int)utf_ptr2len_len(src, size);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001565 if (bytelen > size)
1566 {
1567 /* Only got some bytes of a character. Normally
1568 * it's put in "conv_rest", but if it's too long
1569 * deal with it as if they were illegal bytes. */
1570 if (bytelen <= CONV_RESTLEN)
1571 break;
1572
1573 /* weird overlong byte sequence */
1574 bytelen = size;
1575 found_bad = TRUE;
1576 }
1577 else
1578 {
Bram Moolenaarc01140a2006-03-24 22:21:52 +00001579 int u8c = utf_ptr2char(src);
1580
Bram Moolenaar86e01082005-12-29 22:45:34 +00001581 if (u8c > 0xffff || (*src >= 0x80 && bytelen == 1))
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001582 found_bad = TRUE;
1583 ucs2buf[0] = u8c;
1584 ucs2len = 1;
1585 }
1586 }
1587 else
1588# endif
1589 {
1590 /* We don't know how long the byte sequence is, try
1591 * from one to three bytes. */
1592 for (bytelen = 1; bytelen <= size && bytelen <= 3;
1593 ++bytelen)
1594 {
1595 ucs2len = MultiByteToWideChar(codepage,
1596 MB_ERR_INVALID_CHARS,
1597 (LPCSTR)src, bytelen,
1598 ucs2buf, 3);
1599 if (ucs2len > 0)
1600 break;
1601 }
1602 if (ucs2len == 0)
1603 {
1604 /* If we have only one byte then it's probably an
1605 * incomplete byte sequence. Otherwise discard
1606 * one byte as a bad character. */
1607 if (size == 1)
1608 break;
1609 found_bad = TRUE;
1610 bytelen = 1;
1611 }
1612 }
1613
1614 if (!found_bad)
1615 {
1616 int i;
1617
1618 /* Convert "ucs2buf[ucs2len]" to 'enc' in "dst". */
1619 if (enc_utf8)
1620 {
1621 /* From UCS-2 to UTF-8. Cannot fail. */
1622 for (i = 0; i < ucs2len; ++i)
1623 dst += utf_char2bytes(ucs2buf[i], dst);
1624 }
1625 else
1626 {
1627 BOOL bad = FALSE;
1628 int dstlen;
1629
1630 /* From UCS-2 to "enc_codepage". If the
1631 * conversion uses the default character "?",
1632 * the data doesn't fit in this encoding. */
1633 dstlen = WideCharToMultiByte(enc_codepage, 0,
1634 (LPCWSTR)ucs2buf, ucs2len,
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001635 (LPSTR)dst, (int)(src - dst),
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001636 replstr, &bad);
1637 if (bad)
1638 found_bad = TRUE;
1639 else
1640 dst += dstlen;
1641 }
1642 }
1643
1644 if (found_bad)
1645 {
1646 /* Deal with bytes we can't convert. */
1647 if (can_retry)
1648 goto rewind_retry;
1649 if (conv_error == 0)
1650 conv_error = readfile_linenr(linecnt, ptr, dst);
1651 if (bad_char_behavior != BAD_DROP)
1652 {
1653 if (bad_char_behavior == BAD_KEEP)
1654 {
1655 mch_memmove(dst, src, bytelen);
1656 dst += bytelen;
1657 }
1658 else
1659 *dst++ = bad_char_behavior;
1660 }
1661 }
1662
1663 src += bytelen;
1664 size -= bytelen;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001665 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001666
1667 if (size > 0)
1668 {
1669 /* An incomplete byte sequence remaining. */
1670 mch_memmove(conv_rest, src, size);
1671 conv_restlen = size;
1672 }
1673
1674 /* The new size is equal to how much "dst" was advanced. */
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001675 size = (long)(dst - ptr);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001676 }
1677 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001678#endif
1679#ifdef MACOS_CONVERT
Bram Moolenaar071d4272004-06-13 20:20:40 +00001680 if (fio_flags & FIO_MACROMAN)
1681 {
1682 /*
1683 * Conversion from Apple MacRoman char encoding to UTF-8 or
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001684 * latin1. This is in os_mac_conv.c.
Bram Moolenaar071d4272004-06-13 20:20:40 +00001685 */
Bram Moolenaarab79bcb2004-07-18 21:34:53 +00001686 if (macroman2enc(ptr, &size, real_size) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001687 goto rewind_retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001688 }
1689 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001690#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00001691 if (fio_flags != 0)
1692 {
1693 int u8c;
1694 char_u *dest;
1695 char_u *tail = NULL;
1696
1697 /*
1698 * "enc_utf8" set: Convert Unicode or Latin1 to UTF-8.
1699 * "enc_utf8" not set: Convert Unicode to Latin1.
1700 * Go from end to start through the buffer, because the number
1701 * of bytes may increase.
1702 * "dest" points to after where the UTF-8 bytes go, "p" points
1703 * to after the next character to convert.
1704 */
1705 dest = ptr + real_size;
1706 if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8)
1707 {
1708 p = ptr + size;
1709 if (fio_flags == FIO_UTF8)
1710 {
1711 /* Check for a trailing incomplete UTF-8 sequence */
1712 tail = ptr + size - 1;
1713 while (tail > ptr && (*tail & 0xc0) == 0x80)
1714 --tail;
1715 if (tail + utf_byte2len(*tail) <= ptr + size)
1716 tail = NULL;
1717 else
1718 p = tail;
1719 }
1720 }
1721 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1722 {
1723 /* Check for a trailing byte */
1724 p = ptr + (size & ~1);
1725 if (size & 1)
1726 tail = p;
1727 if ((fio_flags & FIO_UTF16) && p > ptr)
1728 {
1729 /* Check for a trailing leading word */
1730 if (fio_flags & FIO_ENDIAN_L)
1731 {
1732 u8c = (*--p << 8);
1733 u8c += *--p;
1734 }
1735 else
1736 {
1737 u8c = *--p;
1738 u8c += (*--p << 8);
1739 }
1740 if (u8c >= 0xd800 && u8c <= 0xdbff)
1741 tail = p;
1742 else
1743 p += 2;
1744 }
1745 }
1746 else /* FIO_UCS4 */
1747 {
1748 /* Check for trailing 1, 2 or 3 bytes */
1749 p = ptr + (size & ~3);
1750 if (size & 3)
1751 tail = p;
1752 }
1753
1754 /* If there is a trailing incomplete sequence move it to
1755 * conv_rest[]. */
1756 if (tail != NULL)
1757 {
1758 conv_restlen = (int)((ptr + size) - tail);
1759 mch_memmove(conv_rest, (char_u *)tail, conv_restlen);
1760 size -= conv_restlen;
1761 }
1762
1763
1764 while (p > ptr)
1765 {
1766 if (fio_flags & FIO_LATIN1)
1767 u8c = *--p;
1768 else if (fio_flags & (FIO_UCS2 | FIO_UTF16))
1769 {
1770 if (fio_flags & FIO_ENDIAN_L)
1771 {
1772 u8c = (*--p << 8);
1773 u8c += *--p;
1774 }
1775 else
1776 {
1777 u8c = *--p;
1778 u8c += (*--p << 8);
1779 }
1780 if ((fio_flags & FIO_UTF16)
1781 && u8c >= 0xdc00 && u8c <= 0xdfff)
1782 {
1783 int u16c;
1784
1785 if (p == ptr)
1786 {
1787 /* Missing leading word. */
1788 if (can_retry)
1789 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001790 if (conv_error == 0)
1791 conv_error = readfile_linenr(linecnt,
1792 ptr, p);
1793 if (bad_char_behavior == BAD_DROP)
1794 continue;
1795 if (bad_char_behavior != BAD_KEEP)
1796 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001797 }
1798
1799 /* found second word of double-word, get the first
1800 * word and compute the resulting character */
1801 if (fio_flags & FIO_ENDIAN_L)
1802 {
1803 u16c = (*--p << 8);
1804 u16c += *--p;
1805 }
1806 else
1807 {
1808 u16c = *--p;
1809 u16c += (*--p << 8);
1810 }
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001811 u8c = 0x10000 + ((u16c & 0x3ff) << 10)
1812 + (u8c & 0x3ff);
1813
Bram Moolenaar071d4272004-06-13 20:20:40 +00001814 /* Check if the word is indeed a leading word. */
1815 if (u16c < 0xd800 || u16c > 0xdbff)
1816 {
1817 if (can_retry)
1818 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001819 if (conv_error == 0)
1820 conv_error = readfile_linenr(linecnt,
1821 ptr, p);
1822 if (bad_char_behavior == BAD_DROP)
1823 continue;
1824 if (bad_char_behavior != BAD_KEEP)
1825 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001826 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001827 }
1828 }
1829 else if (fio_flags & FIO_UCS4)
1830 {
1831 if (fio_flags & FIO_ENDIAN_L)
1832 {
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001833 u8c = (unsigned)*--p << 24;
1834 u8c += (unsigned)*--p << 16;
1835 u8c += (unsigned)*--p << 8;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001836 u8c += *--p;
1837 }
1838 else /* big endian */
1839 {
1840 u8c = *--p;
Bram Moolenaardc1c9812017-10-27 22:15:24 +02001841 u8c += (unsigned)*--p << 8;
1842 u8c += (unsigned)*--p << 16;
1843 u8c += (unsigned)*--p << 24;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001844 }
1845 }
1846 else /* UTF-8 */
1847 {
1848 if (*--p < 0x80)
1849 u8c = *p;
1850 else
1851 {
1852 len = utf_head_off(ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001853 p -= len;
1854 u8c = utf_ptr2char(p);
Bram Moolenaar071d4272004-06-13 20:20:40 +00001855 if (len == 0)
1856 {
1857 /* Not a valid UTF-8 character, retry with
1858 * another fenc when possible, otherwise just
1859 * report the error. */
1860 if (can_retry)
1861 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001862 if (conv_error == 0)
1863 conv_error = readfile_linenr(linecnt,
1864 ptr, p);
1865 if (bad_char_behavior == BAD_DROP)
1866 continue;
1867 if (bad_char_behavior != BAD_KEEP)
1868 u8c = bad_char_behavior;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001869 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001870 }
1871 }
1872 if (enc_utf8) /* produce UTF-8 */
1873 {
1874 dest -= utf_char2len(u8c);
1875 (void)utf_char2bytes(u8c, dest);
1876 }
1877 else /* produce Latin1 */
1878 {
1879 --dest;
1880 if (u8c >= 0x100)
1881 {
1882 /* character doesn't fit in latin1, retry with
1883 * another fenc when possible, otherwise just
1884 * report the error. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001885 if (can_retry)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001886 goto rewind_retry;
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001887 if (conv_error == 0)
1888 conv_error = readfile_linenr(linecnt, ptr, p);
1889 if (bad_char_behavior == BAD_DROP)
1890 ++dest;
1891 else if (bad_char_behavior == BAD_KEEP)
1892 *dest = u8c;
1893 else if (eap != NULL && eap->bad_char != 0)
1894 *dest = bad_char_behavior;
1895 else
1896 *dest = 0xBF;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001897 }
1898 else
1899 *dest = u8c;
1900 }
1901 }
1902
1903 /* move the linerest to before the converted characters */
1904 line_start = dest - linerest;
1905 mch_memmove(line_start, buffer, (size_t)linerest);
1906 size = (long)((ptr + real_size) - dest);
1907 ptr = dest;
1908 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001909 else if (enc_utf8 && !curbuf->b_p_bin)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001910 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001911 int incomplete_tail = FALSE;
1912
1913 /* Reading UTF-8: Check if the bytes are valid UTF-8. */
1914 for (p = ptr; ; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001915 {
Bram Moolenaara93fa7e2006-04-17 22:14:47 +00001916 int todo = (int)((ptr + size) - p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001917 int l;
1918
1919 if (todo <= 0)
1920 break;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001921 if (*p >= 0x80)
1922 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00001923 /* A length of 1 means it's an illegal byte. Accept
1924 * an incomplete character at the end though, the next
1925 * read() will get the next bytes, we'll check it
1926 * then. */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001927 l = utf_ptr2len_len(p, todo);
Bram Moolenaarf453d352008-06-04 17:37:34 +00001928 if (l > todo && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001929 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001930 /* Avoid retrying with a different encoding when
1931 * a truncated file is more likely, or attempting
1932 * to read the rest of an incomplete sequence when
1933 * we have already done so. */
1934 if (p > ptr || filesize > 0)
1935 incomplete_tail = TRUE;
1936 /* Incomplete byte sequence, move it to conv_rest[]
1937 * and try to read the rest of it, unless we've
1938 * already done so. */
1939 if (p > ptr)
1940 {
1941 conv_restlen = todo;
1942 mch_memmove(conv_rest, p, conv_restlen);
1943 size -= conv_restlen;
1944 break;
1945 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001946 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001947 if (l == 1 || l > todo)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001948 {
1949 /* Illegal byte. If we can try another encoding
Bram Moolenaarf453d352008-06-04 17:37:34 +00001950 * do that, unless at EOF where a truncated
1951 * file is more likely than a conversion error. */
1952 if (can_retry && !incomplete_tail)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001953 break;
Bram Moolenaar13505972019-01-24 15:04:48 +01001954#ifdef USE_ICONV
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001955 /* When we did a conversion report an error. */
1956 if (iconv_fd != (iconv_t)-1 && conv_error == 0)
1957 conv_error = readfile_linenr(linecnt, ptr, p);
Bram Moolenaar13505972019-01-24 15:04:48 +01001958#endif
Bram Moolenaarf453d352008-06-04 17:37:34 +00001959 /* Remember the first linenr with an illegal byte */
1960 if (conv_error == 0 && illegal_byte == 0)
1961 illegal_byte = readfile_linenr(linecnt, ptr, p);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001962
1963 /* Drop, keep or replace the bad byte. */
1964 if (bad_char_behavior == BAD_DROP)
1965 {
Bram Moolenaarf453d352008-06-04 17:37:34 +00001966 mch_memmove(p, p + 1, todo - 1);
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001967 --p;
1968 --size;
1969 }
1970 else if (bad_char_behavior != BAD_KEEP)
1971 *p = bad_char_behavior;
1972 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001973 else
1974 p += l - 1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001975 }
1976 }
Bram Moolenaarf453d352008-06-04 17:37:34 +00001977 if (p < ptr + size && !incomplete_tail)
Bram Moolenaar071d4272004-06-13 20:20:40 +00001978 {
1979 /* Detected a UTF-8 error. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00001980rewind_retry:
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001981 /* Retry reading with another conversion. */
Bram Moolenaar13505972019-01-24 15:04:48 +01001982#if defined(FEAT_EVAL) && defined(USE_ICONV)
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001983 if (*p_ccv != NUL && iconv_fd != (iconv_t)-1)
1984 /* iconv() failed, try 'charconvert' */
1985 did_iconv = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001986 else
Bram Moolenaar13505972019-01-24 15:04:48 +01001987#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00001988 /* use next item from 'fileencodings' */
1989 advance_fenc = TRUE;
1990 file_rewind = TRUE;
1991 goto retry;
Bram Moolenaar071d4272004-06-13 20:20:40 +00001992 }
1993 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00001994
1995 /* count the number of characters (after conversion!) */
1996 filesize += size;
1997
1998 /*
1999 * when reading the first part of a file: guess EOL type
2000 */
2001 if (fileformat == EOL_UNKNOWN)
2002 {
2003 /* First try finding a NL, for Dos and Unix */
2004 if (try_dos || try_unix)
2005 {
Bram Moolenaarc6b72172015-02-27 17:48:09 +01002006 /* Reset the carriage return counter. */
2007 if (try_mac)
2008 try_mac = 1;
2009
Bram Moolenaar071d4272004-06-13 20:20:40 +00002010 for (p = ptr; p < ptr + size; ++p)
2011 {
2012 if (*p == NL)
2013 {
2014 if (!try_unix
2015 || (try_dos && p > ptr && p[-1] == CAR))
2016 fileformat = EOL_DOS;
2017 else
2018 fileformat = EOL_UNIX;
2019 break;
2020 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002021 else if (*p == CAR && try_mac)
2022 try_mac++;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002023 }
2024
2025 /* Don't give in to EOL_UNIX if EOL_MAC is more likely */
2026 if (fileformat == EOL_UNIX && try_mac)
2027 {
2028 /* Need to reset the counters when retrying fenc. */
2029 try_mac = 1;
2030 try_unix = 1;
2031 for (; p >= ptr && *p != CAR; p--)
2032 ;
2033 if (p >= ptr)
2034 {
2035 for (p = ptr; p < ptr + size; ++p)
2036 {
2037 if (*p == NL)
2038 try_unix++;
2039 else if (*p == CAR)
2040 try_mac++;
2041 }
2042 if (try_mac > try_unix)
2043 fileformat = EOL_MAC;
2044 }
2045 }
Bram Moolenaar05eb6122015-02-17 14:15:19 +01002046 else if (fileformat == EOL_UNKNOWN && try_mac == 1)
2047 /* Looking for CR but found no end-of-line markers at
2048 * all: use the default format. */
2049 fileformat = default_fileformat();
Bram Moolenaar071d4272004-06-13 20:20:40 +00002050 }
2051
2052 /* No NL found: may use Mac format */
2053 if (fileformat == EOL_UNKNOWN && try_mac)
2054 fileformat = EOL_MAC;
2055
2056 /* Still nothing found? Use first format in 'ffs' */
2057 if (fileformat == EOL_UNKNOWN)
2058 fileformat = default_fileformat();
2059
2060 /* if editing a new file: may set p_tx and p_ff */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002061 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002062 set_fileformat(fileformat, OPT_LOCAL);
2063 }
2064 }
2065
2066 /*
2067 * This loop is executed once for every character read.
2068 * Keep it fast!
2069 */
2070 if (fileformat == EOL_MAC)
2071 {
2072 --ptr;
2073 while (++ptr, --size >= 0)
2074 {
2075 /* catch most common case first */
2076 if ((c = *ptr) != NUL && c != CAR && c != NL)
2077 continue;
2078 if (c == NUL)
2079 *ptr = NL; /* NULs are replaced by newlines! */
2080 else if (c == NL)
2081 *ptr = CAR; /* NLs are replaced by CRs! */
2082 else
2083 {
2084 if (skip_count == 0)
2085 {
2086 *ptr = NUL; /* end of line */
2087 len = (colnr_T) (ptr - line_start + 1);
2088 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2089 {
2090 error = TRUE;
2091 break;
2092 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002093#ifdef FEAT_PERSISTENT_UNDO
2094 if (read_undo_file)
2095 sha256_update(&sha_ctx, line_start, len);
2096#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002097 ++lnum;
2098 if (--read_count == 0)
2099 {
2100 error = TRUE; /* break loop */
2101 line_start = ptr; /* nothing left to write */
2102 break;
2103 }
2104 }
2105 else
2106 --skip_count;
2107 line_start = ptr + 1;
2108 }
2109 }
2110 }
2111 else
2112 {
2113 --ptr;
2114 while (++ptr, --size >= 0)
2115 {
2116 if ((c = *ptr) != NUL && c != NL) /* catch most common case */
2117 continue;
2118 if (c == NUL)
2119 *ptr = NL; /* NULs are replaced by newlines! */
2120 else
2121 {
2122 if (skip_count == 0)
2123 {
2124 *ptr = NUL; /* end of line */
2125 len = (colnr_T)(ptr - line_start + 1);
2126 if (fileformat == EOL_DOS)
2127 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002128 if (ptr > line_start && ptr[-1] == CAR)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002129 {
Bram Moolenaar2aa5f692017-01-24 15:46:48 +01002130 /* remove CR before NL */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002131 ptr[-1] = NUL;
2132 --len;
2133 }
2134 /*
2135 * Reading in Dos format, but no CR-LF found!
2136 * When 'fileformats' includes "unix", delete all
2137 * the lines read so far and start all over again.
2138 * Otherwise give an error message later.
2139 */
2140 else if (ff_error != EOL_DOS)
2141 {
2142 if ( try_unix
2143 && !read_stdin
2144 && (read_buffer
Bram Moolenaar8767f522016-07-01 17:17:39 +02002145 || vim_lseek(fd, (off_T)0L, SEEK_SET)
2146 == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002147 {
2148 fileformat = EOL_UNIX;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002149 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002150 set_fileformat(EOL_UNIX, OPT_LOCAL);
2151 file_rewind = TRUE;
2152 keep_fileformat = TRUE;
2153 goto retry;
2154 }
2155 ff_error = EOL_DOS;
2156 }
2157 }
2158 if (ml_append(lnum, line_start, len, newfile) == FAIL)
2159 {
2160 error = TRUE;
2161 break;
2162 }
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002163#ifdef FEAT_PERSISTENT_UNDO
2164 if (read_undo_file)
2165 sha256_update(&sha_ctx, line_start, len);
2166#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002167 ++lnum;
2168 if (--read_count == 0)
2169 {
2170 error = TRUE; /* break loop */
2171 line_start = ptr; /* nothing left to write */
2172 break;
2173 }
2174 }
2175 else
2176 --skip_count;
2177 line_start = ptr + 1;
2178 }
2179 }
2180 }
2181 linerest = (long)(ptr - line_start);
2182 ui_breakcheck();
2183 }
2184
2185failed:
2186 /* not an error, max. number of lines reached */
2187 if (error && read_count == 0)
2188 error = FALSE;
2189
2190 /*
2191 * If we get EOF in the middle of a line, note the fact and
2192 * complete the line ourselves.
2193 * In Dos format ignore a trailing CTRL-Z, unless 'binary' set.
2194 */
2195 if (!error
2196 && !got_int
2197 && linerest != 0
2198 && !(!curbuf->b_p_bin
2199 && fileformat == EOL_DOS
2200 && *line_start == Ctrl_Z
2201 && ptr == line_start + 1))
2202 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002203 /* remember for when writing */
2204 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002205 curbuf->b_p_eol = FALSE;
2206 *ptr = NUL;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002207 len = (colnr_T)(ptr - line_start + 1);
2208 if (ml_append(lnum, line_start, len, newfile) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002209 error = TRUE;
2210 else
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002211 {
2212#ifdef FEAT_PERSISTENT_UNDO
2213 if (read_undo_file)
2214 sha256_update(&sha_ctx, line_start, len);
2215#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002216 read_no_eol_lnum = ++lnum;
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002217 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002218 }
2219
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002220 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002221 save_file_ff(curbuf); /* remember the current file format */
2222
2223#ifdef FEAT_CRYPT
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002224 if (curbuf->b_cryptstate != NULL)
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002225 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002226 crypt_free_state(curbuf->b_cryptstate);
2227 curbuf->b_cryptstate = NULL;
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002228 }
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002229 if (cryptkey != NULL && cryptkey != curbuf->b_p_key)
2230 crypt_free_key(cryptkey);
2231 /* Don't set cryptkey to NULL, it's used below as a flag that
2232 * encryption was used. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002233#endif
2234
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002235 /* If editing a new file: set 'fenc' for the current buffer.
2236 * Also for ":read ++edit file". */
2237 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002238 set_string_option_direct((char_u *)"fenc", -1, fenc,
Bram Moolenaar5e3cb7e2006-02-27 23:58:35 +00002239 OPT_FREE|OPT_LOCAL, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002240 if (fenc_alloced)
2241 vim_free(fenc);
Bram Moolenaar13505972019-01-24 15:04:48 +01002242#ifdef USE_ICONV
Bram Moolenaar071d4272004-06-13 20:20:40 +00002243 if (iconv_fd != (iconv_t)-1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002244 iconv_close(iconv_fd);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002245#endif
2246
2247 if (!read_buffer && !read_stdin)
2248 close(fd); /* errors are ignored */
Bram Moolenaarf05da212009-11-17 16:13:15 +00002249#ifdef HAVE_FD_CLOEXEC
2250 else
2251 {
2252 int fdflags = fcntl(fd, F_GETFD);
2253 if (fdflags >= 0 && (fdflags & FD_CLOEXEC) == 0)
Bram Moolenaarfbc4b4d2016-02-07 15:14:01 +01002254 (void)fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC);
Bram Moolenaarf05da212009-11-17 16:13:15 +00002255 }
2256#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002257 vim_free(buffer);
2258
2259#ifdef HAVE_DUP
2260 if (read_stdin)
2261 {
2262 /* Use stderr for stdin, makes shell commands work. */
2263 close(0);
Bram Moolenaar42335f52018-09-13 15:33:43 +02002264 vim_ignored = dup(2);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002265 }
2266#endif
2267
Bram Moolenaar071d4272004-06-13 20:20:40 +00002268 if (tmpname != NULL)
2269 {
2270 mch_remove(tmpname); /* delete converted file */
2271 vim_free(tmpname);
2272 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002273 --no_wait_return; /* may wait for return now */
2274
2275 /*
2276 * In recovery mode everything but autocommands is skipped.
2277 */
2278 if (!recoverymode)
2279 {
2280 /* need to delete the last line, which comes from the empty buffer */
2281 if (newfile && wasempty && !(curbuf->b_ml.ml_flags & ML_EMPTY))
2282 {
2283#ifdef FEAT_NETBEANS_INTG
2284 netbeansFireChanges = 0;
2285#endif
2286 ml_delete(curbuf->b_ml.ml_line_count, FALSE);
2287#ifdef FEAT_NETBEANS_INTG
2288 netbeansFireChanges = 1;
2289#endif
2290 --linecnt;
2291 }
2292 linecnt = curbuf->b_ml.ml_line_count - linecnt;
2293 if (filesize == 0)
2294 linecnt = 0;
2295 if (newfile || read_buffer)
Bram Moolenaar7263a772007-05-10 17:35:54 +00002296 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002297 redraw_curbuf_later(NOT_VALID);
Bram Moolenaar7263a772007-05-10 17:35:54 +00002298#ifdef FEAT_DIFF
2299 /* After reading the text into the buffer the diff info needs to
2300 * be updated. */
2301 diff_invalidate(curbuf);
2302#endif
2303#ifdef FEAT_FOLDING
2304 /* All folds in the window are invalid now. Mark them for update
2305 * before triggering autocommands. */
2306 foldUpdateAll(curwin);
2307#endif
2308 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002309 else if (linecnt) /* appended at least one line */
2310 appended_lines_mark(from, linecnt);
2311
Bram Moolenaar071d4272004-06-13 20:20:40 +00002312#ifndef ALWAYS_USE_GUI
2313 /*
2314 * If we were reading from the same terminal as where messages go,
2315 * the screen will have been messed up.
2316 * Switch on raw mode now and clear the screen.
2317 */
2318 if (read_stdin)
2319 {
2320 settmode(TMODE_RAW); /* set to raw mode */
2321 starttermcap();
2322 screenclear();
2323 }
2324#endif
2325
2326 if (got_int)
2327 {
2328 if (!(flags & READ_DUMMY))
2329 {
2330 filemess(curbuf, sfname, (char_u *)_(e_interr), 0);
2331 if (newfile)
2332 curbuf->b_p_ro = TRUE; /* must use "w!" now */
2333 }
2334 msg_scroll = msg_save;
2335#ifdef FEAT_VIMINFO
2336 check_marks_read();
2337#endif
2338 return OK; /* an interrupt isn't really an error */
2339 }
2340
2341 if (!filtering && !(flags & READ_DUMMY))
2342 {
2343 msg_add_fname(curbuf, sfname); /* fname in IObuff with quotes */
2344 c = FALSE;
2345
2346#ifdef UNIX
Bram Moolenaard569bb02018-08-11 13:57:20 +02002347 if (S_ISFIFO(perm)) /* fifo */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002348 {
2349 STRCAT(IObuff, _("[fifo]"));
2350 c = TRUE;
2351 }
Bram Moolenaard569bb02018-08-11 13:57:20 +02002352 if (S_ISSOCK(perm)) /* or socket */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002353 {
2354 STRCAT(IObuff, _("[socket]"));
2355 c = TRUE;
2356 }
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002357# ifdef OPEN_CHR_FILES
2358 if (S_ISCHR(perm)) /* or character special */
2359 {
2360 STRCAT(IObuff, _("[character special]"));
2361 c = TRUE;
2362 }
2363# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002364#endif
2365 if (curbuf->b_p_ro)
2366 {
2367 STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
2368 c = TRUE;
2369 }
2370 if (read_no_eol_lnum)
2371 {
2372 msg_add_eol();
2373 c = TRUE;
2374 }
2375 if (ff_error == EOL_DOS)
2376 {
2377 STRCAT(IObuff, _("[CR missing]"));
2378 c = TRUE;
2379 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002380 if (split)
2381 {
2382 STRCAT(IObuff, _("[long lines split]"));
2383 c = TRUE;
2384 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002385 if (notconverted)
2386 {
2387 STRCAT(IObuff, _("[NOT converted]"));
2388 c = TRUE;
2389 }
2390 else if (converted)
2391 {
2392 STRCAT(IObuff, _("[converted]"));
2393 c = TRUE;
2394 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002395#ifdef FEAT_CRYPT
2396 if (cryptkey != NULL)
2397 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002398 crypt_append_msg(curbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002399 c = TRUE;
2400 }
2401#endif
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002402 if (conv_error != 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002403 {
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002404 sprintf((char *)IObuff + STRLEN(IObuff),
2405 _("[CONVERSION ERROR in line %ld]"), (long)conv_error);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002406 c = TRUE;
2407 }
2408 else if (illegal_byte > 0)
2409 {
2410 sprintf((char *)IObuff + STRLEN(IObuff),
2411 _("[ILLEGAL BYTE in line %ld]"), (long)illegal_byte);
2412 c = TRUE;
2413 }
Bram Moolenaar13505972019-01-24 15:04:48 +01002414 else if (error)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002415 {
2416 STRCAT(IObuff, _("[READ ERRORS]"));
2417 c = TRUE;
2418 }
2419 if (msg_add_fileformat(fileformat))
2420 c = TRUE;
2421#ifdef FEAT_CRYPT
2422 if (cryptkey != NULL)
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002423 msg_add_lines(c, (long)linecnt, filesize
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002424 - crypt_get_header_len(crypt_get_method_nr(curbuf)));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002425 else
2426#endif
2427 msg_add_lines(c, (long)linecnt, filesize);
2428
Bram Moolenaard23a8232018-02-10 18:45:26 +01002429 VIM_CLEAR(keep_msg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002430 msg_scrolled_ign = TRUE;
2431#ifdef ALWAYS_USE_GUI
2432 /* Don't show the message when reading stdin, it would end up in a
2433 * message box (which might be shown when exiting!) */
2434 if (read_stdin || read_buffer)
2435 p = msg_may_trunc(FALSE, IObuff);
2436 else
2437#endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002438 {
2439 if (msg_col > 0)
2440 msg_putchar('\r'); // overwrite previous message
Bram Moolenaar32526b32019-01-19 17:43:09 +01002441 p = (char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002442 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002443 if (read_stdin || read_buffer || restart_edit != 0
Bram Moolenaar1c7715d2005-10-03 22:02:18 +00002444 || (msg_scrolled != 0 && !need_wait_return))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002445 /* Need to repeat the message after redrawing when:
2446 * - When reading from stdin (the screen will be cleared next).
2447 * - When restart_edit is set (otherwise there will be a delay
2448 * before redrawing).
2449 * - When the screen was scrolled but there is no wait-return
2450 * prompt. */
Bram Moolenaar8f7fd652006-02-21 22:04:51 +00002451 set_keep_msg(p, 0);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002452 msg_scrolled_ign = FALSE;
2453 }
2454
2455 /* with errors writing the file requires ":w!" */
2456 if (newfile && (error
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002457 || conv_error != 0
Bram Moolenaar13505972019-01-24 15:04:48 +01002458 || (illegal_byte > 0 && bad_char_behavior != BAD_KEEP)))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002459 curbuf->b_p_ro = TRUE;
2460
2461 u_clearline(); /* cannot use "U" command after adding lines */
2462
2463 /*
2464 * In Ex mode: cursor at last new line.
2465 * Otherwise: cursor at first new line.
2466 */
2467 if (exmode_active)
2468 curwin->w_cursor.lnum = from + linecnt;
2469 else
2470 curwin->w_cursor.lnum = from + 1;
2471 check_cursor_lnum();
2472 beginline(BL_WHITE | BL_FIX); /* on first non-blank */
2473
2474 /*
2475 * Set '[ and '] marks to the newly read lines.
2476 */
2477 curbuf->b_op_start.lnum = from + 1;
2478 curbuf->b_op_start.col = 0;
2479 curbuf->b_op_end.lnum = from + linecnt;
2480 curbuf->b_op_end.col = 0;
Bram Moolenaar03f48552006-02-28 23:52:23 +00002481
Bram Moolenaar4f974752019-02-17 17:44:42 +01002482#ifdef MSWIN
Bram Moolenaar03f48552006-02-28 23:52:23 +00002483 /*
2484 * Work around a weird problem: When a file has two links (only
2485 * possible on NTFS) and we write through one link, then stat() it
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00002486 * through the other link, the timestamp information may be wrong.
Bram Moolenaar03f48552006-02-28 23:52:23 +00002487 * It's correct again after reading the file, thus reset the timestamp
2488 * here.
2489 */
2490 if (newfile && !read_stdin && !read_buffer
2491 && mch_stat((char *)fname, &st) >= 0)
2492 {
2493 buf_store_time(curbuf, &st, fname);
2494 curbuf->b_mtime_read = curbuf->b_mtime;
2495 }
2496#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002497 }
2498 msg_scroll = msg_save;
2499
2500#ifdef FEAT_VIMINFO
2501 /*
2502 * Get the marks before executing autocommands, so they can be used there.
2503 */
2504 check_marks_read();
2505#endif
2506
Bram Moolenaar071d4272004-06-13 20:20:40 +00002507 /*
Bram Moolenaar34d72d42015-07-17 14:18:08 +02002508 * We remember if the last line of the read didn't have
2509 * an eol even when 'binary' is off, to support turning 'fixeol' off,
2510 * or writing the read again with 'binary' on. The latter is required
2511 * for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002512 */
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002513 curbuf->b_no_eol_lnum = read_no_eol_lnum;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002514
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02002515 /* When reloading a buffer put the cursor at the first line that is
2516 * different. */
2517 if (flags & READ_KEEP_UNDO)
2518 u_find_first_changed();
2519
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002520#ifdef FEAT_PERSISTENT_UNDO
2521 /*
2522 * When opening a new file locate undo info and read it.
2523 */
2524 if (read_undo_file)
2525 {
2526 char_u hash[UNDO_HASH_SIZE];
2527
2528 sha256_finish(&sha_ctx, hash);
Bram Moolenaar6ed8ed82010-05-30 20:40:11 +02002529 u_read_undo(NULL, hash, fname);
Bram Moolenaar55debbe2010-05-23 23:34:36 +02002530 }
2531#endif
2532
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002533 if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL))
Bram Moolenaar071d4272004-06-13 20:20:40 +00002534 {
2535 int m = msg_scroll;
2536 int n = msg_scrolled;
2537
2538 /* Save the fileformat now, otherwise the buffer will be considered
2539 * modified if the format/encoding was automatically detected. */
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002540 if (set_options)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002541 save_file_ff(curbuf);
2542
2543 /*
2544 * The output from the autocommands should not overwrite anything and
2545 * should not be overwritten: Set msg_scroll, restore its value if no
2546 * output was done.
2547 */
2548 msg_scroll = TRUE;
2549 if (filtering)
2550 apply_autocmds_exarg(EVENT_FILTERREADPOST, NULL, sfname,
2551 FALSE, curbuf, eap);
Bram Moolenaarf71d7b92016-08-09 22:14:05 +02002552 else if (newfile || (read_buffer && sfname != NULL))
Bram Moolenaarc3691332016-04-20 12:49:49 +02002553 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00002554 apply_autocmds_exarg(EVENT_BUFREADPOST, NULL, sfname,
2555 FALSE, curbuf, eap);
Bram Moolenaarc3691332016-04-20 12:49:49 +02002556 if (!au_did_filetype && *curbuf->b_p_ft != NUL)
2557 /*
2558 * EVENT_FILETYPE was not triggered but the buffer already has a
2559 * filetype. Trigger EVENT_FILETYPE using the existing filetype.
2560 */
2561 apply_autocmds(EVENT_FILETYPE, curbuf->b_p_ft, curbuf->b_fname,
2562 TRUE, curbuf);
2563 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002564 else
2565 apply_autocmds_exarg(EVENT_FILEREADPOST, sfname, sfname,
2566 FALSE, NULL, eap);
2567 if (msg_scrolled == n)
2568 msg_scroll = m;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002569# ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002570 if (aborting()) /* autocmds may abort script processing */
2571 return FAIL;
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01002572# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002573 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00002574
2575 if (recoverymode && error)
2576 return FAIL;
2577 return OK;
2578}
2579
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002580#if defined(OPEN_CHR_FILES) || defined(PROTO)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002581/*
2582 * Returns TRUE if the file name argument is of the form "/dev/fd/\d\+",
2583 * which is the name of files used for process substitution output by
2584 * some shells on some operating systems, e.g., bash on SunOS.
2585 * Do not accept "/dev/fd/[012]", opening these may hang Vim.
2586 */
Bram Moolenaarf04507d2016-08-20 15:05:39 +02002587 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002588is_dev_fd_file(char_u *fname)
Bram Moolenaarfe1c56d2007-07-10 15:10:54 +00002589{
2590 return (STRNCMP(fname, "/dev/fd/", 8) == 0
2591 && VIM_ISDIGIT(fname[8])
2592 && *skipdigits(fname + 9) == NUL
2593 && (fname[9] != NUL
2594 || (fname[8] != '0' && fname[8] != '1' && fname[8] != '2')));
2595}
2596#endif
2597
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002598/*
2599 * From the current line count and characters read after that, estimate the
2600 * line number where we are now.
2601 * Used for error messages that include a line number.
2602 */
2603 static linenr_T
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002604readfile_linenr(
2605 linenr_T linecnt, /* line count before reading more bytes */
2606 char_u *p, /* start of more bytes read */
2607 char_u *endp) /* end of more bytes read */
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002608{
2609 char_u *s;
2610 linenr_T lnum;
2611
2612 lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
2613 for (s = p; s < endp; ++s)
2614 if (*s == '\n')
2615 ++lnum;
2616 return lnum;
2617}
Bram Moolenaarb0bf8582005-12-13 20:02:15 +00002618
Bram Moolenaar071d4272004-06-13 20:20:40 +00002619/*
Bram Moolenaar195d6352005-12-19 22:08:24 +00002620 * Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary to be
2621 * equal to the buffer "buf". Used for calling readfile().
Bram Moolenaar071d4272004-06-13 20:20:40 +00002622 * Returns OK or FAIL.
2623 */
2624 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002625prep_exarg(exarg_T *eap, buf_T *buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002626{
Bram Moolenaar13505972019-01-24 15:04:48 +01002627 eap->cmd = alloc(15 + (unsigned)STRLEN(buf->b_p_fenc));
Bram Moolenaar071d4272004-06-13 20:20:40 +00002628 if (eap->cmd == NULL)
2629 return FAIL;
2630
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002631 sprintf((char *)eap->cmd, "e ++enc=%s", buf->b_p_fenc);
2632 eap->force_enc = 8;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002633 eap->bad_char = buf->b_bad_char;
Bram Moolenaar333b80a2018-04-04 22:57:29 +02002634 eap->force_ff = *buf->b_p_ff;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002635
2636 eap->force_bin = buf->b_p_bin ? FORCE_BIN : FORCE_NOBIN;
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002637 eap->read_edit = FALSE;
Bram Moolenaar195d6352005-12-19 22:08:24 +00002638 eap->forceit = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002639 return OK;
2640}
2641
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002642/*
2643 * Set default or forced 'fileformat' and 'binary'.
2644 */
2645 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002646set_file_options(int set_options, exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002647{
2648 /* set default 'fileformat' */
2649 if (set_options)
2650 {
2651 if (eap != NULL && eap->force_ff != 0)
2652 set_fileformat(get_fileformat_force(curbuf, eap), OPT_LOCAL);
2653 else if (*p_ffs != NUL)
2654 set_fileformat(default_fileformat(), OPT_LOCAL);
2655 }
2656
2657 /* set or reset 'binary' */
2658 if (eap != NULL && eap->force_bin != 0)
2659 {
2660 int oldval = curbuf->b_p_bin;
2661
2662 curbuf->b_p_bin = (eap->force_bin == FORCE_BIN);
2663 set_options_bin(oldval, curbuf->b_p_bin, OPT_LOCAL);
2664 }
2665}
2666
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002667/*
2668 * Set forced 'fileencoding'.
2669 */
2670 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002671set_forced_fenc(exarg_T *eap)
Bram Moolenaarad875fb2013-07-24 15:02:03 +02002672{
2673 if (eap->force_enc != 0)
2674 {
2675 char_u *fenc = enc_canonize(eap->cmd + eap->force_enc);
2676
2677 if (fenc != NULL)
2678 set_string_option_direct((char_u *)"fenc", -1,
2679 fenc, OPT_FREE|OPT_LOCAL, 0);
2680 vim_free(fenc);
2681 }
2682}
2683
Bram Moolenaar071d4272004-06-13 20:20:40 +00002684/*
2685 * Find next fileencoding to use from 'fileencodings'.
2686 * "pp" points to fenc_next. It's advanced to the next item.
2687 * When there are no more items, an empty string is returned and *pp is set to
2688 * NULL.
Bram Moolenaarf077db22019-08-13 00:18:24 +02002689 * When *pp is not set to NULL, the result is in allocated memory and "alloced"
2690 * is set to TRUE.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002691 */
2692 static char_u *
Bram Moolenaarf077db22019-08-13 00:18:24 +02002693next_fenc(char_u **pp, int *alloced)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002694{
2695 char_u *p;
2696 char_u *r;
2697
Bram Moolenaarf077db22019-08-13 00:18:24 +02002698 *alloced = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002699 if (**pp == NUL)
2700 {
2701 *pp = NULL;
2702 return (char_u *)"";
2703 }
2704 p = vim_strchr(*pp, ',');
2705 if (p == NULL)
2706 {
2707 r = enc_canonize(*pp);
2708 *pp += STRLEN(*pp);
2709 }
2710 else
2711 {
2712 r = vim_strnsave(*pp, (int)(p - *pp));
2713 *pp = p + 1;
2714 if (r != NULL)
2715 {
2716 p = enc_canonize(r);
2717 vim_free(r);
2718 r = p;
2719 }
2720 }
Bram Moolenaarf077db22019-08-13 00:18:24 +02002721 if (r != NULL)
2722 *alloced = TRUE;
2723 else
Bram Moolenaar071d4272004-06-13 20:20:40 +00002724 {
Bram Moolenaarf077db22019-08-13 00:18:24 +02002725 // out of memory
Bram Moolenaar071d4272004-06-13 20:20:40 +00002726 r = (char_u *)"";
2727 *pp = NULL;
2728 }
2729 return r;
2730}
2731
Bram Moolenaar13505972019-01-24 15:04:48 +01002732#ifdef FEAT_EVAL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002733/*
2734 * Convert a file with the 'charconvert' expression.
2735 * This closes the file which is to be read, converts it and opens the
2736 * resulting file for reading.
2737 * Returns name of the resulting converted file (the caller should delete it
2738 * after reading it).
2739 * Returns NULL if the conversion failed ("*fdp" is not set) .
2740 */
2741 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002742readfile_charconvert(
2743 char_u *fname, /* name of input file */
2744 char_u *fenc, /* converted from */
2745 int *fdp) /* in/out: file descriptor of file */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002746{
2747 char_u *tmpname;
Bram Moolenaar32526b32019-01-19 17:43:09 +01002748 char *errmsg = NULL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002749
Bram Moolenaare5c421c2015-03-31 13:33:08 +02002750 tmpname = vim_tempname('r', FALSE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002751 if (tmpname == NULL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002752 errmsg = _("Can't find temp file for conversion");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002753 else
2754 {
2755 close(*fdp); /* close the input file, ignore errors */
2756 *fdp = -1;
2757 if (eval_charconvert(fenc, enc_utf8 ? (char_u *)"utf-8" : p_enc,
2758 fname, tmpname) == FAIL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002759 errmsg = _("Conversion with 'charconvert' failed");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002760 if (errmsg == NULL && (*fdp = mch_open((char *)tmpname,
2761 O_RDONLY | O_EXTRA, 0)) < 0)
Bram Moolenaar32526b32019-01-19 17:43:09 +01002762 errmsg = _("can't read output of 'charconvert'");
Bram Moolenaar071d4272004-06-13 20:20:40 +00002763 }
2764
2765 if (errmsg != NULL)
2766 {
2767 /* Don't use emsg(), it breaks mappings, the retry with
2768 * another type of conversion might still work. */
Bram Moolenaar32526b32019-01-19 17:43:09 +01002769 msg(errmsg);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002770 if (tmpname != NULL)
2771 {
2772 mch_remove(tmpname); /* delete converted file */
Bram Moolenaard23a8232018-02-10 18:45:26 +01002773 VIM_CLEAR(tmpname);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002774 }
2775 }
2776
2777 /* If the input file is closed, open it (caller should check for error). */
2778 if (*fdp < 0)
2779 *fdp = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0);
2780
2781 return tmpname;
2782}
Bram Moolenaar071d4272004-06-13 20:20:40 +00002783#endif
2784
Bram Moolenaara3ff49f2010-05-30 22:48:02 +02002785#if defined(FEAT_CRYPT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002786/*
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002787 * Check for magic number used for encryption. Applies to the current buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00002788 * If found, the magic number is removed from ptr[*sizep] and *sizep and
2789 * *filesizep are updated.
2790 * Return the (new) encryption key, NULL for no encryption.
2791 */
2792 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002793check_for_cryptkey(
2794 char_u *cryptkey, /* previous encryption key or NULL */
2795 char_u *ptr, /* pointer to read bytes */
2796 long *sizep, /* length of read bytes */
Bram Moolenaar8767f522016-07-01 17:17:39 +02002797 off_T *filesizep, /* nr of bytes used from file */
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002798 int newfile, /* editing a new buffer */
2799 char_u *fname, /* file name to display */
2800 int *did_ask) /* flag: whether already asked for key */
Bram Moolenaar071d4272004-06-13 20:20:40 +00002801{
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002802 int method = crypt_method_nr_from_magic((char *)ptr, *sizep);
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002803 int b_p_ro = curbuf->b_p_ro;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002804
2805 if (method >= 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002806 {
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002807 /* Mark the buffer as read-only until the decryption has taken place.
2808 * Avoids accidentally overwriting the file with garbage. */
2809 curbuf->b_p_ro = TRUE;
2810
Bram Moolenaar2be79502014-08-13 21:58:28 +02002811 /* Set the cryptmethod local to the buffer. */
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002812 crypt_set_cm_option(curbuf, method);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002813 if (cryptkey == NULL && !*did_ask)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002814 {
2815 if (*curbuf->b_p_key)
2816 cryptkey = curbuf->b_p_key;
2817 else
2818 {
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002819 /* When newfile is TRUE, store the typed key in the 'key'
2820 * option and don't free it. bf needs hash of the key saved.
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002821 * Don't ask for the key again when first time Enter was hit.
2822 * Happens when retrying to detect encoding. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002823 smsg(_(need_key_msg), fname);
Bram Moolenaara8ffcbb2010-06-21 06:15:46 +02002824 msg_scroll = TRUE;
Bram Moolenaar3a0c9082014-11-12 15:15:42 +01002825 crypt_check_method(method);
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002826 cryptkey = crypt_get_key(newfile, FALSE);
Bram Moolenaarf50a2532010-05-21 15:36:08 +02002827 *did_ask = TRUE;
2828
Bram Moolenaar071d4272004-06-13 20:20:40 +00002829 /* check if empty key entered */
2830 if (cryptkey != NULL && *cryptkey == NUL)
2831 {
2832 if (cryptkey != curbuf->b_p_key)
2833 vim_free(cryptkey);
2834 cryptkey = NULL;
2835 }
2836 }
2837 }
2838
2839 if (cryptkey != NULL)
2840 {
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002841 int header_len;
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002842
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002843 curbuf->b_cryptstate = crypt_create_from_header(
2844 method, cryptkey, ptr);
2845 crypt_set_cm_option(curbuf, method);
Bram Moolenaar071d4272004-06-13 20:20:40 +00002846
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002847 /* Remove cryptmethod specific header from the text. */
2848 header_len = crypt_get_header_len(method);
Bram Moolenaar680e0152016-09-25 20:54:11 +02002849 if (*sizep <= header_len)
2850 /* invalid header, buffer can't be encrypted */
2851 return NULL;
Bram Moolenaar8f4ac012014-08-10 13:38:34 +02002852 *filesizep += header_len;
2853 *sizep -= header_len;
2854 mch_memmove(ptr, ptr + header_len, (size_t)*sizep);
2855
Bram Moolenaarcf81aef2013-08-25 17:46:08 +02002856 /* Restore the read-only flag. */
2857 curbuf->b_p_ro = b_p_ro;
Bram Moolenaar071d4272004-06-13 20:20:40 +00002858 }
2859 }
Bram Moolenaar40e6a712010-05-16 22:32:54 +02002860 /* When starting to edit a new file which does not have encryption, clear
2861 * the 'key' option, except when starting up (called with -x argument) */
Bram Moolenaarfa0ff9a2010-07-25 16:05:19 +02002862 else if (newfile && *curbuf->b_p_key != NUL && !starting)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002863 set_option_value((char_u *)"key", 0L, (char_u *)"", OPT_LOCAL);
2864
2865 return cryptkey;
2866}
Bram Moolenaar80794b12010-06-13 05:20:42 +02002867#endif /* FEAT_CRYPT */
2868
Bram Moolenaard4755bb2004-09-02 19:12:26 +00002869#if defined(VMS) && !defined(MIN)
2870/* Older DECC compiler for VAX doesn't define MIN() */
2871# define MIN(a, b) ((a) < (b) ? (a) : (b))
2872#endif
2873
Bram Moolenaar071d4272004-06-13 20:20:40 +00002874/*
Bram Moolenaar5386a122007-06-28 20:02:32 +00002875 * Return TRUE if a file appears to be read-only from the file permissions.
2876 */
2877 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002878check_file_readonly(
2879 char_u *fname, /* full path to file */
Bram Moolenaarbd67aac2019-09-21 23:09:04 +02002880 int perm UNUSED) /* known permissions on file */
Bram Moolenaar5386a122007-06-28 20:02:32 +00002881{
2882#ifndef USE_MCH_ACCESS
2883 int fd = 0;
2884#endif
2885
2886 return (
2887#ifdef USE_MCH_ACCESS
2888# ifdef UNIX
2889 (perm & 0222) == 0 ||
2890# endif
2891 mch_access((char *)fname, W_OK)
2892#else
2893 (fd = mch_open((char *)fname, O_RDWR | O_EXTRA, 0)) < 0
2894 ? TRUE : (close(fd), FALSE)
2895#endif
2896 );
2897}
2898
Bram Moolenaara7870192019-02-14 12:56:36 +01002899#if defined(HAVE_FSYNC) || defined(PROTO)
2900/*
2901 * Call fsync() with Mac-specific exception.
2902 * Return fsync() result: zero for success.
2903 */
2904 int
2905vim_fsync(int fd)
2906{
2907 int r;
2908
2909# ifdef MACOS_X
2910 r = fcntl(fd, F_FULLFSYNC);
Bram Moolenaar91668382019-02-21 12:16:12 +01002911 if (r != 0) // F_FULLFSYNC not working or not supported
Bram Moolenaara7870192019-02-14 12:56:36 +01002912# endif
2913 r = fsync(fd);
2914 return r;
2915}
2916#endif
2917
Bram Moolenaar071d4272004-06-13 20:20:40 +00002918/*
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002919 * Set the name of the current buffer. Use when the buffer doesn't have a
2920 * name and a ":r" or ":w" command with a file name is used.
2921 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02002922 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002923set_rw_fname(char_u *fname, char_u *sfname)
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002924{
Bram Moolenaar8b38e242009-06-16 13:35:20 +00002925 buf_T *buf = curbuf;
2926
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002927 /* It's like the unnamed buffer is deleted.... */
2928 if (curbuf->b_p_bl)
2929 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
2930 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01002931#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002932 if (aborting()) /* autocmds may abort script processing */
2933 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01002934#endif
Bram Moolenaar8b38e242009-06-16 13:35:20 +00002935 if (curbuf != buf)
2936 {
2937 /* We are in another buffer now, don't do the renaming. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01002938 emsg(_(e_auchangedbuf));
Bram Moolenaar8b38e242009-06-16 13:35:20 +00002939 return FAIL;
2940 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002941
2942 if (setfname(curbuf, fname, sfname, FALSE) == OK)
2943 curbuf->b_flags |= BF_NOTEDITED;
2944
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002945 /* ....and a new named one is created */
2946 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, curbuf);
2947 if (curbuf->b_p_bl)
2948 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01002949#ifdef FEAT_EVAL
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002950 if (aborting()) /* autocmds may abort script processing */
2951 return FAIL;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01002952#endif
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002953
2954 /* Do filetype detection now if 'filetype' is empty. */
2955 if (*curbuf->b_p_ft == NUL)
2956 {
Bram Moolenaar910f66f2006-04-05 20:41:53 +00002957 if (au_has_group((char_u *)"filetypedetect"))
Bram Moolenaar1610d052016-06-09 22:53:01 +02002958 (void)do_doautocmd((char_u *)"filetypedetect BufRead", FALSE, NULL);
Bram Moolenaara3227e22006-03-08 21:32:40 +00002959 do_modelines(0);
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002960 }
Bram Moolenaar2d3f4892006-01-20 23:02:51 +00002961
2962 return OK;
2963}
2964
2965/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00002966 * Put file name into IObuff with quotes.
2967 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00002968 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002969msg_add_fname(buf_T *buf, char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002970{
2971 if (fname == NULL)
2972 fname = (char_u *)"-stdin-";
2973 home_replace(buf, fname, IObuff + 1, IOSIZE - 4, TRUE);
2974 IObuff[0] = '"';
2975 STRCAT(IObuff, "\" ");
2976}
2977
2978/*
2979 * Append message for text mode to IObuff.
2980 * Return TRUE if something appended.
2981 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02002982 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01002983msg_add_fileformat(int eol_type)
Bram Moolenaar071d4272004-06-13 20:20:40 +00002984{
2985#ifndef USE_CRNL
2986 if (eol_type == EOL_DOS)
2987 {
2988 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
2989 return TRUE;
2990 }
2991#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00002992 if (eol_type == EOL_MAC)
2993 {
2994 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
2995 return TRUE;
2996 }
Bram Moolenaar00590742019-02-15 21:06:09 +01002997#ifdef USE_CRNL
Bram Moolenaar071d4272004-06-13 20:20:40 +00002998 if (eol_type == EOL_UNIX)
2999 {
3000 STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
3001 return TRUE;
3002 }
3003#endif
3004 return FALSE;
3005}
3006
3007/*
3008 * Append line and character count to IObuff.
3009 */
Bram Moolenaar009b2592004-10-24 19:18:58 +00003010 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003011msg_add_lines(
3012 int insert_space,
3013 long lnum,
Bram Moolenaar8767f522016-07-01 17:17:39 +02003014 off_T nchars)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003015{
3016 char_u *p;
3017
3018 p = IObuff + STRLEN(IObuff);
3019
3020 if (insert_space)
3021 *p++ = ' ';
3022 if (shortmess(SHM_LINES))
Bram Moolenaarbde98102016-07-01 20:03:42 +02003023 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
Bram Moolenaar88c86eb2019-01-17 17:13:30 +01003024 "%ldL, %lldC", lnum, (long_long_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003025 else
3026 {
Bram Moolenaarda6e8912018-08-21 15:12:14 +02003027 sprintf((char *)p, NGETTEXT("%ld line, ", "%ld lines, ", lnum), lnum);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003028 p += STRLEN(p);
Bram Moolenaarda6e8912018-08-21 15:12:14 +02003029 vim_snprintf((char *)p, IOSIZE - (p - IObuff),
3030 NGETTEXT("%lld character", "%lld characters", nchars),
Bram Moolenaar88c86eb2019-01-17 17:13:30 +01003031 (long_long_T)nchars);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003032 }
3033}
3034
3035/*
3036 * Append message for missing line separator to IObuff.
3037 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003038 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003039msg_add_eol(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003040{
3041 STRCAT(IObuff, shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
3042}
3043
Bram Moolenaar473952e2019-09-28 16:30:04 +02003044 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003045time_differs(long t1, long t2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003046{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003047#if defined(__linux__) || defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003048 /* On a FAT filesystem, esp. under Linux, there are only 5 bits to store
3049 * the seconds. Since the roundoff is done when flushing the inode, the
3050 * time may change unexpectedly by one second!!! */
3051 return (t1 - t2 > 1 || t2 - t1 > 1);
3052#else
3053 return (t1 != t2);
3054#endif
3055}
3056
3057/*
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003058 * Return TRUE if file encoding "fenc" requires conversion from or to
3059 * 'encoding'.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003060 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003061 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003062need_conversion(char_u *fenc)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003063{
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003064 int same_encoding;
3065 int enc_flags;
3066 int fenc_flags;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003067
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003068 if (*fenc == NUL || STRCMP(p_enc, fenc) == 0)
Bram Moolenaar442b4222010-05-24 21:34:22 +02003069 {
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003070 same_encoding = TRUE;
Bram Moolenaar442b4222010-05-24 21:34:22 +02003071 fenc_flags = 0;
3072 }
Bram Moolenaarb5cdf2e2009-07-29 16:25:31 +00003073 else
3074 {
3075 /* Ignore difference between "ansi" and "latin1", "ucs-4" and
3076 * "ucs-4be", etc. */
3077 enc_flags = get_fio_flags(p_enc);
3078 fenc_flags = get_fio_flags(fenc);
3079 same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
3080 }
3081 if (same_encoding)
3082 {
3083 /* Specified encoding matches with 'encoding'. This requires
3084 * conversion when 'encoding' is Unicode but not UTF-8. */
3085 return enc_unicode != 0;
3086 }
3087
3088 /* Encodings differ. However, conversion is not needed when 'enc' is any
3089 * Unicode encoding and the file is UTF-8. */
3090 return !(enc_utf8 && fenc_flags == FIO_UTF8);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003091}
3092
3093/*
3094 * Check "ptr" for a unicode encoding and return the FIO_ flags needed for the
3095 * internal conversion.
3096 * if "ptr" is an empty string, use 'encoding'.
3097 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003098 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003099get_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003100{
3101 int prop;
3102
3103 if (*ptr == NUL)
3104 ptr = p_enc;
3105
3106 prop = enc_canon_props(ptr);
3107 if (prop & ENC_UNICODE)
3108 {
3109 if (prop & ENC_2BYTE)
3110 {
3111 if (prop & ENC_ENDIAN_L)
3112 return FIO_UCS2 | FIO_ENDIAN_L;
3113 return FIO_UCS2;
3114 }
3115 if (prop & ENC_4BYTE)
3116 {
3117 if (prop & ENC_ENDIAN_L)
3118 return FIO_UCS4 | FIO_ENDIAN_L;
3119 return FIO_UCS4;
3120 }
3121 if (prop & ENC_2WORD)
3122 {
3123 if (prop & ENC_ENDIAN_L)
3124 return FIO_UTF16 | FIO_ENDIAN_L;
3125 return FIO_UTF16;
3126 }
3127 return FIO_UTF8;
3128 }
3129 if (prop & ENC_LATIN1)
3130 return FIO_LATIN1;
3131 /* must be ENC_DBCS, requires iconv() */
3132 return 0;
3133}
3134
Bram Moolenaar473952e2019-09-28 16:30:04 +02003135#if defined(MSWIN) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003136/*
3137 * Check "ptr" for a MS-Windows codepage name and return the FIO_ flags needed
3138 * for the conversion MS-Windows can do for us. Also accept "utf-8".
3139 * Used for conversion between 'encoding' and 'fileencoding'.
3140 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003141 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003142get_win_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003143{
3144 int cp;
3145
3146 /* Cannot do this when 'encoding' is not utf-8 and not a codepage. */
3147 if (!enc_utf8 && enc_codepage <= 0)
3148 return 0;
3149
3150 cp = encname2codepage(ptr);
3151 if (cp == 0)
3152 {
3153# ifdef CP_UTF8 /* VC 4.1 doesn't define CP_UTF8 */
3154 if (STRCMP(ptr, "utf-8") == 0)
3155 cp = CP_UTF8;
3156 else
3157# endif
3158 return 0;
3159 }
3160 return FIO_PUT_CP(cp) | FIO_CODEPAGE;
3161}
3162#endif
3163
Bram Moolenaar473952e2019-09-28 16:30:04 +02003164#if defined(MACOS_CONVERT) || defined(PROTO)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003165/*
3166 * Check "ptr" for a Carbon supported encoding and return the FIO_ flags
3167 * needed for the internal conversion to/from utf-8 or latin1.
3168 */
Bram Moolenaar473952e2019-09-28 16:30:04 +02003169 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003170get_mac_fio_flags(char_u *ptr)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003171{
3172 if ((enc_utf8 || STRCMP(p_enc, "latin1") == 0)
3173 && (enc_canon_props(ptr) & ENC_MACROMAN))
3174 return FIO_MACROMAN;
3175 return 0;
3176}
3177#endif
3178
3179/*
3180 * Check for a Unicode BOM (Byte Order Mark) at the start of p[size].
3181 * "size" must be at least 2.
3182 * Return the name of the encoding and set "*lenp" to the length.
3183 * Returns NULL when no BOM found.
3184 */
3185 static char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003186check_for_bom(
3187 char_u *p,
3188 long size,
3189 int *lenp,
3190 int flags)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003191{
3192 char *name = NULL;
3193 int len = 2;
3194
3195 if (p[0] == 0xef && p[1] == 0xbb && size >= 3 && p[2] == 0xbf
Bram Moolenaaree0f5a62008-07-24 20:09:16 +00003196 && (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003197 {
3198 name = "utf-8"; /* EF BB BF */
3199 len = 3;
3200 }
3201 else if (p[0] == 0xff && p[1] == 0xfe)
3202 {
3203 if (size >= 4 && p[2] == 0 && p[3] == 0
3204 && (flags == FIO_ALL || flags == (FIO_UCS4 | FIO_ENDIAN_L)))
3205 {
3206 name = "ucs-4le"; /* FF FE 00 00 */
3207 len = 4;
3208 }
Bram Moolenaar223a1892008-11-11 20:57:11 +00003209 else if (flags == (FIO_UCS2 | FIO_ENDIAN_L))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003210 name = "ucs-2le"; /* FF FE */
Bram Moolenaar223a1892008-11-11 20:57:11 +00003211 else if (flags == FIO_ALL || flags == (FIO_UTF16 | FIO_ENDIAN_L))
3212 /* utf-16le is preferred, it also works for ucs-2le text */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003213 name = "utf-16le"; /* FF FE */
3214 }
3215 else if (p[0] == 0xfe && p[1] == 0xff
3216 && (flags == FIO_ALL || flags == FIO_UCS2 || flags == FIO_UTF16))
3217 {
Bram Moolenaarffd82c52008-02-20 17:15:26 +00003218 /* Default to utf-16, it works also for ucs-2 text. */
3219 if (flags == FIO_UCS2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003220 name = "ucs-2"; /* FE FF */
Bram Moolenaarffd82c52008-02-20 17:15:26 +00003221 else
3222 name = "utf-16"; /* FE FF */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003223 }
3224 else if (size >= 4 && p[0] == 0 && p[1] == 0 && p[2] == 0xfe
3225 && p[3] == 0xff && (flags == FIO_ALL || flags == FIO_UCS4))
3226 {
3227 name = "ucs-4"; /* 00 00 FE FF */
3228 len = 4;
3229 }
3230
3231 *lenp = len;
3232 return (char_u *)name;
3233}
3234
3235/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00003236 * Try to find a shortname by comparing the fullname with the current
3237 * directory.
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003238 * Returns "full_path" or pointer into "full_path" if shortened.
3239 */
3240 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003241shorten_fname1(char_u *full_path)
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003242{
Bram Moolenaard9462e32011-04-11 21:35:11 +02003243 char_u *dirname;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003244 char_u *p = full_path;
3245
Bram Moolenaard9462e32011-04-11 21:35:11 +02003246 dirname = alloc(MAXPATHL);
3247 if (dirname == NULL)
3248 return full_path;
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003249 if (mch_dirname(dirname, MAXPATHL) == OK)
3250 {
3251 p = shorten_fname(full_path, dirname);
3252 if (p == NULL || *p == NUL)
3253 p = full_path;
3254 }
Bram Moolenaard9462e32011-04-11 21:35:11 +02003255 vim_free(dirname);
Bram Moolenaard089d9b2007-09-30 12:02:55 +00003256 return p;
3257}
3258
3259/*
3260 * Try to find a shortname by comparing the fullname with the current
3261 * directory.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003262 * Returns NULL if not shorter name possible, pointer into "full_path"
3263 * otherwise.
3264 */
3265 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003266shorten_fname(char_u *full_path, char_u *dir_name)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003267{
3268 int len;
3269 char_u *p;
3270
3271 if (full_path == NULL)
3272 return NULL;
3273 len = (int)STRLEN(dir_name);
3274 if (fnamencmp(dir_name, full_path, len) == 0)
3275 {
3276 p = full_path + len;
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003277#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003278 /*
Bram Moolenaar4f974752019-02-17 17:44:42 +01003279 * MS-Windows: when a file is in the root directory, dir_name will end
3280 * in a slash, since C: by itself does not define a specific dir. In
3281 * this case p may already be correct. <negri>
Bram Moolenaar071d4272004-06-13 20:20:40 +00003282 */
3283 if (!((len > 2) && (*(p - 2) == ':')))
3284#endif
3285 {
3286 if (vim_ispathsep(*p))
3287 ++p;
3288#ifndef VMS /* the path separator is always part of the path */
3289 else
3290 p = NULL;
3291#endif
3292 }
3293 }
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003294#if defined(MSWIN)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003295 /*
3296 * When using a file in the current drive, remove the drive name:
3297 * "A:\dir\file" -> "\dir\file". This helps when moving a session file on
3298 * a floppy from "A:\dir" to "B:\dir".
3299 */
3300 else if (len > 3
3301 && TOUPPER_LOC(full_path[0]) == TOUPPER_LOC(dir_name[0])
3302 && full_path[1] == ':'
3303 && vim_ispathsep(full_path[2]))
3304 p = full_path + 2;
3305#endif
3306 else
3307 p = NULL;
3308 return p;
3309}
3310
3311/*
Bram Moolenaara796d462018-05-01 14:30:36 +02003312 * Shorten filename of a buffer.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003313 * When "force" is TRUE: Use full path from now on for files currently being
3314 * edited, both for file name and swap file name. Try to shorten the file
3315 * names a bit, if safe to do so.
3316 * When "force" is FALSE: Only try to shorten absolute file names.
3317 * For buffers that have buftype "nofile" or "scratch": never change the file
3318 * name.
3319 */
3320 void
Bram Moolenaara796d462018-05-01 14:30:36 +02003321shorten_buf_fname(buf_T *buf, char_u *dirname, int force)
3322{
3323 char_u *p;
3324
3325 if (buf->b_fname != NULL
3326#ifdef FEAT_QUICKFIX
Bram Moolenaar26910de2019-06-15 19:37:15 +02003327 && !bt_nofilename(buf)
Bram Moolenaara796d462018-05-01 14:30:36 +02003328#endif
3329 && !path_with_url(buf->b_fname)
3330 && (force
3331 || buf->b_sfname == NULL
3332 || mch_isFullName(buf->b_sfname)))
3333 {
Bram Moolenaar3d6014f2018-10-11 19:27:47 +02003334 if (buf->b_sfname != buf->b_ffname)
3335 VIM_CLEAR(buf->b_sfname);
Bram Moolenaara796d462018-05-01 14:30:36 +02003336 p = shorten_fname(buf->b_ffname, dirname);
3337 if (p != NULL)
3338 {
3339 buf->b_sfname = vim_strsave(p);
3340 buf->b_fname = buf->b_sfname;
3341 }
3342 if (p == NULL || buf->b_fname == NULL)
3343 buf->b_fname = buf->b_ffname;
3344 }
3345}
3346
3347/*
3348 * Shorten filenames for all buffers.
3349 */
3350 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003351shorten_fnames(int force)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003352{
3353 char_u dirname[MAXPATHL];
3354 buf_T *buf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003355
3356 mch_dirname(dirname, MAXPATHL);
Bram Moolenaar29323592016-07-24 22:04:11 +02003357 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003358 {
Bram Moolenaara796d462018-05-01 14:30:36 +02003359 shorten_buf_fname(buf, dirname, force);
Bram Moolenaar69a7cb42004-06-20 12:51:53 +00003360
3361 /* Always make the swap file name a full path, a "nofile" buffer may
3362 * also have a swap file. */
3363 mf_fullname(buf->b_ml.ml_mfp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003364 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003365 status_redraw_all();
Bram Moolenaar49d7bf12006-02-17 21:45:41 +00003366 redraw_tabline = TRUE;
Bram Moolenaar90f3e7a2019-08-01 22:40:44 +02003367#ifdef FEAT_TEXT_PROP
3368 popup_update_preview_title();
3369#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003370}
3371
3372#if (defined(FEAT_DND) && defined(FEAT_GUI_GTK)) \
3373 || defined(FEAT_GUI_MSWIN) \
3374 || defined(FEAT_GUI_MAC) \
3375 || defined(PROTO)
3376/*
3377 * Shorten all filenames in "fnames[count]" by current directory.
3378 */
3379 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003380shorten_filenames(char_u **fnames, int count)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003381{
3382 int i;
3383 char_u dirname[MAXPATHL];
3384 char_u *p;
3385
3386 if (fnames == NULL || count < 1)
3387 return;
3388 mch_dirname(dirname, sizeof(dirname));
3389 for (i = 0; i < count; ++i)
3390 {
3391 if ((p = shorten_fname(fnames[i], dirname)) != NULL)
3392 {
3393 /* shorten_fname() returns pointer in given "fnames[i]". If free
3394 * "fnames[i]" first, "p" becomes invalid. So we need to copy
3395 * "p" first then free fnames[i]. */
3396 p = vim_strsave(p);
3397 vim_free(fnames[i]);
3398 fnames[i] = p;
3399 }
3400 }
3401}
3402#endif
3403
3404/*
Bram Moolenaarb782ba42018-08-07 21:39:28 +02003405 * Add extension to file name - change path/fo.o.h to path/fo.o.h.ext or
Bram Moolenaar071d4272004-06-13 20:20:40 +00003406 * fo_o_h.ext for MSDOS or when shortname option set.
3407 *
3408 * Assumed that fname is a valid name found in the filesystem we assure that
3409 * the return value is a different name and ends in 'ext'.
3410 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
3411 * characters otherwise.
3412 * Space for the returned name is allocated, must be freed later.
3413 * Returns NULL when out of memory.
3414 */
3415 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003416modname(
3417 char_u *fname,
3418 char_u *ext,
3419 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003420{
Bram Moolenaar48e330a2016-02-23 14:53:34 +01003421 return buf_modname((curbuf->b_p_sn || curbuf->b_shortname),
Bram Moolenaar071d4272004-06-13 20:20:40 +00003422 fname, ext, prepend_dot);
3423}
3424
3425 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003426buf_modname(
3427 int shortname, /* use 8.3 file name */
3428 char_u *fname,
3429 char_u *ext,
3430 int prepend_dot) /* may prepend a '.' to file name */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003431{
3432 char_u *retval;
3433 char_u *s;
3434 char_u *e;
3435 char_u *ptr;
3436 int fnamelen, extlen;
3437
3438 extlen = (int)STRLEN(ext);
3439
3440 /*
3441 * If there is no file name we must get the name of the current directory
3442 * (we need the full path in case :cd is used).
3443 */
3444 if (fname == NULL || *fname == NUL)
3445 {
Bram Moolenaar964b3742019-05-24 18:54:09 +02003446 retval = alloc(MAXPATHL + extlen + 3);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003447 if (retval == NULL)
3448 return NULL;
3449 if (mch_dirname(retval, MAXPATHL) == FAIL ||
3450 (fnamelen = (int)STRLEN(retval)) == 0)
3451 {
3452 vim_free(retval);
3453 return NULL;
3454 }
Bram Moolenaar1cd871b2004-12-19 22:46:22 +00003455 if (!after_pathsep(retval, retval + fnamelen))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003456 {
3457 retval[fnamelen++] = PATHSEP;
3458 retval[fnamelen] = NUL;
3459 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003460 prepend_dot = FALSE; /* nothing to prepend a dot to */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003461 }
3462 else
3463 {
3464 fnamelen = (int)STRLEN(fname);
Bram Moolenaar964b3742019-05-24 18:54:09 +02003465 retval = alloc(fnamelen + extlen + 3);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003466 if (retval == NULL)
3467 return NULL;
3468 STRCPY(retval, fname);
3469#ifdef VMS
3470 vms_remove_version(retval); /* we do not need versions here */
3471#endif
3472 }
3473
3474 /*
3475 * search backwards until we hit a '/', '\' or ':' replacing all '.'
3476 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
3477 * Then truncate what is after the '/', '\' or ':' to 8 characters for
3478 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
3479 */
Bram Moolenaar91acfff2017-03-12 19:22:36 +01003480 for (ptr = retval + fnamelen; ptr > retval; MB_PTR_BACK(retval, ptr))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003481 {
Bram Moolenaar00f148d2019-02-12 22:37:27 +01003482 if (*ext == '.' && shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003483 if (*ptr == '.') /* replace '.' by '_' */
3484 *ptr = '_';
Bram Moolenaar071d4272004-06-13 20:20:40 +00003485 if (vim_ispathsep(*ptr))
Bram Moolenaar53180ce2005-07-05 21:48:14 +00003486 {
3487 ++ptr;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003488 break;
Bram Moolenaar53180ce2005-07-05 21:48:14 +00003489 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003490 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003491
3492 /* the file name has at most BASENAMELEN characters. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003493 if (STRLEN(ptr) > (unsigned)BASENAMELEN)
3494 ptr[BASENAMELEN] = '\0';
Bram Moolenaar071d4272004-06-13 20:20:40 +00003495
3496 s = ptr + STRLEN(ptr);
3497
3498 /*
3499 * For 8.3 file names we may have to reduce the length.
3500 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003501 if (shortname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003502 {
3503 /*
3504 * If there is no file name, or the file name ends in '/', and the
3505 * extension starts with '.', put a '_' before the dot, because just
3506 * ".ext" is invalid.
3507 */
3508 if (fname == NULL || *fname == NUL
3509 || vim_ispathsep(fname[STRLEN(fname) - 1]))
3510 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003511 if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003512 *s++ = '_';
3513 }
3514 /*
3515 * If the extension starts with '.', truncate the base name at 8
3516 * characters
3517 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003518 else if (*ext == '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003519 {
Bram Moolenaar78a15312009-05-15 19:33:18 +00003520 if ((size_t)(s - ptr) > (size_t)8)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003521 {
3522 s = ptr + 8;
3523 *s = '\0';
3524 }
3525 }
3526 /*
3527 * If the extension doesn't start with '.', and the file name
3528 * doesn't have an extension yet, append a '.'
3529 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003530 else if ((e = vim_strchr(ptr, '.')) == NULL)
3531 *s++ = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00003532 /*
3533 * If the extension doesn't start with '.', and there already is an
Bram Moolenaar7263a772007-05-10 17:35:54 +00003534 * extension, it may need to be truncated
Bram Moolenaar071d4272004-06-13 20:20:40 +00003535 */
3536 else if ((int)STRLEN(e) + extlen > 4)
3537 s = e + 4 - extlen;
3538 }
Bram Moolenaar4f974752019-02-17 17:44:42 +01003539#ifdef MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00003540 /*
3541 * If there is no file name, and the extension starts with '.', put a
3542 * '_' before the dot, because just ".ext" may be invalid if it's on a
3543 * FAT partition, and on HPFS it doesn't matter.
3544 */
3545 else if ((fname == NULL || *fname == NUL) && *ext == '.')
3546 *s++ = '_';
3547#endif
3548
3549 /*
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003550 * Append the extension.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003551 * ext can start with '.' and cannot exceed 3 more characters.
3552 */
3553 STRCPY(s, ext);
3554
Bram Moolenaar071d4272004-06-13 20:20:40 +00003555 /*
3556 * Prepend the dot.
3557 */
Bram Moolenaar00f148d2019-02-12 22:37:27 +01003558 if (prepend_dot && !shortname && *(e = gettail(retval)) != '.')
Bram Moolenaar071d4272004-06-13 20:20:40 +00003559 {
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00003560 STRMOVE(e + 1, e);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003561 *e = '.';
Bram Moolenaar071d4272004-06-13 20:20:40 +00003562 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003563
3564 /*
3565 * Check that, after appending the extension, the file name is really
3566 * different.
3567 */
3568 if (fname != NULL && STRCMP(fname, retval) == 0)
3569 {
3570 /* we search for a character that can be replaced by '_' */
3571 while (--s >= ptr)
3572 {
3573 if (*s != '_')
3574 {
3575 *s = '_';
3576 break;
3577 }
3578 }
3579 if (s < ptr) /* fname was "________.<ext>", how tricky! */
3580 *ptr = 'v';
3581 }
3582 return retval;
3583}
3584
3585/*
3586 * Like fgets(), but if the file line is too long, it is truncated and the
3587 * rest of the line is thrown away. Returns TRUE for end-of-file.
Bram Moolenaar7e1652c2017-12-16 18:27:02 +01003588 * If the line is truncated then buf[size - 2] will not be NUL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003589 */
3590 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003591vim_fgets(char_u *buf, int size, FILE *fp)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003592{
3593 char *eof;
3594#define FGETS_SIZE 200
3595 char tbuf[FGETS_SIZE];
3596
3597 buf[size - 2] = NUL;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003598 eof = fgets((char *)buf, size, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003599 if (buf[size - 2] != NUL && buf[size - 2] != '\n')
3600 {
3601 buf[size - 1] = NUL; /* Truncate the line */
3602
3603 /* Now throw away the rest of the line: */
3604 do
3605 {
3606 tbuf[FGETS_SIZE - 2] = NUL;
Bram Moolenaar42335f52018-09-13 15:33:43 +02003607 vim_ignoredp = fgets((char *)tbuf, FGETS_SIZE, fp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003608 } while (tbuf[FGETS_SIZE - 2] != NUL && tbuf[FGETS_SIZE - 2] != '\n');
3609 }
3610 return (eof == NULL);
3611}
3612
Bram Moolenaar071d4272004-06-13 20:20:40 +00003613/*
3614 * rename() only works if both files are on the same file system, this
3615 * function will (attempts to?) copy the file across if rename fails -- webb
3616 * Return -1 for failure, 0 for success.
3617 */
3618 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003619vim_rename(char_u *from, char_u *to)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003620{
3621 int fd_in;
3622 int fd_out;
3623 int n;
3624 char *errmsg = NULL;
3625 char *buffer;
3626#ifdef AMIGA
3627 BPTR flock;
3628#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02003629 stat_T st;
Bram Moolenaar9be038d2005-03-08 22:34:32 +00003630 long perm;
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003631#ifdef HAVE_ACL
3632 vim_acl_T acl; /* ACL from original file */
3633#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003634 int use_tmp_file = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003635
3636 /*
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003637 * When the names are identical, there is nothing to do. When they refer
3638 * to the same file (ignoring case and slash/backslash differences) but
3639 * the file name differs we need to go through a temp file.
Bram Moolenaar071d4272004-06-13 20:20:40 +00003640 */
3641 if (fnamecmp(from, to) == 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003642 {
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01003643 if (p_fic && STRCMP(gettail(from), gettail(to)) != 0)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003644 use_tmp_file = TRUE;
3645 else
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003646 return 0;
3647 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003648
3649 /*
3650 * Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
3651 */
3652 if (mch_stat((char *)from, &st) < 0)
3653 return -1;
3654
Bram Moolenaar3576da72008-12-30 15:15:57 +00003655#ifdef UNIX
3656 {
Bram Moolenaar8767f522016-07-01 17:17:39 +02003657 stat_T st_to;
Bram Moolenaar3576da72008-12-30 15:15:57 +00003658
3659 /* It's possible for the source and destination to be the same file.
3660 * This happens when "from" and "to" differ in case and are on a FAT32
3661 * filesystem. In that case go through a temp file name. */
3662 if (mch_stat((char *)to, &st_to) >= 0
3663 && st.st_dev == st_to.st_dev
3664 && st.st_ino == st_to.st_ino)
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003665 use_tmp_file = TRUE;
3666 }
3667#endif
Bram Moolenaar4f974752019-02-17 17:44:42 +01003668#ifdef MSWIN
Bram Moolenaar1c32dff2011-05-05 16:41:24 +02003669 {
3670 BY_HANDLE_FILE_INFORMATION info1, info2;
3671
3672 /* It's possible for the source and destination to be the same file.
3673 * In that case go through a temp file name. This makes rename("foo",
3674 * "./foo") a no-op (in a complicated way). */
3675 if (win32_fileinfo(from, &info1) == FILEINFO_OK
3676 && win32_fileinfo(to, &info2) == FILEINFO_OK
3677 && info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
3678 && info1.nFileIndexHigh == info2.nFileIndexHigh
3679 && info1.nFileIndexLow == info2.nFileIndexLow)
3680 use_tmp_file = TRUE;
3681 }
3682#endif
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003683
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003684 if (use_tmp_file)
3685 {
3686 char tempname[MAXPATHL + 1];
3687
3688 /*
3689 * Find a name that doesn't exist and is in the same directory.
3690 * Rename "from" to "tempname" and then rename "tempname" to "to".
3691 */
3692 if (STRLEN(from) >= MAXPATHL - 5)
3693 return -1;
3694 STRCPY(tempname, from);
3695 for (n = 123; n < 99999; ++n)
Bram Moolenaar3576da72008-12-30 15:15:57 +00003696 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003697 sprintf((char *)gettail((char_u *)tempname), "%d", n);
3698 if (mch_stat(tempname, &st) < 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00003699 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003700 if (mch_rename((char *)from, tempname) == 0)
Bram Moolenaar3576da72008-12-30 15:15:57 +00003701 {
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003702 if (mch_rename(tempname, (char *)to) == 0)
3703 return 0;
3704 /* Strange, the second step failed. Try moving the
3705 * file back and return failure. */
3706 mch_rename(tempname, (char *)from);
Bram Moolenaar3576da72008-12-30 15:15:57 +00003707 return -1;
3708 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003709 /* If it fails for one temp name it will most likely fail
3710 * for any temp name, give up. */
3711 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00003712 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00003713 }
Bram Moolenaare0e6f992008-12-31 15:21:32 +00003714 return -1;
Bram Moolenaar3576da72008-12-30 15:15:57 +00003715 }
Bram Moolenaar3576da72008-12-30 15:15:57 +00003716
Bram Moolenaar071d4272004-06-13 20:20:40 +00003717 /*
3718 * Delete the "to" file, this is required on some systems to make the
3719 * mch_rename() work, on other systems it makes sure that we don't have
3720 * two files when the mch_rename() fails.
3721 */
3722
3723#ifdef AMIGA
3724 /*
3725 * With MSDOS-compatible filesystems (crossdos, messydos) it is possible
3726 * that the name of the "to" file is the same as the "from" file, even
Bram Moolenaar7263a772007-05-10 17:35:54 +00003727 * though the names are different. To avoid the chance of accidentally
Bram Moolenaar071d4272004-06-13 20:20:40 +00003728 * deleting the "from" file (horror!) we lock it during the remove.
3729 *
3730 * When used for making a backup before writing the file: This should not
3731 * happen with ":w", because startscript() should detect this problem and
3732 * set buf->b_shortname, causing modname() to return a correct ".bak" file
3733 * name. This problem does exist with ":w filename", but then the
3734 * original file will be somewhere else so the backup isn't really
3735 * important. If autoscripting is off the rename may fail.
3736 */
3737 flock = Lock((UBYTE *)from, (long)ACCESS_READ);
3738#endif
3739 mch_remove(to);
3740#ifdef AMIGA
3741 if (flock)
3742 UnLock(flock);
3743#endif
3744
3745 /*
3746 * First try a normal rename, return if it works.
3747 */
3748 if (mch_rename((char *)from, (char *)to) == 0)
3749 return 0;
3750
3751 /*
3752 * Rename() failed, try copying the file.
3753 */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00003754 perm = mch_getperm(from);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003755#ifdef HAVE_ACL
3756 /* For systems that support ACL: get the ACL from the original file. */
3757 acl = mch_get_acl(from);
3758#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003759 fd_in = mch_open((char *)from, O_RDONLY|O_EXTRA, 0);
3760 if (fd_in == -1)
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003761 {
3762#ifdef HAVE_ACL
3763 mch_free_acl(acl);
3764#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003765 return -1;
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003766 }
Bram Moolenaar9be038d2005-03-08 22:34:32 +00003767
3768 /* Create the new file with same permissions as the original. */
Bram Moolenaara5792f52005-11-23 21:25:05 +00003769 fd_out = mch_open((char *)to,
3770 O_CREAT|O_EXCL|O_WRONLY|O_EXTRA|O_NOFOLLOW, (int)perm);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003771 if (fd_out == -1)
3772 {
3773 close(fd_in);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003774#ifdef HAVE_ACL
3775 mch_free_acl(acl);
3776#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003777 return -1;
3778 }
3779
Bram Moolenaar473952e2019-09-28 16:30:04 +02003780 buffer = alloc(WRITEBUFSIZE);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003781 if (buffer == NULL)
3782 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00003783 close(fd_out);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003784 close(fd_in);
3785#ifdef HAVE_ACL
3786 mch_free_acl(acl);
3787#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003788 return -1;
3789 }
3790
Bram Moolenaar473952e2019-09-28 16:30:04 +02003791 while ((n = read_eintr(fd_in, buffer, WRITEBUFSIZE)) > 0)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01003792 if (write_eintr(fd_out, buffer, n) != n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003793 {
3794 errmsg = _("E208: Error writing to \"%s\"");
3795 break;
3796 }
3797
3798 vim_free(buffer);
3799 close(fd_in);
3800 if (close(fd_out) < 0)
3801 errmsg = _("E209: Error closing \"%s\"");
3802 if (n < 0)
3803 {
3804 errmsg = _("E210: Error reading \"%s\"");
3805 to = from;
3806 }
Bram Moolenaar7263a772007-05-10 17:35:54 +00003807#ifndef UNIX /* for Unix mch_open() already set the permission */
Bram Moolenaar9be038d2005-03-08 22:34:32 +00003808 mch_setperm(to, perm);
Bram Moolenaarc6039d82005-12-02 00:44:04 +00003809#endif
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003810#ifdef HAVE_ACL
3811 mch_set_acl(to, acl);
Bram Moolenaarb23a7e82008-06-27 18:42:32 +00003812 mch_free_acl(acl);
Bram Moolenaarcd71fa32005-03-11 22:46:48 +00003813#endif
Bram Moolenaar5bd32f42014-04-02 14:05:38 +02003814#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
Bram Moolenaare8747442013-11-12 18:09:29 +01003815 mch_copy_sec(from, to);
Bram Moolenaar0671de32013-11-12 05:12:03 +01003816#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003817 if (errmsg != NULL)
3818 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003819 semsg(errmsg, to);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003820 return -1;
3821 }
3822 mch_remove(from);
3823 return 0;
3824}
3825
3826static int already_warned = FALSE;
3827
3828/*
3829 * Check if any not hidden buffer has been changed.
3830 * Postpone the check if there are characters in the stuff buffer, a global
3831 * command is being executed, a mapping is being executed or an autocommand is
3832 * busy.
3833 * Returns TRUE if some message was written (screen should be redrawn and
3834 * cursor positioned).
3835 */
3836 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003837check_timestamps(
3838 int focus) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003839{
3840 buf_T *buf;
3841 int didit = 0;
3842 int n;
3843
3844 /* Don't check timestamps while system() or another low-level function may
3845 * cause us to lose and gain focus. */
3846 if (no_check_timestamps > 0)
3847 return FALSE;
3848
3849 /* Avoid doing a check twice. The OK/Reload dialog can cause a focus
3850 * event and we would keep on checking if the file is steadily growing.
3851 * Do check again after typing something. */
3852 if (focus && did_check_timestamps)
3853 {
3854 need_check_timestamps = TRUE;
3855 return FALSE;
3856 }
3857
3858 if (!stuff_empty() || global_busy || !typebuf_typed()
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01003859 || autocmd_busy || curbuf_lock > 0 || allbuf_lock > 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003860 need_check_timestamps = TRUE; /* check later */
3861 else
3862 {
3863 ++no_wait_return;
3864 did_check_timestamps = TRUE;
3865 already_warned = FALSE;
Bram Moolenaar29323592016-07-24 22:04:11 +02003866 FOR_ALL_BUFFERS(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003867 {
3868 /* Only check buffers in a window. */
3869 if (buf->b_nwindows > 0)
3870 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003871 bufref_T bufref;
3872
3873 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003874 n = buf_check_timestamp(buf, focus);
3875 if (didit < n)
3876 didit = n;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003877 if (n > 0 && !bufref_valid(&bufref))
Bram Moolenaar071d4272004-06-13 20:20:40 +00003878 {
3879 /* Autocommands have removed the buffer, start at the
3880 * first one again. */
3881 buf = firstbuf;
3882 continue;
3883 }
3884 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00003885 }
3886 --no_wait_return;
3887 need_check_timestamps = FALSE;
3888 if (need_wait_return && didit == 2)
3889 {
3890 /* make sure msg isn't overwritten */
Bram Moolenaar32526b32019-01-19 17:43:09 +01003891 msg_puts("\n");
Bram Moolenaar071d4272004-06-13 20:20:40 +00003892 out_flush();
3893 }
3894 }
3895 return didit;
3896}
3897
3898/*
3899 * Move all the lines from buffer "frombuf" to buffer "tobuf".
3900 * Return OK or FAIL. When FAIL "tobuf" is incomplete and/or "frombuf" is not
3901 * empty.
3902 */
3903 static int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003904move_lines(buf_T *frombuf, buf_T *tobuf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003905{
3906 buf_T *tbuf = curbuf;
3907 int retval = OK;
3908 linenr_T lnum;
3909 char_u *p;
3910
3911 /* Copy the lines in "frombuf" to "tobuf". */
3912 curbuf = tobuf;
3913 for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; ++lnum)
3914 {
3915 p = vim_strsave(ml_get_buf(frombuf, lnum, FALSE));
3916 if (p == NULL || ml_append(lnum - 1, p, 0, FALSE) == FAIL)
3917 {
3918 vim_free(p);
3919 retval = FAIL;
3920 break;
3921 }
3922 vim_free(p);
3923 }
3924
3925 /* Delete all the lines in "frombuf". */
3926 if (retval != FAIL)
3927 {
3928 curbuf = frombuf;
Bram Moolenaar9460b9d2007-01-09 14:37:01 +00003929 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; --lnum)
3930 if (ml_delete(lnum, FALSE) == FAIL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003931 {
3932 /* Oops! We could try putting back the saved lines, but that
3933 * might fail again... */
3934 retval = FAIL;
3935 break;
3936 }
3937 }
3938
3939 curbuf = tbuf;
3940 return retval;
3941}
3942
3943/*
3944 * Check if buffer "buf" has been changed.
3945 * Also check if the file for a new buffer unexpectedly appeared.
3946 * return 1 if a changed buffer was found.
3947 * return 2 if a message has been displayed.
3948 * return 0 otherwise.
3949 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003950 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01003951buf_check_timestamp(
3952 buf_T *buf,
3953 int focus UNUSED) /* called for GUI focus event */
Bram Moolenaar071d4272004-06-13 20:20:40 +00003954{
Bram Moolenaar8767f522016-07-01 17:17:39 +02003955 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003956 int stat_res;
3957 int retval = 0;
3958 char_u *path;
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01003959 char *tbuf;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003960 char *mesg = NULL;
Bram Moolenaar44ecf652005-03-07 23:09:59 +00003961 char *mesg2 = "";
Bram Moolenaar071d4272004-06-13 20:20:40 +00003962 int helpmesg = FALSE;
3963 int reload = FALSE;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003964 char *reason;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003965#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
3966 int can_reload = FALSE;
3967#endif
Bram Moolenaar8767f522016-07-01 17:17:39 +02003968 off_T orig_size = buf->b_orig_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00003969 int orig_mode = buf->b_orig_mode;
3970#ifdef FEAT_GUI
3971 int save_mouse_correct = need_mouse_correct;
3972#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003973 static int busy = FALSE;
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003974 int n;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01003975#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00003976 char_u *s;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01003977#endif
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02003978 bufref_T bufref;
3979
3980 set_bufref(&bufref, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00003981
3982 /* If there is no file name, the buffer is not loaded, 'buftype' is
3983 * set, we are in the middle of a save or being called recursively: ignore
3984 * this buffer. */
3985 if (buf->b_ffname == NULL
3986 || buf->b_ml.ml_mfp == NULL
Bram Moolenaar91335e52018-08-01 17:53:12 +02003987 || !bt_normal(buf)
Bram Moolenaar071d4272004-06-13 20:20:40 +00003988 || buf->b_saving
Bram Moolenaar071d4272004-06-13 20:20:40 +00003989 || busy
Bram Moolenaar009b2592004-10-24 19:18:58 +00003990#ifdef FEAT_NETBEANS_INTG
3991 || isNetbeansBuffer(buf)
3992#endif
Bram Moolenaar8cad9302017-08-12 14:32:32 +02003993#ifdef FEAT_TERMINAL
3994 || buf->b_term != NULL
3995#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00003996 )
3997 return 0;
3998
3999 if ( !(buf->b_flags & BF_NOTEDITED)
4000 && buf->b_mtime != 0
4001 && ((stat_res = mch_stat((char *)buf->b_ffname, &st)) < 0
4002 || time_differs((long)st.st_mtime, buf->b_mtime)
Bram Moolenaara7611f62014-05-02 15:46:14 +02004003 || st.st_size != buf->b_orig_size
Bram Moolenaar071d4272004-06-13 20:20:40 +00004004#ifdef HAVE_ST_MODE
4005 || (int)st.st_mode != buf->b_orig_mode
4006#else
4007 || mch_getperm(buf->b_ffname) != buf->b_orig_mode
4008#endif
4009 ))
4010 {
Bram Moolenaar674e2bd2019-07-31 20:21:01 +02004011 long prev_b_mtime = buf->b_mtime;
4012
Bram Moolenaar071d4272004-06-13 20:20:40 +00004013 retval = 1;
4014
Bram Moolenaar386bc822018-07-07 18:34:12 +02004015 // set b_mtime to stop further warnings (e.g., when executing
4016 // FileChangedShell autocmd)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004017 if (stat_res < 0)
4018 {
Bram Moolenaar8239c622019-05-24 16:46:01 +02004019 // Check the file again later to see if it re-appears.
4020 buf->b_mtime = -1;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004021 buf->b_orig_size = 0;
4022 buf->b_orig_mode = 0;
4023 }
4024 else
4025 buf_store_time(buf, &st, buf->b_ffname);
4026
4027 /* Don't do anything for a directory. Might contain the file
4028 * explorer. */
4029 if (mch_isdir(buf->b_fname))
4030 ;
4031
4032 /*
4033 * If 'autoread' is set, the buffer has no changes and the file still
4034 * exists, reload the buffer. Use the buffer-local option value if it
4035 * was set, the global option value otherwise.
4036 */
4037 else if ((buf->b_p_ar >= 0 ? buf->b_p_ar : p_ar)
4038 && !bufIsChanged(buf) && stat_res >= 0)
4039 reload = TRUE;
4040 else
4041 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004042 if (stat_res < 0)
4043 reason = "deleted";
4044 else if (bufIsChanged(buf))
4045 reason = "conflict";
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01004046 /*
4047 * Check if the file contents really changed to avoid giving a
4048 * warning when only the timestamp was set (e.g., checked out of
4049 * CVS). Always warn when the buffer was changed.
4050 */
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004051 else if (orig_size != buf->b_orig_size || buf_contents_changed(buf))
4052 reason = "changed";
4053 else if (orig_mode != buf->b_orig_mode)
4054 reason = "mode";
4055 else
4056 reason = "time";
Bram Moolenaar071d4272004-06-13 20:20:40 +00004057
4058 /*
4059 * Only give the warning if there are no FileChangedShell
4060 * autocommands.
4061 * Avoid being called recursively by setting "busy".
4062 */
4063 busy = TRUE;
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004064#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004065 set_vim_var_string(VV_FCS_REASON, (char_u *)reason, -1);
4066 set_vim_var_string(VV_FCS_CHOICE, (char_u *)"", -1);
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004067#endif
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00004068 ++allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004069 n = apply_autocmds(EVENT_FILECHANGEDSHELL,
4070 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaarbf1b7a72009-03-05 02:15:53 +00004071 --allbuf_lock;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004072 busy = FALSE;
4073 if (n)
4074 {
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004075 if (!bufref_valid(&bufref))
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004076 emsg(_("E246: FileChangedShell autocommand deleted buffer"));
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004077#ifdef FEAT_EVAL
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004078 s = get_vim_var_str(VV_FCS_CHOICE);
4079 if (STRCMP(s, "reload") == 0 && *reason != 'd')
4080 reload = TRUE;
4081 else if (STRCMP(s, "ask") == 0)
4082 n = FALSE;
4083 else
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004084#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004085 return 2;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004086 }
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004087 if (!n)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004088 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004089 if (*reason == 'd')
Bram Moolenaar674e2bd2019-07-31 20:21:01 +02004090 {
4091 // Only give the message once.
4092 if (prev_b_mtime != -1)
4093 mesg = _("E211: File \"%s\" no longer available");
4094 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004095 else
4096 {
4097 helpmesg = TRUE;
4098#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
4099 can_reload = TRUE;
4100#endif
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004101 if (reason[2] == 'n')
4102 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004103 mesg = _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004104 mesg2 = _("See \":help W12\" for more info.");
4105 }
4106 else if (reason[1] == 'h')
4107 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004108 mesg = _("W11: Warning: File \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004109 mesg2 = _("See \":help W11\" for more info.");
4110 }
4111 else if (*reason == 'm')
4112 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004113 mesg = _("W16: Warning: Mode of file \"%s\" has changed since editing started");
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004114 mesg2 = _("See \":help W16\" for more info.");
4115 }
Bram Moolenaar85388b52009-06-24 09:58:32 +00004116 else
4117 /* Only timestamp changed, store it to avoid a warning
4118 * in check_mtime() later. */
4119 buf->b_mtime_read = buf->b_mtime;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004120 }
4121 }
4122 }
4123
4124 }
4125 else if ((buf->b_flags & BF_NEW) && !(buf->b_flags & BF_NEW_W)
4126 && vim_fexists(buf->b_ffname))
4127 {
4128 retval = 1;
4129 mesg = _("W13: Warning: File \"%s\" has been created after editing started");
4130 buf->b_flags |= BF_NEW_W;
4131#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
4132 can_reload = TRUE;
4133#endif
4134 }
4135
4136 if (mesg != NULL)
4137 {
4138 path = home_replace_save(buf, buf->b_fname);
4139 if (path != NULL)
4140 {
Bram Moolenaar19a09a12005-03-04 23:39:37 +00004141 if (!helpmesg)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004142 mesg2 = "";
Bram Moolenaarc799fe22019-05-28 23:08:19 +02004143 tbuf = alloc(STRLEN(path) + STRLEN(mesg) + STRLEN(mesg2) + 2);
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004144 sprintf(tbuf, mesg, path);
Bram Moolenaar496c5262009-03-18 14:42:00 +00004145#ifdef FEAT_EVAL
4146 /* Set warningmsg here, before the unimportant and output-specific
4147 * mesg2 has been appended. */
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004148 set_vim_var_string(VV_WARNINGMSG, (char_u *)tbuf, -1);
Bram Moolenaar496c5262009-03-18 14:42:00 +00004149#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004150#if defined(FEAT_CON_DIALOG) || defined(FEAT_GUI_DIALOG)
4151 if (can_reload)
4152 {
4153 if (*mesg2 != NUL)
4154 {
4155 STRCAT(tbuf, "\n");
4156 STRCAT(tbuf, mesg2);
4157 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004158 if (do_dialog(VIM_WARNING, (char_u *)_("Warning"),
4159 (char_u *)tbuf,
Bram Moolenaard2c340a2011-01-17 20:08:11 +01004160 (char_u *)_("&OK\n&Load File"), 1, NULL, TRUE) == 2)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004161 reload = TRUE;
4162 }
4163 else
4164#endif
4165 if (State > NORMAL_BUSY || (State & CMDLINE) || already_warned)
4166 {
4167 if (*mesg2 != NUL)
4168 {
4169 STRCAT(tbuf, "; ");
4170 STRCAT(tbuf, mesg2);
4171 }
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004172 emsg(tbuf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004173 retval = 2;
4174 }
4175 else
4176 {
Bram Moolenaar071d4272004-06-13 20:20:40 +00004177 if (!autocmd_busy)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004178 {
4179 msg_start();
Bram Moolenaar32526b32019-01-19 17:43:09 +01004180 msg_puts_attr(tbuf, HL_ATTR(HLF_E) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004181 if (*mesg2 != NUL)
Bram Moolenaar32526b32019-01-19 17:43:09 +01004182 msg_puts_attr(mesg2, HL_ATTR(HLF_W) + MSG_HIST);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004183 msg_clr_eos();
4184 (void)msg_end();
4185 if (emsg_silent == 0)
4186 {
4187 out_flush();
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004188#ifdef FEAT_GUI
Bram Moolenaar071d4272004-06-13 20:20:40 +00004189 if (!focus)
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004190#endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004191 /* give the user some time to think about it */
4192 ui_delay(1000L, TRUE);
4193
4194 /* don't redraw and erase the message */
4195 redraw_cmdline = FALSE;
4196 }
4197 }
4198 already_warned = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004199 }
4200
4201 vim_free(path);
4202 vim_free(tbuf);
4203 }
4204 }
4205
4206 if (reload)
Bram Moolenaar465748e2012-08-29 18:50:54 +02004207 {
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004208 /* Reload the buffer. */
Bram Moolenaar316059c2006-01-14 21:18:42 +00004209 buf_reload(buf, orig_mode);
Bram Moolenaar465748e2012-08-29 18:50:54 +02004210#ifdef FEAT_PERSISTENT_UNDO
4211 if (buf->b_p_udf && buf->b_ffname != NULL)
4212 {
4213 char_u hash[UNDO_HASH_SIZE];
4214 buf_T *save_curbuf = curbuf;
4215
4216 /* Any existing undo file is unusable, write it now. */
4217 curbuf = buf;
4218 u_compute_hash(hash);
4219 u_write_undo(NULL, FALSE, buf, hash);
4220 curbuf = save_curbuf;
4221 }
4222#endif
4223 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00004224
Bram Moolenaar3577c6f2008-06-24 21:16:56 +00004225 /* Trigger FileChangedShell when the file was changed in any way. */
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004226 if (bufref_valid(&bufref) && retval != 0)
Bram Moolenaar56718732006-03-15 22:53:57 +00004227 (void)apply_autocmds(EVENT_FILECHANGEDSHELLPOST,
4228 buf->b_fname, buf->b_fname, FALSE, buf);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004229#ifdef FEAT_GUI
4230 /* restore this in case an autocommand has set it; it would break
4231 * 'mousefocus' */
4232 need_mouse_correct = save_mouse_correct;
4233#endif
4234
4235 return retval;
4236}
4237
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004238/*
4239 * Reload a buffer that is already loaded.
4240 * Used when the file was changed outside of Vim.
Bram Moolenaar316059c2006-01-14 21:18:42 +00004241 * "orig_mode" is buf->b_orig_mode before the need for reloading was detected.
4242 * buf->b_orig_mode may have been reset already.
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004243 */
4244 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004245buf_reload(buf_T *buf, int orig_mode)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004246{
4247 exarg_T ea;
4248 pos_T old_cursor;
4249 linenr_T old_topline;
4250 int old_ro = buf->b_p_ro;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004251 buf_T *savebuf;
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004252 bufref_T bufref;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004253 int saved = OK;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004254 aco_save_T aco;
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004255 int flags = READ_NEW;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004256
4257 /* set curwin/curbuf for "buf" and save some things */
4258 aucmd_prepbuf(&aco, buf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004259
4260 /* We only want to read the text from the file, not reset the syntax
4261 * highlighting, clear marks, diff status, etc. Force the fileformat
4262 * and encoding to be the same. */
4263 if (prep_exarg(&ea, buf) == OK)
4264 {
4265 old_cursor = curwin->w_cursor;
4266 old_topline = curwin->w_topline;
4267
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02004268 if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur)
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004269 {
4270 /* Save all the text, so that the reload can be undone.
4271 * Sync first so that this is a separate undo-able action. */
4272 u_sync(FALSE);
4273 saved = u_savecommon(0, curbuf->b_ml.ml_line_count + 1, 0, TRUE);
4274 flags |= READ_KEEP_UNDO;
4275 }
4276
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004277 /*
4278 * To behave like when a new file is edited (matters for
4279 * BufReadPost autocommands) we first need to delete the current
4280 * buffer contents. But if reading the file fails we should keep
4281 * the old contents. Can't use memory only, the file might be
4282 * too big. Use a hidden buffer to move the buffer contents to.
4283 */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01004284 if (BUFEMPTY() || saved == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004285 savebuf = NULL;
4286 else
4287 {
4288 /* Allocate a buffer without putting it in the buffer list. */
4289 savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004290 set_bufref(&bufref, savebuf);
Bram Moolenaar8424a622006-04-19 21:23:36 +00004291 if (savebuf != NULL && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004292 {
4293 /* Open the memline. */
4294 curbuf = savebuf;
4295 curwin->w_buffer = savebuf;
Bram Moolenaar4770d092006-01-12 23:22:24 +00004296 saved = ml_open(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004297 curbuf = buf;
4298 curwin->w_buffer = buf;
4299 }
Bram Moolenaar8424a622006-04-19 21:23:36 +00004300 if (savebuf == NULL || saved == FAIL || buf != curbuf
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004301 || move_lines(buf, savebuf) == FAIL)
4302 {
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004303 semsg(_("E462: Could not prepare for reloading \"%s\""),
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004304 buf->b_fname);
4305 saved = FAIL;
4306 }
4307 }
4308
4309 if (saved == OK)
4310 {
4311 curbuf->b_flags |= BF_CHECK_RO; /* check for RO again */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004312 keep_filetype = TRUE; /* don't detect 'filetype' */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004313 if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0,
4314 (linenr_T)0,
Bram Moolenaare13b9af2017-01-13 22:01:02 +01004315 (linenr_T)MAXLNUM, &ea, flags) != OK)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004316 {
Bram Moolenaarf2bd8ef2018-03-04 18:08:14 +01004317#if defined(FEAT_EVAL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004318 if (!aborting())
4319#endif
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01004320 semsg(_("E321: Could not reload \"%s\""), buf->b_fname);
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004321 if (savebuf != NULL && bufref_valid(&bufref) && buf == curbuf)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004322 {
4323 /* Put the text back from the save buffer. First
4324 * delete any lines that readfile() added. */
Bram Moolenaarb5aedf32017-03-12 18:23:53 +01004325 while (!BUFEMPTY())
Bram Moolenaar8424a622006-04-19 21:23:36 +00004326 if (ml_delete(buf->b_ml.ml_line_count, FALSE) == FAIL)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004327 break;
4328 (void)move_lines(savebuf, buf);
4329 }
4330 }
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004331 else if (buf == curbuf) /* "buf" still valid */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004332 {
4333 /* Mark the buffer as unmodified and free undo info. */
Bram Moolenaarc024b462019-06-08 18:07:21 +02004334 unchanged(buf, TRUE, TRUE);
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004335 if ((flags & READ_KEEP_UNDO) == 0)
4336 {
4337 u_blockfree(buf);
4338 u_clearall(buf);
4339 }
4340 else
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02004341 {
Bram Moolenaar59f931e2010-07-24 20:27:03 +02004342 /* Mark all undo states as changed. */
4343 u_unchanged(curbuf);
Bram Moolenaarf9bb7342010-08-04 14:29:54 +02004344 }
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004345 }
4346 }
4347 vim_free(ea.cmd);
4348
Bram Moolenaar7c0a2f32016-07-10 22:11:16 +02004349 if (savebuf != NULL && bufref_valid(&bufref))
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004350 wipe_buffer(savebuf, FALSE);
4351
4352#ifdef FEAT_DIFF
4353 /* Invalidate diff info if necessary. */
Bram Moolenaar8424a622006-04-19 21:23:36 +00004354 diff_invalidate(curbuf);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004355#endif
4356
4357 /* Restore the topline and cursor position and check it (lines may
4358 * have been removed). */
4359 if (old_topline > curbuf->b_ml.ml_line_count)
4360 curwin->w_topline = curbuf->b_ml.ml_line_count;
4361 else
4362 curwin->w_topline = old_topline;
4363 curwin->w_cursor = old_cursor;
4364 check_cursor();
4365 update_topline();
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004366 keep_filetype = FALSE;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004367#ifdef FEAT_FOLDING
4368 {
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00004369 win_T *wp;
4370 tabpage_T *tp;
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004371
4372 /* Update folds unless they are defined manually. */
Bram Moolenaarbd1e5d22009-04-29 09:02:44 +00004373 FOR_ALL_TAB_WINDOWS(tp, wp)
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004374 if (wp->w_buffer == curwin->w_buffer
4375 && !foldmethodIsManual(wp))
4376 foldUpdateAll(wp);
4377 }
4378#endif
4379 /* If the mode didn't change and 'readonly' was set, keep the old
4380 * value; the user probably used the ":view" command. But don't
4381 * reset it, might have had a read error. */
4382 if (orig_mode == curbuf->b_orig_mode)
4383 curbuf->b_p_ro |= old_ro;
Bram Moolenaar52f85b72013-01-30 14:13:56 +01004384
4385 /* Modelines must override settings done by autocommands. */
4386 do_modelines(0);
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004387 }
4388
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004389 /* restore curwin/curbuf and a few other things */
4390 aucmd_restbuf(&aco);
4391 /* Careful: autocommands may have made "buf" invalid! */
Bram Moolenaar631d6f62005-06-07 21:02:10 +00004392}
4393
Bram Moolenaar071d4272004-06-13 20:20:40 +00004394 void
Bram Moolenaar8767f522016-07-01 17:17:39 +02004395buf_store_time(buf_T *buf, stat_T *st, char_u *fname UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004396{
4397 buf->b_mtime = (long)st->st_mtime;
Bram Moolenaar914703b2010-05-31 21:59:46 +02004398 buf->b_orig_size = st->st_size;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004399#ifdef HAVE_ST_MODE
4400 buf->b_orig_mode = (int)st->st_mode;
4401#else
4402 buf->b_orig_mode = mch_getperm(fname);
4403#endif
4404}
4405
4406/*
4407 * Adjust the line with missing eol, used for the next write.
4408 * Used for do_filter(), when the input lines for the filter are deleted.
4409 */
4410 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004411write_lnum_adjust(linenr_T offset)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004412{
Bram Moolenaarcab35ad2011-02-15 17:39:22 +01004413 if (curbuf->b_no_eol_lnum != 0) /* only if there is a missing eol */
4414 curbuf->b_no_eol_lnum += offset;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004415}
4416
Bram Moolenaarda440d22016-01-16 21:27:23 +01004417#if defined(TEMPDIRNAMES) || defined(FEAT_EVAL) || defined(PROTO)
4418/*
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004419 * Core part of "readdir()" function.
4420 * Retrieve the list of files/directories of "path" into "gap".
4421 * Return OK for success, FAIL for failure.
4422 */
4423 int
4424readdir_core(
4425 garray_T *gap,
4426 char_u *path,
4427 void *context,
4428 int (*checkitem)(void *context, char_u *name))
4429{
4430 int failed = FALSE;
4431#ifdef MSWIN
4432 char_u *buf, *p;
4433 int ok;
4434 HANDLE hFind = INVALID_HANDLE_VALUE;
4435 WIN32_FIND_DATAW wfb;
4436 WCHAR *wn = NULL; // UTF-16 name, NULL when not used.
4437#endif
4438
4439 ga_init2(gap, (int)sizeof(char *), 20);
4440
4441#ifdef MSWIN
Bram Moolenaar51e14382019-05-25 20:21:28 +02004442 buf = alloc(MAXPATHL);
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004443 if (buf == NULL)
4444 return FAIL;
4445 STRNCPY(buf, path, MAXPATHL-5);
Bram Moolenaar71de7202019-05-24 19:04:29 +02004446 p = buf + STRLEN(buf);
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004447 MB_PTR_BACK(buf, p);
4448 if (*p == '\\' || *p == '/')
4449 *p = NUL;
4450 STRCAT(buf, "\\*");
4451
4452 wn = enc_to_utf16(buf, NULL);
4453 if (wn != NULL)
4454 hFind = FindFirstFileW(wn, &wfb);
4455 ok = (hFind != INVALID_HANDLE_VALUE);
4456 if (!ok)
4457 {
4458 failed = TRUE;
4459 smsg(_(e_notopen), path);
4460 }
4461 else
4462 {
4463 while (ok)
4464 {
4465 int ignore;
4466
4467 p = utf16_to_enc(wfb.cFileName, NULL); // p is allocated here
4468 if (p == NULL)
4469 break; // out of memory
4470
4471 ignore = p[0] == '.' && (p[1] == NUL
4472 || (p[1] == '.' && p[2] == NUL));
4473 if (!ignore && checkitem != NULL)
4474 {
4475 int r = checkitem(context, p);
4476
4477 if (r < 0)
4478 {
4479 vim_free(p);
4480 break;
4481 }
4482 if (r == 0)
4483 ignore = TRUE;
4484 }
4485
4486 if (!ignore)
4487 {
4488 if (ga_grow(gap, 1) == OK)
4489 ((char_u**)gap->ga_data)[gap->ga_len++] = vim_strsave(p);
4490 else
4491 {
4492 failed = TRUE;
4493 vim_free(p);
4494 break;
4495 }
4496 }
4497
4498 vim_free(p);
4499 ok = FindNextFileW(hFind, &wfb);
4500 }
4501 FindClose(hFind);
4502 }
4503
4504 vim_free(buf);
4505 vim_free(wn);
4506#else
4507 DIR *dirp;
4508 struct dirent *dp;
4509 char_u *p;
4510
4511 dirp = opendir((char *)path);
4512 if (dirp == NULL)
4513 {
4514 failed = TRUE;
4515 smsg(_(e_notopen), path);
4516 }
4517 else
4518 {
4519 for (;;)
4520 {
4521 int ignore;
4522
4523 dp = readdir(dirp);
4524 if (dp == NULL)
4525 break;
4526 p = (char_u *)dp->d_name;
4527
4528 ignore = p[0] == '.' &&
4529 (p[1] == NUL ||
4530 (p[1] == '.' && p[2] == NUL));
4531 if (!ignore && checkitem != NULL)
4532 {
4533 int r = checkitem(context, p);
4534
4535 if (r < 0)
4536 break;
4537 if (r == 0)
4538 ignore = TRUE;
4539 }
4540
4541 if (!ignore)
4542 {
4543 if (ga_grow(gap, 1) == OK)
4544 ((char_u**)gap->ga_data)[gap->ga_len++] = vim_strsave(p);
4545 else
4546 {
4547 failed = TRUE;
4548 break;
4549 }
4550 }
4551 }
4552
4553 closedir(dirp);
4554 }
4555#endif
4556
4557 if (!failed && gap->ga_len > 0)
4558 sort_strings((char_u **)gap->ga_data, gap->ga_len);
4559
4560 return failed ? FAIL : OK;
4561}
4562
4563/*
Bram Moolenaarda440d22016-01-16 21:27:23 +01004564 * Delete "name" and everything in it, recursively.
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004565 * return 0 for success, -1 if some file was not deleted.
Bram Moolenaarda440d22016-01-16 21:27:23 +01004566 */
4567 int
4568delete_recursive(char_u *name)
4569{
4570 int result = 0;
Bram Moolenaarda440d22016-01-16 21:27:23 +01004571 int i;
4572 char_u *exp;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004573 garray_T ga;
Bram Moolenaarda440d22016-01-16 21:27:23 +01004574
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004575 // A symbolic link to a directory itself is deleted, not the directory it
4576 // points to.
Bram Moolenaar43a34f92016-01-17 15:56:34 +01004577 if (
Bram Moolenaar4f974752019-02-17 17:44:42 +01004578# if defined(UNIX) || defined(MSWIN)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01004579 mch_isrealdir(name)
Bram Moolenaar203258c2016-01-17 22:15:16 +01004580# else
Bram Moolenaar43a34f92016-01-17 15:56:34 +01004581 mch_isdir(name)
Bram Moolenaar43a34f92016-01-17 15:56:34 +01004582# endif
4583 )
Bram Moolenaarda440d22016-01-16 21:27:23 +01004584 {
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004585 exp = vim_strsave(name);
Bram Moolenaarda440d22016-01-16 21:27:23 +01004586 if (exp == NULL)
4587 return -1;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004588 if (readdir_core(&ga, exp, NULL, NULL) == OK)
Bram Moolenaarda440d22016-01-16 21:27:23 +01004589 {
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004590 for (i = 0; i < ga.ga_len; ++i)
4591 {
4592 vim_snprintf((char *)NameBuff, MAXPATHL, "%s/%s", exp,
4593 ((char_u **)ga.ga_data)[i]);
4594 if (delete_recursive(NameBuff) != 0)
Bram Moolenaarda440d22016-01-16 21:27:23 +01004595 result = -1;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004596 }
4597 ga_clear_strings(&ga);
Bram Moolenaarda440d22016-01-16 21:27:23 +01004598 }
4599 else
4600 result = -1;
Bram Moolenaar701ff0a2019-05-24 14:14:14 +02004601 (void)mch_rmdir(exp);
Bram Moolenaarda440d22016-01-16 21:27:23 +01004602 vim_free(exp);
Bram Moolenaarda440d22016-01-16 21:27:23 +01004603 }
4604 else
4605 result = mch_remove(name) == 0 ? 0 : -1;
4606
4607 return result;
4608}
4609#endif
4610
Bram Moolenaar071d4272004-06-13 20:20:40 +00004611#if defined(TEMPDIRNAMES) || defined(PROTO)
4612static long temp_count = 0; /* Temp filename counter. */
4613
4614/*
4615 * Delete the temp directory and all files it contains.
4616 */
4617 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004618vim_deltempdir(void)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004619{
Bram Moolenaar071d4272004-06-13 20:20:40 +00004620 if (vim_tempdir != NULL)
4621 {
Bram Moolenaarda440d22016-01-16 21:27:23 +01004622 /* remove the trailing path separator */
4623 gettail(vim_tempdir)[-1] = NUL;
4624 delete_recursive(vim_tempdir);
Bram Moolenaard23a8232018-02-10 18:45:26 +01004625 VIM_CLEAR(vim_tempdir);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004626 }
4627}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004628
4629/*
Bram Moolenaareaf03392009-11-17 11:08:52 +00004630 * Directory "tempdir" was created. Expand this name to a full path and put
4631 * it in "vim_tempdir". This avoids that using ":cd" would confuse us.
4632 * "tempdir" must be no longer than MAXPATHL.
4633 */
4634 static void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004635vim_settempdir(char_u *tempdir)
Bram Moolenaareaf03392009-11-17 11:08:52 +00004636{
4637 char_u *buf;
4638
Bram Moolenaar964b3742019-05-24 18:54:09 +02004639 buf = alloc(MAXPATHL + 2);
Bram Moolenaareaf03392009-11-17 11:08:52 +00004640 if (buf != NULL)
4641 {
4642 if (vim_FullName(tempdir, buf, MAXPATHL, FALSE) == FAIL)
4643 STRCPY(buf, tempdir);
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004644 add_pathsep(buf);
Bram Moolenaareaf03392009-11-17 11:08:52 +00004645 vim_tempdir = vim_strsave(buf);
4646 vim_free(buf);
4647 }
4648}
Bram Moolenaar4592dee2009-11-18 19:11:58 +00004649#endif
Bram Moolenaareaf03392009-11-17 11:08:52 +00004650
4651/*
Bram Moolenaar071d4272004-06-13 20:20:40 +00004652 * vim_tempname(): Return a unique name that can be used for a temp file.
4653 *
Bram Moolenaar76ae22f2016-06-13 20:00:29 +02004654 * The temp file is NOT guaranteed to be created. If "keep" is FALSE it is
4655 * guaranteed to NOT be created.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004656 *
4657 * The returned pointer is to allocated memory.
4658 * The returned pointer is NULL if no valid name was found.
4659 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004660 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004661vim_tempname(
4662 int extra_char UNUSED, /* char to use in the name instead of '?' */
4663 int keep UNUSED)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004664{
4665#ifdef USE_TMPNAM
4666 char_u itmp[L_tmpnam]; /* use tmpnam() */
Bram Moolenaar4f974752019-02-17 17:44:42 +01004667#elif defined(MSWIN)
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01004668 WCHAR itmp[TEMPNAMELEN];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004669#else
4670 char_u itmp[TEMPNAMELEN];
4671#endif
4672
4673#ifdef TEMPDIRNAMES
4674 static char *(tempdirs[]) = {TEMPDIRNAMES};
4675 int i;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004676# ifndef EEXIST
Bram Moolenaar8767f522016-07-01 17:17:39 +02004677 stat_T st;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004678# endif
4679
4680 /*
4681 * This will create a directory for private use by this instance of Vim.
4682 * This is done once, and the same directory is used for all temp files.
4683 * This method avoids security problems because of symlink attacks et al.
4684 * It's also a bit faster, because we only need to check for an existing
4685 * file when creating the directory and not for each temp file.
4686 */
4687 if (vim_tempdir == NULL)
4688 {
4689 /*
4690 * Try the entries in TEMPDIRNAMES to create the temp directory.
4691 */
Bram Moolenaar78a15312009-05-15 19:33:18 +00004692 for (i = 0; i < (int)(sizeof(tempdirs) / sizeof(char *)); ++i)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004693 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00004694# ifndef HAVE_MKDTEMP
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01004695 size_t itmplen;
Bram Moolenaareaf03392009-11-17 11:08:52 +00004696 long nr;
4697 long off;
4698# endif
4699
Bram Moolenaare1a61992015-12-03 21:02:27 +01004700 /* Expand $TMP, leave room for "/v1100000/999999999".
4701 * Skip the directory check if the expansion fails. */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004702 expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 20);
Bram Moolenaare1a61992015-12-03 21:02:27 +01004703 if (itmp[0] != '$' && mch_isdir(itmp))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004704 {
Bram Moolenaare1a61992015-12-03 21:02:27 +01004705 /* directory exists */
Bram Moolenaara06ecab2016-07-16 14:47:36 +02004706 add_pathsep(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004707
Bram Moolenaareaf03392009-11-17 11:08:52 +00004708# ifdef HAVE_MKDTEMP
Bram Moolenaar35d88f42016-06-04 14:52:00 +02004709 {
4710# if defined(UNIX) || defined(VMS)
4711 /* Make sure the umask doesn't remove the executable bit.
4712 * "repl" has been reported to use "177". */
4713 mode_t umask_save = umask(077);
4714# endif
4715 /* Leave room for filename */
4716 STRCAT(itmp, "vXXXXXX");
4717 if (mkdtemp((char *)itmp) != NULL)
4718 vim_settempdir(itmp);
4719# if defined(UNIX) || defined(VMS)
4720 (void)umask(umask_save);
4721# endif
4722 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00004723# else
Bram Moolenaar071d4272004-06-13 20:20:40 +00004724 /* Get an arbitrary number of up to 6 digits. When it's
4725 * unlikely that it already exists it will be faster,
4726 * otherwise it doesn't matter. The use of mkdir() avoids any
4727 * security problems because of the predictable number. */
4728 nr = (mch_get_pid() + (long)time(NULL)) % 1000000L;
Bram Moolenaar2660c0e2010-01-19 14:59:56 +01004729 itmplen = STRLEN(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004730
4731 /* Try up to 10000 different values until we find a name that
4732 * doesn't exist. */
4733 for (off = 0; off < 10000L; ++off)
4734 {
4735 int r;
Bram Moolenaareaf03392009-11-17 11:08:52 +00004736# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004737 mode_t umask_save;
Bram Moolenaareaf03392009-11-17 11:08:52 +00004738# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004739
Bram Moolenaareaf03392009-11-17 11:08:52 +00004740 sprintf((char *)itmp + itmplen, "v%ld", nr + off);
4741# ifndef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00004742 /* If mkdir() does not set errno to EEXIST, check for
4743 * existing file here. There is a race condition then,
4744 * although it's fail-safe. */
4745 if (mch_stat((char *)itmp, &st) >= 0)
4746 continue;
Bram Moolenaareaf03392009-11-17 11:08:52 +00004747# endif
4748# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004749 /* Make sure the umask doesn't remove the executable bit.
4750 * "repl" has been reported to use "177". */
4751 umask_save = umask(077);
Bram Moolenaareaf03392009-11-17 11:08:52 +00004752# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004753 r = vim_mkdir(itmp, 0700);
Bram Moolenaareaf03392009-11-17 11:08:52 +00004754# if defined(UNIX) || defined(VMS)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004755 (void)umask(umask_save);
Bram Moolenaareaf03392009-11-17 11:08:52 +00004756# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004757 if (r == 0)
4758 {
Bram Moolenaareaf03392009-11-17 11:08:52 +00004759 vim_settempdir(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004760 break;
4761 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00004762# ifdef EEXIST
Bram Moolenaar071d4272004-06-13 20:20:40 +00004763 /* If the mkdir() didn't fail because the file/dir exists,
4764 * we probably can't create any dir here, try another
4765 * place. */
4766 if (errno != EEXIST)
Bram Moolenaareaf03392009-11-17 11:08:52 +00004767# endif
Bram Moolenaar071d4272004-06-13 20:20:40 +00004768 break;
4769 }
Bram Moolenaareaf03392009-11-17 11:08:52 +00004770# endif /* HAVE_MKDTEMP */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004771 if (vim_tempdir != NULL)
4772 break;
4773 }
4774 }
4775 }
4776
4777 if (vim_tempdir != NULL)
4778 {
4779 /* There is no need to check if the file exists, because we own the
4780 * directory and nobody else creates a file in it. */
4781 sprintf((char *)itmp, "%s%ld", vim_tempdir, temp_count++);
4782 return vim_strsave(itmp);
4783 }
4784
4785 return NULL;
4786
4787#else /* TEMPDIRNAMES */
4788
Bram Moolenaar4f974752019-02-17 17:44:42 +01004789# ifdef MSWIN
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01004790 WCHAR wszTempFile[_MAX_PATH + 1];
4791 WCHAR buf4[4];
Bram Moolenaar071d4272004-06-13 20:20:40 +00004792 char_u *retval;
4793 char_u *p;
4794
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01004795 wcscpy(itmp, L"");
4796 if (GetTempPathW(_MAX_PATH, wszTempFile) == 0)
Bram Moolenaarb1891912011-02-09 14:47:03 +01004797 {
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01004798 wszTempFile[0] = L'.'; // GetTempPathW() failed, use current dir
4799 wszTempFile[1] = NUL;
Bram Moolenaarb1891912011-02-09 14:47:03 +01004800 }
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01004801 wcscpy(buf4, L"VIM");
Bram Moolenaar071d4272004-06-13 20:20:40 +00004802 buf4[2] = extra_char; /* make it "VIa", "VIb", etc. */
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01004803 if (GetTempFileNameW(wszTempFile, buf4, 0, itmp) == 0)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004804 return NULL;
Bram Moolenaare5c421c2015-03-31 13:33:08 +02004805 if (!keep)
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01004806 // GetTempFileName() will create the file, we don't want that
4807 (void)DeleteFileW(itmp);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004808
Bram Moolenaarec0f50a2019-02-10 23:26:13 +01004809 // Backslashes in a temp file name cause problems when filtering with
4810 // "sh". NOTE: This also checks 'shellcmdflag' to help those people who
4811 // didn't set 'shellslash'.
4812 retval = utf16_to_enc(itmp, NULL);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004813 if (*p_shcf == '-' || p_ssl)
4814 for (p = retval; *p; ++p)
4815 if (*p == '\\')
4816 *p = '/';
4817 return retval;
4818
Bram Moolenaar4f974752019-02-17 17:44:42 +01004819# else // MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004820
4821# ifdef USE_TMPNAM
Bram Moolenaar95474ca2011-02-09 16:44:51 +01004822 char_u *p;
4823
Bram Moolenaar071d4272004-06-13 20:20:40 +00004824 /* tmpnam() will make its own name */
Bram Moolenaar95474ca2011-02-09 16:44:51 +01004825 p = tmpnam((char *)itmp);
4826 if (p == NULL || *p == NUL)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004827 return NULL;
4828# else
4829 char_u *p;
4830
4831# ifdef VMS_TEMPNAM
4832 /* mktemp() is not working on VMS. It seems to be
4833 * a do-nothing function. Therefore we use tempnam().
4834 */
4835 sprintf((char *)itmp, "VIM%c", extra_char);
4836 p = (char_u *)tempnam("tmp:", (char *)itmp);
4837 if (p != NULL)
4838 {
Bram Moolenaar206f0112014-03-12 16:51:55 +01004839 /* VMS will use '.LIS' if we don't explicitly specify an extension,
Bram Moolenaar071d4272004-06-13 20:20:40 +00004840 * and VIM will then be unable to find the file later */
4841 STRCPY(itmp, p);
4842 STRCAT(itmp, ".txt");
4843 free(p);
4844 }
4845 else
4846 return NULL;
4847# else
4848 STRCPY(itmp, TEMPNAME);
4849 if ((p = vim_strchr(itmp, '?')) != NULL)
4850 *p = extra_char;
4851 if (mktemp((char *)itmp) == NULL)
4852 return NULL;
4853# endif
4854# endif
4855
4856 return vim_strsave(itmp);
Bram Moolenaar4f974752019-02-17 17:44:42 +01004857# endif // MSWIN
Bram Moolenaar071d4272004-06-13 20:20:40 +00004858#endif /* TEMPDIRNAMES */
4859}
4860
4861#if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
4862/*
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02004863 * Convert all backslashes in fname to forward slashes in-place, unless when
4864 * it looks like a URL.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004865 */
4866 void
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004867forward_slash(char_u *fname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004868{
4869 char_u *p;
4870
Bram Moolenaarb4f6a462015-10-13 19:43:17 +02004871 if (path_with_url(fname))
4872 return;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004873 for (p = fname; *p != NUL; ++p)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004874 /* The Big5 encoding can have '\' in the trail byte. */
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00004875 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004876 ++p;
Bram Moolenaar13505972019-01-24 15:04:48 +01004877 else if (*p == '\\')
Bram Moolenaar071d4272004-06-13 20:20:40 +00004878 *p = '/';
4879}
4880#endif
4881
Bram Moolenaarf30e74c2006-08-16 17:35:00 +00004882/*
Bram Moolenaar748bf032005-02-02 23:04:36 +00004883 * Try matching a filename with a "pattern" ("prog" is NULL), or use the
4884 * precompiled regprog "prog" ("pattern" is NULL). That avoids calling
4885 * vim_regcomp() often.
Bram Moolenaar071d4272004-06-13 20:20:40 +00004886 * Used for autocommands and 'wildignore'.
4887 * Returns TRUE if there is a match, FALSE otherwise.
4888 */
Bram Moolenaar3e460fd2019-01-26 16:21:07 +01004889 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004890match_file_pat(
4891 char_u *pattern, /* pattern to match with */
4892 regprog_T **prog, /* pre-compiled regprog or NULL */
4893 char_u *fname, /* full path of file name */
4894 char_u *sfname, /* short file name or NULL */
4895 char_u *tail, /* tail of path */
4896 int allow_dirs) /* allow matching with dir */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004897{
4898 regmatch_T regmatch;
4899 int result = FALSE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004900
Bram Moolenaar71afbfe2013-03-19 16:49:16 +01004901 regmatch.rm_ic = p_fic; /* ignore case if 'fileignorecase' is set */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01004902 if (prog != NULL)
4903 regmatch.regprog = *prog;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004904 else
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01004905 regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004906
4907 /*
4908 * Try for a match with the pattern with:
4909 * 1. the full file name, when the pattern has a '/'.
4910 * 2. the short file name, when the pattern has a '/'.
4911 * 3. the tail of the file name, when the pattern has no '/'.
4912 */
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01004913 if (regmatch.regprog != NULL
Bram Moolenaar071d4272004-06-13 20:20:40 +00004914 && ((allow_dirs
4915 && (vim_regexec(&regmatch, fname, (colnr_T)0)
4916 || (sfname != NULL
4917 && vim_regexec(&regmatch, sfname, (colnr_T)0))))
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01004918 || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0))))
Bram Moolenaar071d4272004-06-13 20:20:40 +00004919 result = TRUE;
4920
Bram Moolenaardffa5b82014-11-19 16:38:07 +01004921 if (prog != NULL)
4922 *prog = regmatch.regprog;
4923 else
Bram Moolenaar473de612013-06-08 18:19:48 +02004924 vim_regfree(regmatch.regprog);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004925 return result;
4926}
Bram Moolenaar071d4272004-06-13 20:20:40 +00004927
4928#if defined(FEAT_WILDIGN) || defined(PROTO)
4929/*
4930 * Return TRUE if a file matches with a pattern in "list".
4931 * "list" is a comma-separated list of patterns, like 'wildignore'.
4932 * "sfname" is the short file name or NULL, "ffname" the long file name.
4933 */
4934 int
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004935match_file_list(char_u *list, char_u *sfname, char_u *ffname)
Bram Moolenaar071d4272004-06-13 20:20:40 +00004936{
4937 char_u buf[100];
4938 char_u *tail;
4939 char_u *regpat;
4940 char allow_dirs;
4941 int match;
4942 char_u *p;
4943
4944 tail = gettail(sfname);
4945
4946 /* try all patterns in 'wildignore' */
4947 p = list;
4948 while (*p)
4949 {
4950 copy_option_part(&p, buf, 100, ",");
4951 regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, FALSE);
4952 if (regpat == NULL)
4953 break;
Bram Moolenaar748bf032005-02-02 23:04:36 +00004954 match = match_file_pat(regpat, NULL, ffname, sfname,
4955 tail, (int)allow_dirs);
Bram Moolenaar071d4272004-06-13 20:20:40 +00004956 vim_free(regpat);
4957 if (match)
4958 return TRUE;
4959 }
4960 return FALSE;
4961}
4962#endif
4963
4964/*
4965 * Convert the given pattern "pat" which has shell style wildcards in it, into
4966 * a regular expression, and return the result in allocated memory. If there
4967 * is a directory path separator to be matched, then TRUE is put in
4968 * allow_dirs, otherwise FALSE is put there -- webb.
4969 * Handle backslashes before special characters, like "\*" and "\ ".
4970 *
Bram Moolenaar071d4272004-06-13 20:20:40 +00004971 * Returns NULL when out of memory.
4972 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004973 char_u *
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01004974file_pat_to_reg_pat(
4975 char_u *pat,
4976 char_u *pat_end, /* first char after pattern or NULL */
4977 char *allow_dirs, /* Result passed back out in here */
4978 int no_bslash UNUSED) /* Don't use a backward slash as pathsep */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004979{
Bram Moolenaar49a6ed82015-01-07 14:43:39 +01004980 int size = 2; /* '^' at start, '$' at end */
Bram Moolenaar071d4272004-06-13 20:20:40 +00004981 char_u *endp;
4982 char_u *reg_pat;
4983 char_u *p;
4984 int i;
4985 int nested = 0;
4986 int add_dollar = TRUE;
Bram Moolenaar071d4272004-06-13 20:20:40 +00004987
4988 if (allow_dirs != NULL)
4989 *allow_dirs = FALSE;
4990 if (pat_end == NULL)
4991 pat_end = pat + STRLEN(pat);
4992
Bram Moolenaar071d4272004-06-13 20:20:40 +00004993 for (p = pat; p < pat_end; p++)
4994 {
4995 switch (*p)
4996 {
4997 case '*':
4998 case '.':
4999 case ',':
5000 case '{':
5001 case '}':
5002 case '~':
5003 size += 2; /* extra backslash */
5004 break;
5005#ifdef BACKSLASH_IN_FILENAME
5006 case '\\':
5007 case '/':
5008 size += 4; /* could become "[\/]" */
5009 break;
5010#endif
5011 default:
5012 size++;
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005013 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005014 {
5015 ++p;
5016 ++size;
5017 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005018 break;
5019 }
5020 }
5021 reg_pat = alloc(size + 1);
5022 if (reg_pat == NULL)
5023 return NULL;
5024
Bram Moolenaar071d4272004-06-13 20:20:40 +00005025 i = 0;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005026
5027 if (pat[0] == '*')
5028 while (pat[0] == '*' && pat < pat_end - 1)
5029 pat++;
5030 else
5031 reg_pat[i++] = '^';
5032 endp = pat_end - 1;
Bram Moolenaar8fee8782015-08-11 18:45:48 +02005033 if (endp >= pat && *endp == '*')
Bram Moolenaar071d4272004-06-13 20:20:40 +00005034 {
5035 while (endp - pat > 0 && *endp == '*')
5036 endp--;
5037 add_dollar = FALSE;
5038 }
5039 for (p = pat; *p && nested >= 0 && p <= endp; p++)
5040 {
5041 switch (*p)
5042 {
5043 case '*':
5044 reg_pat[i++] = '.';
5045 reg_pat[i++] = '*';
Bram Moolenaar02743632005-07-25 20:42:36 +00005046 while (p[1] == '*') /* "**" matches like "*" */
5047 ++p;
Bram Moolenaar071d4272004-06-13 20:20:40 +00005048 break;
5049 case '.':
Bram Moolenaar071d4272004-06-13 20:20:40 +00005050 case '~':
5051 reg_pat[i++] = '\\';
5052 reg_pat[i++] = *p;
5053 break;
5054 case '?':
Bram Moolenaar071d4272004-06-13 20:20:40 +00005055 reg_pat[i++] = '.';
5056 break;
5057 case '\\':
5058 if (p[1] == NUL)
5059 break;
5060#ifdef BACKSLASH_IN_FILENAME
5061 if (!no_bslash)
5062 {
5063 /* translate:
5064 * "\x" to "\\x" e.g., "dir\file"
5065 * "\*" to "\\.*" e.g., "dir\*.c"
5066 * "\?" to "\\." e.g., "dir\??.c"
5067 * "\+" to "\+" e.g., "fileX\+.c"
5068 */
5069 if ((vim_isfilec(p[1]) || p[1] == '*' || p[1] == '?')
5070 && p[1] != '+')
5071 {
5072 reg_pat[i++] = '[';
5073 reg_pat[i++] = '\\';
5074 reg_pat[i++] = '/';
5075 reg_pat[i++] = ']';
5076 if (allow_dirs != NULL)
5077 *allow_dirs = TRUE;
5078 break;
5079 }
5080 }
5081#endif
Bram Moolenaar8cd213c2010-06-01 21:57:09 +02005082 /* Undo escaping from ExpandEscape():
5083 * foo\?bar -> foo?bar
5084 * foo\%bar -> foo%bar
5085 * foo\,bar -> foo,bar
5086 * foo\ bar -> foo bar
5087 * Don't unescape \, * and others that are also special in a
Bram Moolenaarf4e11432013-07-03 16:53:03 +02005088 * regexp.
5089 * An escaped { must be unescaped since we use magic not
Bram Moolenaara946afe2013-08-02 15:22:39 +02005090 * verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
Bram Moolenaarf4e11432013-07-03 16:53:03 +02005091 */
Bram Moolenaar071d4272004-06-13 20:20:40 +00005092 if (*++p == '?'
5093#ifdef BACKSLASH_IN_FILENAME
5094 && no_bslash
5095#endif
5096 )
5097 reg_pat[i++] = '?';
5098 else
Bram Moolenaarf4e11432013-07-03 16:53:03 +02005099 if (*p == ',' || *p == '%' || *p == '#'
Bram Moolenaar2288afe2015-08-11 16:20:05 +02005100 || vim_isspace(*p) || *p == '{' || *p == '}')
Bram Moolenaar8cd213c2010-06-01 21:57:09 +02005101 reg_pat[i++] = *p;
Bram Moolenaara946afe2013-08-02 15:22:39 +02005102 else if (*p == '\\' && p[1] == '\\' && p[2] == '{')
5103 {
5104 reg_pat[i++] = '\\';
5105 reg_pat[i++] = '{';
5106 p += 2;
5107 }
Bram Moolenaar071d4272004-06-13 20:20:40 +00005108 else
5109 {
5110 if (allow_dirs != NULL && vim_ispathsep(*p)
5111#ifdef BACKSLASH_IN_FILENAME
5112 && (!no_bslash || *p != '\\')
5113#endif
5114 )
5115 *allow_dirs = TRUE;
5116 reg_pat[i++] = '\\';
5117 reg_pat[i++] = *p;
5118 }
5119 break;
5120#ifdef BACKSLASH_IN_FILENAME
5121 case '/':
5122 reg_pat[i++] = '[';
5123 reg_pat[i++] = '\\';
5124 reg_pat[i++] = '/';
5125 reg_pat[i++] = ']';
5126 if (allow_dirs != NULL)
5127 *allow_dirs = TRUE;
5128 break;
5129#endif
5130 case '{':
5131 reg_pat[i++] = '\\';
5132 reg_pat[i++] = '(';
5133 nested++;
5134 break;
5135 case '}':
5136 reg_pat[i++] = '\\';
5137 reg_pat[i++] = ')';
5138 --nested;
5139 break;
5140 case ',':
5141 if (nested)
5142 {
5143 reg_pat[i++] = '\\';
5144 reg_pat[i++] = '|';
5145 }
5146 else
5147 reg_pat[i++] = ',';
5148 break;
5149 default:
Bram Moolenaar0fa313a2005-08-10 21:07:57 +00005150 if (enc_dbcs != 0 && (*mb_ptr2len)(p) > 1)
Bram Moolenaar071d4272004-06-13 20:20:40 +00005151 reg_pat[i++] = *p++;
Bram Moolenaar13505972019-01-24 15:04:48 +01005152 else if (allow_dirs != NULL && vim_ispathsep(*p))
Bram Moolenaar071d4272004-06-13 20:20:40 +00005153 *allow_dirs = TRUE;
5154 reg_pat[i++] = *p;
5155 break;
5156 }
5157 }
5158 if (add_dollar)
5159 reg_pat[i++] = '$';
5160 reg_pat[i] = NUL;
5161 if (nested != 0)
5162 {
5163 if (nested < 0)
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005164 emsg(_("E219: Missing {."));
Bram Moolenaar071d4272004-06-13 20:20:40 +00005165 else
Bram Moolenaarf9e3e092019-01-13 23:38:42 +01005166 emsg(_("E220: Missing }."));
Bram Moolenaard23a8232018-02-10 18:45:26 +01005167 VIM_CLEAR(reg_pat);
Bram Moolenaar071d4272004-06-13 20:20:40 +00005168 }
5169 return reg_pat;
5170}
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005171
5172#if defined(EINTR) || defined(PROTO)
5173/*
5174 * Version of read() that retries when interrupted by EINTR (possibly
5175 * by a SIGWINCH).
5176 */
5177 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005178read_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005179{
5180 long ret;
5181
5182 for (;;)
5183 {
5184 ret = vim_read(fd, buf, bufsize);
5185 if (ret >= 0 || errno != EINTR)
5186 break;
5187 }
5188 return ret;
5189}
5190
5191/*
5192 * Version of write() that retries when interrupted by EINTR (possibly
5193 * by a SIGWINCH).
5194 */
5195 long
Bram Moolenaar78c0b7d2016-01-30 15:52:46 +01005196write_eintr(int fd, void *buf, size_t bufsize)
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005197{
5198 long ret = 0;
5199 long wlen;
5200
5201 /* Repeat the write() so long it didn't fail, other than being interrupted
5202 * by a signal. */
5203 while (ret < (long)bufsize)
5204 {
Bram Moolenaar9c263032010-12-17 18:06:06 +01005205 wlen = vim_write(fd, (char *)buf + ret, bufsize - ret);
Bram Moolenaar540fc6f2010-12-17 16:27:16 +01005206 if (wlen < 0)
5207 {
5208 if (errno != EINTR)
5209 break;
5210 }
5211 else
5212 ret += wlen;
5213 }
5214 return ret;
5215}
5216#endif