blob: d7c3034766b6a11186d2480cab44d545a39325eb [file] [log] [blame]
Bram Moolenaar473952e2019-09-28 16:30:04 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
9
10/*
11 * bufwrite.c: functions for writing a buffer
12 */
13
14#include "vim.h"
15
16#if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
17# include <utime.h> // for struct utimbuf
18#endif
19
20#define SMALLBUFSIZE 256 // size of emergency write buffer
21
22/*
23 * Structure to pass arguments from buf_write() to buf_write_bytes().
24 */
25struct bw_info
26{
27 int bw_fd; // file descriptor
28 char_u *bw_buf; // buffer with data to be written
29 int bw_len; // length of data
30 int bw_flags; // FIO_ flags
31#ifdef FEAT_CRYPT
32 buf_T *bw_buffer; // buffer being written
Bram Moolenaar6ed545e2022-05-09 20:09:23 +010033 int bw_finish; // finish encrypting
Bram Moolenaar473952e2019-09-28 16:30:04 +020034#endif
35 char_u bw_rest[CONV_RESTLEN]; // not converted bytes
36 int bw_restlen; // nr of bytes in bw_rest[]
37 int bw_first; // first write call
38 char_u *bw_conv_buf; // buffer for writing converted chars
39 size_t bw_conv_buflen; // size of bw_conv_buf
40 int bw_conv_error; // set for conversion error
41 linenr_T bw_conv_error_lnum; // first line with error or zero
Bram Moolenaar6ed545e2022-05-09 20:09:23 +010042 linenr_T bw_start_lnum; // line number at start of buffer
Bram Moolenaar473952e2019-09-28 16:30:04 +020043#ifdef USE_ICONV
44 iconv_t bw_iconv_fd; // descriptor for iconv() or -1
45#endif
46};
47
48/*
49 * Convert a Unicode character to bytes.
50 * Return TRUE for an error, FALSE when it's OK.
51 */
52 static int
53ucs2bytes(
54 unsigned c, // in: character
55 char_u **pp, // in/out: pointer to result
56 int flags) // FIO_ flags
57{
58 char_u *p = *pp;
59 int error = FALSE;
60 int cc;
61
62
63 if (flags & FIO_UCS4)
64 {
65 if (flags & FIO_ENDIAN_L)
66 {
67 *p++ = c;
68 *p++ = (c >> 8);
69 *p++ = (c >> 16);
70 *p++ = (c >> 24);
71 }
72 else
73 {
74 *p++ = (c >> 24);
75 *p++ = (c >> 16);
76 *p++ = (c >> 8);
77 *p++ = c;
78 }
79 }
80 else if (flags & (FIO_UCS2 | FIO_UTF16))
81 {
82 if (c >= 0x10000)
83 {
84 if (flags & FIO_UTF16)
85 {
86 // Make two words, ten bits of the character in each. First
87 // word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff
88 c -= 0x10000;
89 if (c >= 0x100000)
90 error = TRUE;
91 cc = ((c >> 10) & 0x3ff) + 0xd800;
92 if (flags & FIO_ENDIAN_L)
93 {
94 *p++ = cc;
95 *p++ = ((unsigned)cc >> 8);
96 }
97 else
98 {
99 *p++ = ((unsigned)cc >> 8);
100 *p++ = cc;
101 }
102 c = (c & 0x3ff) + 0xdc00;
103 }
104 else
105 error = TRUE;
106 }
107 if (flags & FIO_ENDIAN_L)
108 {
109 *p++ = c;
110 *p++ = (c >> 8);
111 }
112 else
113 {
114 *p++ = (c >> 8);
115 *p++ = c;
116 }
117 }
118 else // Latin1
119 {
120 if (c >= 0x100)
121 {
122 error = TRUE;
123 *p++ = 0xBF;
124 }
125 else
126 *p++ = c;
127 }
128
129 *pp = p;
130 return error;
131}
132
133/*
134 * Call write() to write a number of bytes to the file.
135 * Handles encryption and 'encoding' conversion.
136 *
137 * Return FAIL for failure, OK otherwise.
138 */
139 static int
140buf_write_bytes(struct bw_info *ip)
141{
142 int wlen;
143 char_u *buf = ip->bw_buf; // data to write
144 int len = ip->bw_len; // length of data
145 int flags = ip->bw_flags; // extra flags
146
147 // Skip conversion when writing the crypt magic number or the BOM.
148 if (!(flags & FIO_NOCONVERT))
149 {
150 char_u *p;
151 unsigned c;
152 int n;
153
154 if (flags & FIO_UTF8)
155 {
156 // Convert latin1 in the buffer to UTF-8 in the file.
157 p = ip->bw_conv_buf; // translate to buffer
158 for (wlen = 0; wlen < len; ++wlen)
159 p += utf_char2bytes(buf[wlen], p);
160 buf = ip->bw_conv_buf;
161 len = (int)(p - ip->bw_conv_buf);
162 }
163 else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1))
164 {
165 // Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
166 // Latin1 chars in the file.
167 if (flags & FIO_LATIN1)
168 p = buf; // translate in-place (can only get shorter)
169 else
170 p = ip->bw_conv_buf; // translate to buffer
171 for (wlen = 0; wlen < len; wlen += n)
172 {
173 if (wlen == 0 && ip->bw_restlen != 0)
174 {
175 int l;
176
177 // Use remainder of previous call. Append the start of
178 // buf[] to get a full sequence. Might still be too
179 // short!
180 l = CONV_RESTLEN - ip->bw_restlen;
181 if (l > len)
182 l = len;
183 mch_memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
184 n = utf_ptr2len_len(ip->bw_rest, ip->bw_restlen + l);
185 if (n > ip->bw_restlen + len)
186 {
187 // We have an incomplete byte sequence at the end to
188 // be written. We can't convert it without the
189 // remaining bytes. Keep them for the next call.
190 if (ip->bw_restlen + len > CONV_RESTLEN)
191 return FAIL;
192 ip->bw_restlen += len;
193 break;
194 }
195 if (n > 1)
196 c = utf_ptr2char(ip->bw_rest);
197 else
198 c = ip->bw_rest[0];
199 if (n >= ip->bw_restlen)
200 {
201 n -= ip->bw_restlen;
202 ip->bw_restlen = 0;
203 }
204 else
205 {
206 ip->bw_restlen -= n;
207 mch_memmove(ip->bw_rest, ip->bw_rest + n,
208 (size_t)ip->bw_restlen);
209 n = 0;
210 }
211 }
212 else
213 {
214 n = utf_ptr2len_len(buf + wlen, len - wlen);
215 if (n > len - wlen)
216 {
217 // We have an incomplete byte sequence at the end to
218 // be written. We can't convert it without the
219 // remaining bytes. Keep them for the next call.
220 if (len - wlen > CONV_RESTLEN)
221 return FAIL;
222 ip->bw_restlen = len - wlen;
223 mch_memmove(ip->bw_rest, buf + wlen,
224 (size_t)ip->bw_restlen);
225 break;
226 }
227 if (n > 1)
228 c = utf_ptr2char(buf + wlen);
229 else
230 c = buf[wlen];
231 }
232
233 if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error)
234 {
235 ip->bw_conv_error = TRUE;
236 ip->bw_conv_error_lnum = ip->bw_start_lnum;
237 }
238 if (c == NL)
239 ++ip->bw_start_lnum;
240 }
241 if (flags & FIO_LATIN1)
242 len = (int)(p - buf);
243 else
244 {
245 buf = ip->bw_conv_buf;
246 len = (int)(p - ip->bw_conv_buf);
247 }
248 }
249
250#ifdef MSWIN
251 else if (flags & FIO_CODEPAGE)
252 {
253 // Convert UTF-8 or codepage to UCS-2 and then to MS-Windows
254 // codepage.
255 char_u *from;
256 size_t fromlen;
257 char_u *to;
258 int u8c;
259 BOOL bad = FALSE;
260 int needed;
261
262 if (ip->bw_restlen > 0)
263 {
264 // Need to concatenate the remainder of the previous call and
265 // the bytes of the current call. Use the end of the
266 // conversion buffer for this.
267 fromlen = len + ip->bw_restlen;
268 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
269 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
270 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
271 }
272 else
273 {
274 from = buf;
275 fromlen = len;
276 }
277
278 to = ip->bw_conv_buf;
279 if (enc_utf8)
280 {
281 // Convert from UTF-8 to UCS-2, to the start of the buffer.
282 // The buffer has been allocated to be big enough.
283 while (fromlen > 0)
284 {
285 n = (int)utf_ptr2len_len(from, (int)fromlen);
286 if (n > (int)fromlen) // incomplete byte sequence
287 break;
288 u8c = utf_ptr2char(from);
289 *to++ = (u8c & 0xff);
290 *to++ = (u8c >> 8);
291 fromlen -= n;
292 from += n;
293 }
294
295 // Copy remainder to ip->bw_rest[] to be used for the next
296 // call.
297 if (fromlen > CONV_RESTLEN)
298 {
299 // weird overlong sequence
300 ip->bw_conv_error = TRUE;
301 return FAIL;
302 }
303 mch_memmove(ip->bw_rest, from, fromlen);
304 ip->bw_restlen = (int)fromlen;
305 }
306 else
307 {
308 // Convert from enc_codepage to UCS-2, to the start of the
309 // buffer. The buffer has been allocated to be big enough.
310 ip->bw_restlen = 0;
311 needed = MultiByteToWideChar(enc_codepage,
312 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen,
313 NULL, 0);
314 if (needed == 0)
315 {
316 // When conversion fails there may be a trailing byte.
317 needed = MultiByteToWideChar(enc_codepage,
318 MB_ERR_INVALID_CHARS, (LPCSTR)from, (int)fromlen - 1,
319 NULL, 0);
320 if (needed == 0)
321 {
322 // Conversion doesn't work.
323 ip->bw_conv_error = TRUE;
324 return FAIL;
325 }
326 // Save the trailing byte for the next call.
327 ip->bw_rest[0] = from[fromlen - 1];
328 ip->bw_restlen = 1;
329 }
330 needed = MultiByteToWideChar(enc_codepage, MB_ERR_INVALID_CHARS,
331 (LPCSTR)from, (int)(fromlen - ip->bw_restlen),
332 (LPWSTR)to, needed);
333 if (needed == 0)
334 {
335 // Safety check: Conversion doesn't work.
336 ip->bw_conv_error = TRUE;
337 return FAIL;
338 }
339 to += needed * 2;
340 }
341
342 fromlen = to - ip->bw_conv_buf;
343 buf = to;
344# ifdef CP_UTF8 // VC 4.1 doesn't define CP_UTF8
345 if (FIO_GET_CP(flags) == CP_UTF8)
346 {
347 // Convert from UCS-2 to UTF-8, using the remainder of the
348 // conversion buffer. Fails when out of space.
349 for (from = ip->bw_conv_buf; fromlen > 1; fromlen -= 2)
350 {
351 u8c = *from++;
352 u8c += (*from++ << 8);
353 to += utf_char2bytes(u8c, to);
354 if (to + 6 >= ip->bw_conv_buf + ip->bw_conv_buflen)
355 {
356 ip->bw_conv_error = TRUE;
357 return FAIL;
358 }
359 }
360 len = (int)(to - buf);
361 }
362 else
363# endif
364 {
365 // Convert from UCS-2 to the codepage, using the remainder of
366 // the conversion buffer. If the conversion uses the default
367 // character "0", the data doesn't fit in this encoding, so
368 // fail.
369 len = WideCharToMultiByte(FIO_GET_CP(flags), 0,
370 (LPCWSTR)ip->bw_conv_buf, (int)fromlen / sizeof(WCHAR),
371 (LPSTR)to, (int)(ip->bw_conv_buflen - fromlen), 0,
372 &bad);
373 if (bad)
374 {
375 ip->bw_conv_error = TRUE;
376 return FAIL;
377 }
378 }
379 }
380#endif
381
382#ifdef MACOS_CONVERT
383 else if (flags & FIO_MACROMAN)
384 {
385 // Convert UTF-8 or latin1 to Apple MacRoman.
386 char_u *from;
387 size_t fromlen;
388
389 if (ip->bw_restlen > 0)
390 {
391 // Need to concatenate the remainder of the previous call and
392 // the bytes of the current call. Use the end of the
393 // conversion buffer for this.
394 fromlen = len + ip->bw_restlen;
395 from = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
396 mch_memmove(from, ip->bw_rest, (size_t)ip->bw_restlen);
397 mch_memmove(from + ip->bw_restlen, buf, (size_t)len);
398 }
399 else
400 {
401 from = buf;
402 fromlen = len;
403 }
404
405 if (enc2macroman(from, fromlen,
406 ip->bw_conv_buf, &len, ip->bw_conv_buflen,
407 ip->bw_rest, &ip->bw_restlen) == FAIL)
408 {
409 ip->bw_conv_error = TRUE;
410 return FAIL;
411 }
412 buf = ip->bw_conv_buf;
413 }
414#endif
415
416#ifdef USE_ICONV
417 if (ip->bw_iconv_fd != (iconv_t)-1)
418 {
419 const char *from;
420 size_t fromlen;
421 char *to;
422 size_t tolen;
423
424 // Convert with iconv().
425 if (ip->bw_restlen > 0)
426 {
427 char *fp;
428
429 // Need to concatenate the remainder of the previous call and
430 // the bytes of the current call. Use the end of the
431 // conversion buffer for this.
432 fromlen = len + ip->bw_restlen;
433 fp = (char *)ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
434 mch_memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
435 mch_memmove(fp + ip->bw_restlen, buf, (size_t)len);
436 from = fp;
437 tolen = ip->bw_conv_buflen - fromlen;
438 }
439 else
440 {
441 from = (const char *)buf;
442 fromlen = len;
443 tolen = ip->bw_conv_buflen;
444 }
445 to = (char *)ip->bw_conv_buf;
446
447 if (ip->bw_first)
448 {
449 size_t save_len = tolen;
450
451 // output the initial shift state sequence
452 (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
453
454 // There is a bug in iconv() on Linux (which appears to be
455 // wide-spread) which sets "to" to NULL and messes up "tolen".
456 if (to == NULL)
457 {
458 to = (char *)ip->bw_conv_buf;
459 tolen = save_len;
460 }
461 ip->bw_first = FALSE;
462 }
463
464 // If iconv() has an error or there is not enough room, fail.
465 if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
466 == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
467 || fromlen > CONV_RESTLEN)
468 {
469 ip->bw_conv_error = TRUE;
470 return FAIL;
471 }
472
473 // copy remainder to ip->bw_rest[] to be used for the next call.
474 if (fromlen > 0)
475 mch_memmove(ip->bw_rest, (void *)from, fromlen);
476 ip->bw_restlen = (int)fromlen;
477
478 buf = ip->bw_conv_buf;
479 len = (int)((char_u *)to - ip->bw_conv_buf);
480 }
481#endif
482 }
483
484 if (ip->bw_fd < 0)
485 // Only checking conversion, which is OK if we get here.
486 return OK;
487
488#ifdef FEAT_CRYPT
489 if (flags & FIO_ENCRYPTED)
490 {
491 // Encrypt the data. Do it in-place if possible, otherwise use an
492 // allocated buffer.
493# ifdef CRYPT_NOT_INPLACE
494 if (crypt_works_inplace(ip->bw_buffer->b_cryptstate))
495 {
496# endif
Bram Moolenaar65aee0b2021-06-27 14:08:24 +0200497 crypt_encode_inplace(ip->bw_buffer->b_cryptstate, buf, len,
498 ip->bw_finish);
Bram Moolenaar473952e2019-09-28 16:30:04 +0200499# ifdef CRYPT_NOT_INPLACE
500 }
501 else
502 {
503 char_u *outbuf;
504
Bram Moolenaar65aee0b2021-06-27 14:08:24 +0200505 len = crypt_encode_alloc(curbuf->b_cryptstate, buf, len, &outbuf,
506 ip->bw_finish);
Bram Moolenaar473952e2019-09-28 16:30:04 +0200507 if (len == 0)
508 return OK; // Crypt layer is buffering, will flush later.
509 wlen = write_eintr(ip->bw_fd, outbuf, len);
510 vim_free(outbuf);
511 return (wlen < len) ? FAIL : OK;
512 }
513# endif
514 }
515#endif
516
517 wlen = write_eintr(ip->bw_fd, buf, len);
518 return (wlen < len) ? FAIL : OK;
519}
520
521/*
522 * Check modification time of file, before writing to it.
523 * The size isn't checked, because using a tool like "gzip" takes care of
524 * using the same timestamp but can't set the size.
525 */
526 static int
527check_mtime(buf_T *buf, stat_T *st)
528{
529 if (buf->b_mtime_read != 0
Leah Neukirchen0a7984a2021-10-14 21:27:55 +0100530 && time_differs(st, buf->b_mtime_read, buf->b_mtime_read_ns))
Bram Moolenaar473952e2019-09-28 16:30:04 +0200531 {
532 msg_scroll = TRUE; // don't overwrite messages here
533 msg_silent = 0; // must give this prompt
534 // don't use emsg() here, don't want to flush the buffers
535 msg_attr(_("WARNING: The file has been changed since reading it!!!"),
536 HL_ATTR(HLF_E));
537 if (ask_yesno((char_u *)_("Do you really want to write to it"),
538 TRUE) == 'n')
539 return FAIL;
540 msg_scroll = FALSE; // always overwrite the file message now
541 }
542 return OK;
543}
544
545/*
546 * Generate a BOM in "buf[4]" for encoding "name".
547 * Return the length of the BOM (zero when no BOM).
548 */
549 static int
550make_bom(char_u *buf, char_u *name)
551{
552 int flags;
553 char_u *p;
554
555 flags = get_fio_flags(name);
556
557 // Can't put a BOM in a non-Unicode file.
558 if (flags == FIO_LATIN1 || flags == 0)
559 return 0;
560
561 if (flags == FIO_UTF8) // UTF-8
562 {
563 buf[0] = 0xef;
564 buf[1] = 0xbb;
565 buf[2] = 0xbf;
566 return 3;
567 }
568 p = buf;
569 (void)ucs2bytes(0xfeff, &p, flags);
570 return (int)(p - buf);
571}
572
573#ifdef UNIX
574 static void
575set_file_time(
576 char_u *fname,
577 time_t atime, // access time
578 time_t mtime) // modification time
579{
580# if defined(HAVE_UTIME) && defined(HAVE_UTIME_H)
581 struct utimbuf buf;
582
583 buf.actime = atime;
584 buf.modtime = mtime;
585 (void)utime((char *)fname, &buf);
586# else
587# if defined(HAVE_UTIMES)
588 struct timeval tvp[2];
589
590 tvp[0].tv_sec = atime;
591 tvp[0].tv_usec = 0;
592 tvp[1].tv_sec = mtime;
593 tvp[1].tv_usec = 0;
594# ifdef NeXT
595 (void)utimes((char *)fname, tvp);
596# else
597 (void)utimes((char *)fname, (const struct timeval *)&tvp);
598# endif
599# endif
600# endif
601}
602#endif // UNIX
603
Bram Moolenaar722e5052020-06-12 22:31:00 +0200604 char *
605new_file_message(void)
606{
607 return shortmess(SHM_NEW) ? _("[New]") : _("[New File]");
608}
609
Bram Moolenaar473952e2019-09-28 16:30:04 +0200610/*
611 * buf_write() - write to file "fname" lines "start" through "end"
612 *
613 * We do our own buffering here because fwrite() is so slow.
614 *
615 * If "forceit" is true, we don't care for errors when attempting backups.
616 * In case of an error everything possible is done to restore the original
617 * file. But when "forceit" is TRUE, we risk losing it.
618 *
619 * When "reset_changed" is TRUE and "append" == FALSE and "start" == 1 and
620 * "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
621 *
622 * This function must NOT use NameBuff (because it's called by autowrite()).
623 *
624 * return FAIL for failure, OK otherwise
625 */
626 int
627buf_write(
628 buf_T *buf,
629 char_u *fname,
630 char_u *sfname,
631 linenr_T start,
632 linenr_T end,
633 exarg_T *eap, // for forced 'ff' and 'fenc', can be
634 // NULL!
635 int append, // append to the file
636 int forceit,
637 int reset_changed,
638 int filtering)
639{
640 int fd;
641 char_u *backup = NULL;
642 int backup_copy = FALSE; // copy the original file?
643 int dobackup;
644 char_u *ffname;
645 char_u *wfname = NULL; // name of file to write to
646 char_u *s;
647 char_u *ptr;
648 char_u c;
649 int len;
650 linenr_T lnum;
651 long nchars;
652 char_u *errmsg = NULL;
653 int errmsg_allocated = FALSE;
654 char_u *errnum = NULL;
655 char_u *buffer;
656 char_u smallbuf[SMALLBUFSIZE];
657 char_u *backup_ext;
658 int bufsize;
659 long perm; // file permissions
660 int retval = OK;
661 int newfile = FALSE; // TRUE if file doesn't exist yet
662 int msg_save = msg_scroll;
663 int overwriting; // TRUE if writing over original
664 int no_eol = FALSE; // no end-of-line written
665 int device = FALSE; // writing to a device
666 stat_T st_old;
667 int prev_got_int = got_int;
668 int checking_conversion;
669 int file_readonly = FALSE; // overwritten file is read-only
Bram Moolenaar473952e2019-09-28 16:30:04 +0200670#if defined(UNIX) // XXX fix me sometime?
671 int made_writable = FALSE; // 'w' bit has been set
672#endif
673 // writing everything
674 int whole = (start == 1 && end == buf->b_ml.ml_line_count);
675 linenr_T old_line_count = buf->b_ml.ml_line_count;
676 int attr;
677 int fileformat;
678 int write_bin;
679 struct bw_info write_info; // info for buf_write_bytes()
680 int converted = FALSE;
681 int notconverted = FALSE;
682 char_u *fenc; // effective 'fileencoding'
683 char_u *fenc_tofree = NULL; // allocated "fenc"
684 int wb_flags = 0;
685#ifdef HAVE_ACL
686 vim_acl_T acl = NULL; // ACL copied from original file to
687 // backup or new file
688#endif
689#ifdef FEAT_PERSISTENT_UNDO
690 int write_undo_file = FALSE;
691 context_sha256_T sha_ctx;
692#endif
693 unsigned int bkc = get_bkc_value(buf);
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100694 pos_T orig_start = buf->b_op_start;
695 pos_T orig_end = buf->b_op_end;
Bram Moolenaar473952e2019-09-28 16:30:04 +0200696
697 if (fname == NULL || *fname == NUL) // safety check
698 return FAIL;
699 if (buf->b_ml.ml_mfp == NULL)
700 {
701 // This can happen during startup when there is a stray "w" in the
702 // vimrc file.
Bram Moolenaar74409f62022-01-01 15:58:22 +0000703 emsg(_(e_empty_buffer));
Bram Moolenaar473952e2019-09-28 16:30:04 +0200704 return FAIL;
705 }
706
707 // Disallow writing from .exrc and .vimrc in current directory for
708 // security reasons.
709 if (check_secure())
710 return FAIL;
711
712 // Avoid a crash for a long name.
713 if (STRLEN(fname) >= MAXPATHL)
714 {
Bram Moolenaar12f3c1b2021-12-05 21:46:34 +0000715 emsg(_(e_name_too_long));
Bram Moolenaar473952e2019-09-28 16:30:04 +0200716 return FAIL;
717 }
718
719 // must init bw_conv_buf and bw_iconv_fd before jumping to "fail"
720 write_info.bw_conv_buf = NULL;
721 write_info.bw_conv_error = FALSE;
722 write_info.bw_conv_error_lnum = 0;
723 write_info.bw_restlen = 0;
724#ifdef USE_ICONV
725 write_info.bw_iconv_fd = (iconv_t)-1;
726#endif
727#ifdef FEAT_CRYPT
728 write_info.bw_buffer = buf;
Christian Brabandtf573c6e2021-06-20 14:02:16 +0200729 write_info.bw_finish = FALSE;
Bram Moolenaar473952e2019-09-28 16:30:04 +0200730#endif
731
732 // After writing a file changedtick changes but we don't want to display
733 // the line.
734 ex_no_reprint = TRUE;
735
736 // If there is no file name yet, use the one for the written file.
737 // BF_NOTEDITED is set to reflect this (in case the write fails).
738 // Don't do this when the write is for a filter command.
739 // Don't do this when appending.
740 // Only do this when 'cpoptions' contains the 'F' flag.
741 if (buf->b_ffname == NULL
742 && reset_changed
743 && whole
744 && buf == curbuf
745#ifdef FEAT_QUICKFIX
746 && !bt_nofilename(buf)
747#endif
748 && !filtering
749 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
750 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
751 {
752 if (set_rw_fname(fname, sfname) == FAIL)
753 return FAIL;
754 buf = curbuf; // just in case autocmds made "buf" invalid
755 }
756
757 if (sfname == NULL)
758 sfname = fname;
759 // For Unix: Use the short file name whenever possible.
760 // Avoids problems with networks and when directory names are changed.
761 // Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
762 // another directory, which we don't detect
763 ffname = fname; // remember full fname
764#ifdef UNIX
765 fname = sfname;
766#endif
767
768 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
769 overwriting = TRUE;
770 else
771 overwriting = FALSE;
772
773 if (exiting)
774 settmode(TMODE_COOK); // when exiting allow typeahead now
775
776 ++no_wait_return; // don't wait for return yet
777
778 // Set '[ and '] marks to the lines to be written.
779 buf->b_op_start.lnum = start;
780 buf->b_op_start.col = 0;
781 buf->b_op_end.lnum = end;
782 buf->b_op_end.col = 0;
783
784 {
785 aco_save_T aco;
786 int buf_ffname = FALSE;
787 int buf_sfname = FALSE;
788 int buf_fname_f = FALSE;
789 int buf_fname_s = FALSE;
790 int did_cmd = FALSE;
791 int nofile_err = FALSE;
792 int empty_memline = (buf->b_ml.ml_mfp == NULL);
793 bufref_T bufref;
794
795 // Apply PRE autocommands.
796 // Set curbuf to the buffer to be written.
797 // Careful: The autocommands may call buf_write() recursively!
798 if (ffname == buf->b_ffname)
799 buf_ffname = TRUE;
800 if (sfname == buf->b_sfname)
801 buf_sfname = TRUE;
802 if (fname == buf->b_ffname)
803 buf_fname_f = TRUE;
804 if (fname == buf->b_sfname)
805 buf_fname_s = TRUE;
806
807 // set curwin/curbuf to buf and save a few things
808 aucmd_prepbuf(&aco, buf);
809 set_bufref(&bufref, buf);
810
811 if (append)
812 {
813 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
814 sfname, sfname, FALSE, curbuf, eap)))
815 {
816#ifdef FEAT_QUICKFIX
817 if (overwriting && bt_nofilename(curbuf))
818 nofile_err = TRUE;
819 else
820#endif
821 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
822 sfname, sfname, FALSE, curbuf, eap);
823 }
824 }
825 else if (filtering)
826 {
827 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
828 NULL, sfname, FALSE, curbuf, eap);
829 }
830 else if (reset_changed && whole)
831 {
832 int was_changed = curbufIsChanged();
833
834 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
835 sfname, sfname, FALSE, curbuf, eap);
836 if (did_cmd)
837 {
838 if (was_changed && !curbufIsChanged())
839 {
840 // Written everything correctly and BufWriteCmd has reset
841 // 'modified': Correct the undo information so that an
842 // undo now sets 'modified'.
843 u_unchanged(curbuf);
844 u_update_save_nr(curbuf);
845 }
846 }
847 else
848 {
849#ifdef FEAT_QUICKFIX
850 if (overwriting && bt_nofilename(curbuf))
851 nofile_err = TRUE;
852 else
853#endif
854 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
855 sfname, sfname, FALSE, curbuf, eap);
856 }
857 }
858 else
859 {
860 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
861 sfname, sfname, FALSE, curbuf, eap)))
862 {
863#ifdef FEAT_QUICKFIX
864 if (overwriting && bt_nofilename(curbuf))
865 nofile_err = TRUE;
866 else
867#endif
868 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
869 sfname, sfname, FALSE, curbuf, eap);
870 }
871 }
872
873 // restore curwin/curbuf and a few other things
874 aucmd_restbuf(&aco);
875
876 // In three situations we return here and don't write the file:
877 // 1. the autocommands deleted or unloaded the buffer.
878 // 2. The autocommands abort script processing.
879 // 3. If one of the "Cmd" autocommands was executed.
880 if (!bufref_valid(&bufref))
881 buf = NULL;
882 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
883 || did_cmd || nofile_err
884#ifdef FEAT_EVAL
885 || aborting()
886#endif
887 )
888 {
Bram Moolenaare1004402020-10-24 20:49:43 +0200889 if (buf != NULL && (cmdmod.cmod_flags & CMOD_LOCKMARKS))
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100890 {
891 // restore the original '[ and '] positions
892 buf->b_op_start = orig_start;
893 buf->b_op_end = orig_end;
894 }
895
Bram Moolenaar473952e2019-09-28 16:30:04 +0200896 --no_wait_return;
897 msg_scroll = msg_save;
898 if (nofile_err)
Bram Moolenaarf1474d82021-12-31 19:59:55 +0000899 emsg(_(e_no_matching_autocommands_for_acwrite_buffer));
Bram Moolenaar473952e2019-09-28 16:30:04 +0200900
901 if (nofile_err
902#ifdef FEAT_EVAL
903 || aborting()
904#endif
905 )
906 // An aborting error, interrupt or exception in the
907 // autocommands.
908 return FAIL;
909 if (did_cmd)
910 {
911 if (buf == NULL)
912 // The buffer was deleted. We assume it was written
913 // (can't retry anyway).
914 return OK;
915 if (overwriting)
916 {
917 // Assume the buffer was written, update the timestamp.
918 ml_timestamp(buf);
919 if (append)
920 buf->b_flags &= ~BF_NEW;
921 else
922 buf->b_flags &= ~BF_WRITE_MASK;
923 }
924 if (reset_changed && buf->b_changed && !append
925 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
926 // Buffer still changed, the autocommands didn't work
927 // properly.
928 return FAIL;
929 return OK;
930 }
931#ifdef FEAT_EVAL
932 if (!aborting())
933#endif
Bram Moolenaar6d057012021-12-31 18:49:43 +0000934 emsg(_(e_autocommands_deleted_or_unloaded_buffer_to_be_written));
Bram Moolenaar473952e2019-09-28 16:30:04 +0200935 return FAIL;
936 }
937
938 // The autocommands may have changed the number of lines in the file.
939 // When writing the whole file, adjust the end.
940 // When writing part of the file, assume that the autocommands only
941 // changed the number of lines that are to be written (tricky!).
942 if (buf->b_ml.ml_line_count != old_line_count)
943 {
944 if (whole) // write all
945 end = buf->b_ml.ml_line_count;
946 else if (buf->b_ml.ml_line_count > old_line_count) // more lines
947 end += buf->b_ml.ml_line_count - old_line_count;
948 else // less lines
949 {
950 end -= old_line_count - buf->b_ml.ml_line_count;
951 if (end < start)
952 {
953 --no_wait_return;
954 msg_scroll = msg_save;
Bram Moolenaar6d057012021-12-31 18:49:43 +0000955 emsg(_(e_autocommands_changed_number_of_lines_in_unexpected_way));
Bram Moolenaar473952e2019-09-28 16:30:04 +0200956 return FAIL;
957 }
958 }
959 }
960
961 // The autocommands may have changed the name of the buffer, which may
962 // be kept in fname, ffname and sfname.
963 if (buf_ffname)
964 ffname = buf->b_ffname;
965 if (buf_sfname)
966 sfname = buf->b_sfname;
967 if (buf_fname_f)
968 fname = buf->b_ffname;
969 if (buf_fname_s)
970 fname = buf->b_sfname;
971 }
972
Bram Moolenaare1004402020-10-24 20:49:43 +0200973 if (cmdmod.cmod_flags & CMOD_LOCKMARKS)
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100974 {
975 // restore the original '[ and '] positions
976 buf->b_op_start = orig_start;
977 buf->b_op_end = orig_end;
978 }
979
Bram Moolenaar473952e2019-09-28 16:30:04 +0200980#ifdef FEAT_NETBEANS_INTG
981 if (netbeans_active() && isNetbeansBuffer(buf))
982 {
983 if (whole)
984 {
985 // b_changed can be 0 after an undo, but we still need to write
986 // the buffer to NetBeans.
987 if (buf->b_changed || isNetbeansModified(buf))
988 {
989 --no_wait_return; // may wait for return now
990 msg_scroll = msg_save;
991 netbeans_save_buffer(buf); // no error checking...
992 return retval;
993 }
994 else
995 {
996 errnum = (char_u *)"E656: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +0000997 errmsg = (char_u *)_(e_netbeans_disallows_writes_of_unmodified_buffers);
Bram Moolenaar473952e2019-09-28 16:30:04 +0200998 buffer = NULL;
999 goto fail;
1000 }
1001 }
1002 else
1003 {
1004 errnum = (char_u *)"E657: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001005 errmsg = (char_u *)_(e_partial_writes_disallowed_for_netbeans_buffers);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001006 buffer = NULL;
1007 goto fail;
1008 }
1009 }
1010#endif
1011
1012 if (shortmess(SHM_OVER) && !exiting)
1013 msg_scroll = FALSE; // overwrite previous file message
1014 else
1015 msg_scroll = TRUE; // don't overwrite previous file message
1016 if (!filtering)
1017 filemess(buf,
1018#ifndef UNIX
1019 sfname,
1020#else
1021 fname,
1022#endif
1023 (char_u *)"", 0); // show that we are busy
1024 msg_scroll = FALSE; // always overwrite the file message now
1025
1026 buffer = alloc(WRITEBUFSIZE);
1027 if (buffer == NULL) // can't allocate big buffer, use small
1028 // one (to be able to write when out of
1029 // memory)
1030 {
1031 buffer = smallbuf;
1032 bufsize = SMALLBUFSIZE;
1033 }
1034 else
1035 bufsize = WRITEBUFSIZE;
1036
1037 // Get information about original file (if there is one).
1038#if defined(UNIX)
1039 st_old.st_dev = 0;
1040 st_old.st_ino = 0;
1041 perm = -1;
1042 if (mch_stat((char *)fname, &st_old) < 0)
1043 newfile = TRUE;
1044 else
1045 {
1046 perm = st_old.st_mode;
1047 if (!S_ISREG(st_old.st_mode)) // not a file
1048 {
1049 if (S_ISDIR(st_old.st_mode))
1050 {
1051 errnum = (char_u *)"E502: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001052 errmsg = (char_u *)_(e_is_a_directory);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001053 goto fail;
1054 }
1055 if (mch_nodetype(fname) != NODE_WRITABLE)
1056 {
1057 errnum = (char_u *)"E503: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001058 errmsg = (char_u *)_(e_is_not_file_or_writable_device);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001059 goto fail;
1060 }
1061 // It's a device of some kind (or a fifo) which we can write to
1062 // but for which we can't make a backup.
1063 device = TRUE;
1064 newfile = TRUE;
1065 perm = -1;
1066 }
1067 }
1068#else // !UNIX
1069 // Check for a writable device name.
1070 c = mch_nodetype(fname);
1071 if (c == NODE_OTHER)
1072 {
1073 errnum = (char_u *)"E503: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001074 errmsg = (char_u *)_(e_is_not_file_or_writable_device);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001075 goto fail;
1076 }
1077 if (c == NODE_WRITABLE)
1078 {
1079# if defined(MSWIN)
1080 // MS-Windows allows opening a device, but we will probably get stuck
1081 // trying to write to it.
1082 if (!p_odev)
1083 {
1084 errnum = (char_u *)"E796: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001085 errmsg = (char_u *)_(e_writing_to_device_disabled_with_opendevice_option);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001086 goto fail;
1087 }
1088# endif
1089 device = TRUE;
1090 newfile = TRUE;
1091 perm = -1;
1092 }
1093 else
1094 {
1095 perm = mch_getperm(fname);
1096 if (perm < 0)
1097 newfile = TRUE;
1098 else if (mch_isdir(fname))
1099 {
1100 errnum = (char_u *)"E502: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001101 errmsg = (char_u *)_(e_is_a_directory);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001102 goto fail;
1103 }
1104 if (overwriting)
1105 (void)mch_stat((char *)fname, &st_old);
1106 }
1107#endif // !UNIX
1108
1109 if (!device && !newfile)
1110 {
1111 // Check if the file is really writable (when renaming the file to
1112 // make a backup we won't discover it later).
1113 file_readonly = check_file_readonly(fname, (int)perm);
1114
1115 if (!forceit && file_readonly)
1116 {
1117 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
1118 {
1119 errnum = (char_u *)"E504: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001120 errmsg = (char_u *)_(e_is_read_only_cannot_override_W_in_cpoptions);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001121 }
1122 else
1123 {
1124 errnum = (char_u *)"E505: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001125 errmsg = (char_u *)_(e_is_read_only_add_bang_to_override);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001126 }
1127 goto fail;
1128 }
1129
1130 // Check if the timestamp hasn't changed since reading the file.
1131 if (overwriting)
1132 {
1133 retval = check_mtime(buf, &st_old);
1134 if (retval == FAIL)
1135 goto fail;
1136 }
1137 }
1138
1139#ifdef HAVE_ACL
1140 // For systems that support ACL: get the ACL from the original file.
1141 if (!newfile)
1142 acl = mch_get_acl(fname);
1143#endif
1144
1145 // If 'backupskip' is not empty, don't make a backup for some files.
1146 dobackup = (p_wb || p_bk || *p_pm != NUL);
1147#ifdef FEAT_WILDIGN
1148 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
1149 dobackup = FALSE;
1150#endif
1151
1152 // Save the value of got_int and reset it. We don't want a previous
1153 // interruption cancel writing, only hitting CTRL-C while writing should
1154 // abort it.
1155 prev_got_int = got_int;
1156 got_int = FALSE;
1157
1158 // Mark the buffer as 'being saved' to prevent changed buffer warnings
1159 buf->b_saving = TRUE;
1160
1161 // If we are not appending or filtering, the file exists, and the
1162 // 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
1163 // When 'patchmode' is set also make a backup when appending.
1164 //
1165 // Do not make any backup, if 'writebackup' and 'backup' are both switched
1166 // off. This helps when editing large files on almost-full disks.
1167 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
1168 {
1169#if defined(UNIX) || defined(MSWIN)
1170 stat_T st;
1171#endif
1172
1173 if ((bkc & BKC_YES) || append) // "yes"
1174 backup_copy = TRUE;
1175#if defined(UNIX) || defined(MSWIN)
1176 else if ((bkc & BKC_AUTO)) // "auto"
1177 {
1178 int i;
1179
1180# ifdef UNIX
1181 // Don't rename the file when:
1182 // - it's a hard link
1183 // - it's a symbolic link
1184 // - we don't have write permission in the directory
1185 // - we can't set the owner/group of the new file
1186 if (st_old.st_nlink > 1
1187 || mch_lstat((char *)fname, &st) < 0
1188 || st.st_dev != st_old.st_dev
1189 || st.st_ino != st_old.st_ino
1190# ifndef HAVE_FCHOWN
1191 || st.st_uid != st_old.st_uid
1192 || st.st_gid != st_old.st_gid
1193# endif
1194 )
1195 backup_copy = TRUE;
1196 else
1197# else
1198# ifdef MSWIN
1199 // On NTFS file systems hard links are possible.
1200 if (mch_is_linked(fname))
1201 backup_copy = TRUE;
1202 else
1203# endif
1204# endif
1205 {
1206 // Check if we can create a file and set the owner/group to
1207 // the ones from the original file.
1208 // First find a file name that doesn't exist yet (use some
1209 // arbitrary numbers).
1210 STRCPY(IObuff, fname);
K.Takatadbdcc792022-07-31 11:50:42 +01001211 fd = -1;
Bram Moolenaar473952e2019-09-28 16:30:04 +02001212 for (i = 4913; ; i += 123)
1213 {
1214 sprintf((char *)gettail(IObuff), "%d", i);
1215 if (mch_lstat((char *)IObuff, &st) < 0)
K.Takatadbdcc792022-07-31 11:50:42 +01001216 {
1217 fd = mch_open((char *)IObuff,
Bram Moolenaar473952e2019-09-28 16:30:04 +02001218 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
K.Takatadbdcc792022-07-31 11:50:42 +01001219 if (fd < 0 && errno == EEXIST)
1220 // If the same file name is created by another
1221 // process between lstat() and open(), find another
1222 // name.
1223 continue;
1224 break;
1225 }
1226 }
Bram Moolenaar473952e2019-09-28 16:30:04 +02001227 if (fd < 0) // can't write in directory
1228 backup_copy = TRUE;
1229 else
1230 {
1231# ifdef UNIX
1232# ifdef HAVE_FCHOWN
1233 vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
1234# endif
1235 if (mch_stat((char *)IObuff, &st) < 0
1236 || st.st_uid != st_old.st_uid
1237 || st.st_gid != st_old.st_gid
1238 || (long)st.st_mode != perm)
1239 backup_copy = TRUE;
1240# endif
1241 // Close the file before removing it, on MS-Windows we
1242 // can't delete an open file.
1243 close(fd);
1244 mch_remove(IObuff);
1245# ifdef MSWIN
1246 // MS-Windows may trigger a virus scanner to open the
1247 // file, we can't delete it then. Keep trying for half a
1248 // second.
1249 {
1250 int try;
1251
1252 for (try = 0; try < 10; ++try)
1253 {
1254 if (mch_lstat((char *)IObuff, &st) < 0)
1255 break;
1256 ui_delay(50L, TRUE); // wait 50 msec
1257 mch_remove(IObuff);
1258 }
1259 }
1260# endif
1261 }
1262 }
1263 }
1264
1265 // Break symlinks and/or hardlinks if we've been asked to.
1266 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
1267 {
1268# ifdef UNIX
1269 int lstat_res;
1270
1271 lstat_res = mch_lstat((char *)fname, &st);
1272
1273 // Symlinks.
1274 if ((bkc & BKC_BREAKSYMLINK)
1275 && lstat_res == 0
1276 && st.st_ino != st_old.st_ino)
1277 backup_copy = FALSE;
1278
1279 // Hardlinks.
1280 if ((bkc & BKC_BREAKHARDLINK)
1281 && st_old.st_nlink > 1
1282 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
1283 backup_copy = FALSE;
1284# else
1285# if defined(MSWIN)
1286 // Symlinks.
1287 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
1288 backup_copy = FALSE;
1289
1290 // Hardlinks.
1291 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
1292 backup_copy = FALSE;
1293# endif
1294# endif
1295 }
1296
1297#endif
1298
1299 // make sure we have a valid backup extension to use
1300 if (*p_bex == NUL)
1301 backup_ext = (char_u *)".bak";
1302 else
1303 backup_ext = p_bex;
1304
1305 if (backup_copy
1306 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
1307 {
1308 int bfd;
1309 char_u *copybuf, *wp;
1310 int some_error = FALSE;
1311 stat_T st_new;
1312 char_u *dirp;
1313 char_u *rootname;
1314#if defined(UNIX) || defined(MSWIN)
1315 char_u *p;
1316#endif
1317#if defined(UNIX)
1318 int did_set_shortname;
1319 mode_t umask_save;
1320#endif
1321
1322 copybuf = alloc(WRITEBUFSIZE + 1);
1323 if (copybuf == NULL)
1324 {
1325 some_error = TRUE; // out of memory
1326 goto nobackup;
1327 }
1328
1329 // Try to make the backup in each directory in the 'bdir' option.
1330 //
1331 // Unix semantics has it, that we may have a writable file,
1332 // that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
1333 // - the directory is not writable,
1334 // - the file may be a symbolic link,
1335 // - the file may belong to another user/group, etc.
1336 //
1337 // For these reasons, the existing writable file must be truncated
1338 // and reused. Creation of a backup COPY will be attempted.
1339 dirp = p_bdir;
1340 while (*dirp)
1341 {
1342#ifdef UNIX
1343 st_new.st_ino = 0;
1344 st_new.st_dev = 0;
1345 st_new.st_gid = 0;
1346#endif
1347
1348 // Isolate one directory name, using an entry in 'bdir'.
1349 (void)copy_option_part(&dirp, copybuf, WRITEBUFSIZE, ",");
1350
1351#if defined(UNIX) || defined(MSWIN)
1352 p = copybuf + STRLEN(copybuf);
1353 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
1354 // Ends with '//', use full path
1355 if ((p = make_percent_swname(copybuf, fname)) != NULL)
1356 {
1357 backup = modname(p, backup_ext, FALSE);
1358 vim_free(p);
1359 }
1360#endif
1361 rootname = get_file_in_dir(fname, copybuf);
1362 if (rootname == NULL)
1363 {
1364 some_error = TRUE; // out of memory
1365 goto nobackup;
1366 }
1367
1368#if defined(UNIX)
1369 did_set_shortname = FALSE;
1370#endif
1371
1372 // May try twice if 'shortname' not set.
1373 for (;;)
1374 {
1375 // Make the backup file name.
1376 if (backup == NULL)
1377 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
1378 rootname, backup_ext, FALSE);
1379 if (backup == NULL)
1380 {
1381 vim_free(rootname);
1382 some_error = TRUE; // out of memory
1383 goto nobackup;
1384 }
1385
1386 // Check if backup file already exists.
1387 if (mch_stat((char *)backup, &st_new) >= 0)
1388 {
1389#ifdef UNIX
1390 // Check if backup file is same as original file.
1391 // May happen when modname() gave the same file back.
1392 // E.g. silly link, or file name-length reached.
1393 // If we don't check here, we either ruin the file
1394 // when copying or erase it after writing. jw.
1395 if (st_new.st_dev == st_old.st_dev
1396 && st_new.st_ino == st_old.st_ino)
1397 {
1398 VIM_CLEAR(backup); // no backup file to delete
1399 // may try again with 'shortname' set
1400 if (!(buf->b_shortname || buf->b_p_sn))
1401 {
1402 buf->b_shortname = TRUE;
1403 did_set_shortname = TRUE;
1404 continue;
1405 }
1406 // setting shortname didn't help
1407 if (did_set_shortname)
1408 buf->b_shortname = FALSE;
1409 break;
1410 }
1411#endif
1412
1413 // If we are not going to keep the backup file, don't
1414 // delete an existing one, try to use another name.
1415 // Change one character, just before the extension.
1416 if (!p_bk)
1417 {
1418 wp = backup + STRLEN(backup) - 1
1419 - STRLEN(backup_ext);
1420 if (wp < backup) // empty file name ???
1421 wp = backup;
1422 *wp = 'z';
1423 while (*wp > 'a'
1424 && mch_stat((char *)backup, &st_new) >= 0)
1425 --*wp;
1426 // They all exist??? Must be something wrong.
1427 if (*wp == 'a')
1428 VIM_CLEAR(backup);
1429 }
1430 }
1431 break;
1432 }
1433 vim_free(rootname);
1434
1435 // Try to create the backup file
1436 if (backup != NULL)
1437 {
1438 // remove old backup, if present
1439 mch_remove(backup);
1440 // Open with O_EXCL to avoid the file being created while
1441 // we were sleeping (symlink hacker attack?). Reset umask
1442 // if possible to avoid mch_setperm() below.
1443#ifdef UNIX
1444 umask_save = umask(0);
1445#endif
1446 bfd = mch_open((char *)backup,
1447 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
1448 perm & 0777);
1449#ifdef UNIX
1450 (void)umask(umask_save);
1451#endif
1452 if (bfd < 0)
1453 VIM_CLEAR(backup);
1454 else
1455 {
1456 // Set file protection same as original file, but
1457 // strip s-bit. Only needed if umask() wasn't used
1458 // above.
1459#ifndef UNIX
1460 (void)mch_setperm(backup, perm & 0777);
1461#else
1462 // Try to set the group of the backup same as the
1463 // original file. If this fails, set the protection
1464 // bits for the group same as the protection bits for
1465 // others.
1466 if (st_new.st_gid != st_old.st_gid
1467# ifdef HAVE_FCHOWN // sequent-ptx lacks fchown()
1468 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
1469# endif
1470 )
1471 mch_setperm(backup,
1472 (perm & 0707) | ((perm & 07) << 3));
1473# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1474 mch_copy_sec(fname, backup);
1475# endif
1476#endif
1477
1478 // copy the file.
1479 write_info.bw_fd = bfd;
1480 write_info.bw_buf = copybuf;
1481 write_info.bw_flags = FIO_NOCONVERT;
1482 while ((write_info.bw_len = read_eintr(fd, copybuf,
1483 WRITEBUFSIZE)) > 0)
1484 {
1485 if (buf_write_bytes(&write_info) == FAIL)
1486 {
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001487 errmsg = (char_u *)_(e_canot_write_to_backup_file_add_bang_to_override);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001488 break;
1489 }
1490 ui_breakcheck();
1491 if (got_int)
1492 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00001493 errmsg = (char_u *)_(e_interrupted);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001494 break;
1495 }
1496 }
1497
1498 if (close(bfd) < 0 && errmsg == NULL)
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001499 errmsg = (char_u *)_(e_close_error_for_backup_file_add_bang_to_write_anyway);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001500 if (write_info.bw_len < 0)
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001501 errmsg = (char_u *)_(e_cant_read_file_for_backup_add_bang_to_write_anyway);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001502#ifdef UNIX
1503 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
1504#endif
1505#ifdef HAVE_ACL
1506 mch_set_acl(backup, acl);
1507#endif
1508#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1509 mch_copy_sec(fname, backup);
1510#endif
Bram Moolenaar7781ebe2021-02-01 20:35:01 +01001511#ifdef MSWIN
1512 (void)mch_copy_file_attribute(fname, backup);
1513#endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02001514 break;
1515 }
1516 }
1517 }
1518 nobackup:
1519 close(fd); // ignore errors for closing read file
1520 vim_free(copybuf);
1521
1522 if (backup == NULL && errmsg == NULL)
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001523 errmsg = (char_u *)_(e_cannot_create_backup_file_add_bang_to_write_anyway);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001524 // ignore errors when forceit is TRUE
1525 if ((some_error || errmsg != NULL) && !forceit)
1526 {
1527 retval = FAIL;
1528 goto fail;
1529 }
1530 errmsg = NULL;
1531 }
1532 else
1533 {
1534 char_u *dirp;
1535 char_u *p;
1536 char_u *rootname;
1537
1538 // Make a backup by renaming the original file.
1539
1540 // If 'cpoptions' includes the "W" flag, we don't want to
1541 // overwrite a read-only file. But rename may be possible
1542 // anyway, thus we need an extra check here.
1543 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
1544 {
1545 errnum = (char_u *)"E504: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001546 errmsg = (char_u *)_(e_is_read_only_cannot_override_W_in_cpoptions);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001547 goto fail;
1548 }
1549
1550 // Form the backup file name - change path/fo.o.h to
1551 // path/fo.o.h.bak Try all directories in 'backupdir', first one
1552 // that works is used.
1553 dirp = p_bdir;
1554 while (*dirp)
1555 {
1556 // Isolate one directory name and make the backup file name.
1557 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
1558
1559#if defined(UNIX) || defined(MSWIN)
1560 p = IObuff + STRLEN(IObuff);
1561 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
1562 // path ends with '//', use full path
1563 if ((p = make_percent_swname(IObuff, fname)) != NULL)
1564 {
1565 backup = modname(p, backup_ext, FALSE);
1566 vim_free(p);
1567 }
1568#endif
1569 if (backup == NULL)
1570 {
1571 rootname = get_file_in_dir(fname, IObuff);
1572 if (rootname == NULL)
1573 backup = NULL;
1574 else
1575 {
1576 backup = buf_modname(
1577 (buf->b_p_sn || buf->b_shortname),
1578 rootname, backup_ext, FALSE);
1579 vim_free(rootname);
1580 }
1581 }
1582
1583 if (backup != NULL)
1584 {
1585 // If we are not going to keep the backup file, don't
1586 // delete an existing one, try to use another name.
1587 // Change one character, just before the extension.
1588 if (!p_bk && mch_getperm(backup) >= 0)
1589 {
1590 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
1591 if (p < backup) // empty file name ???
1592 p = backup;
1593 *p = 'z';
1594 while (*p > 'a' && mch_getperm(backup) >= 0)
1595 --*p;
1596 // They all exist??? Must be something wrong!
1597 if (*p == 'a')
1598 VIM_CLEAR(backup);
1599 }
1600 }
1601 if (backup != NULL)
1602 {
1603 // Delete any existing backup and move the current version
1604 // to the backup. For safety, we don't remove the backup
1605 // until the write has finished successfully. And if the
1606 // 'backup' option is set, leave it around.
1607
1608 // If the renaming of the original file to the backup file
1609 // works, quit here.
1610 if (vim_rename(fname, backup) == 0)
1611 break;
1612
1613 VIM_CLEAR(backup); // don't do the rename below
1614 }
1615 }
1616 if (backup == NULL && !forceit)
1617 {
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001618 errmsg = (char_u *)_(e_cant_make_backup_file_add_bang_to_write_anyway);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001619 goto fail;
1620 }
1621 }
1622 }
1623
1624#if defined(UNIX)
1625 // When using ":w!" and the file was read-only: make it writable
1626 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
1627 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
1628 {
1629 perm |= 0200;
1630 (void)mch_setperm(fname, perm);
1631 made_writable = TRUE;
1632 }
1633#endif
1634
1635 // When using ":w!" and writing to the current file, 'readonly' makes no
1636 // sense, reset it, unless 'Z' appears in 'cpoptions'.
1637 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
1638 {
1639 buf->b_p_ro = FALSE;
Bram Moolenaar473952e2019-09-28 16:30:04 +02001640 need_maketitle = TRUE; // set window title later
Bram Moolenaar473952e2019-09-28 16:30:04 +02001641 status_redraw_all(); // redraw status lines later
1642 }
1643
1644 if (end > buf->b_ml.ml_line_count)
1645 end = buf->b_ml.ml_line_count;
1646 if (buf->b_ml.ml_flags & ML_EMPTY)
1647 start = end + 1;
1648
1649 // If the original file is being overwritten, there is a small chance that
1650 // we crash in the middle of writing. Therefore the file is preserved now.
1651 // This makes all block numbers positive so that recovery does not need
1652 // the original file.
1653 // Don't do this if there is a backup file and we are exiting.
1654 if (reset_changed && !newfile && overwriting
1655 && !(exiting && backup != NULL))
1656 {
1657 ml_preserve(buf, FALSE);
1658 if (got_int)
1659 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00001660 errmsg = (char_u *)_(e_interrupted);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001661 goto restore_backup;
1662 }
1663 }
1664
1665#ifdef VMS
1666 vms_remove_version(fname); // remove version
1667#endif
1668 // Default: write the file directly. May write to a temp file for
1669 // multi-byte conversion.
1670 wfname = fname;
1671
1672 // Check for forced 'fileencoding' from "++opt=val" argument.
1673 if (eap != NULL && eap->force_enc != 0)
1674 {
1675 fenc = eap->cmd + eap->force_enc;
1676 fenc = enc_canonize(fenc);
1677 fenc_tofree = fenc;
1678 }
1679 else
1680 fenc = buf->b_p_fenc;
1681
1682 // Check if the file needs to be converted.
1683 converted = need_conversion(fenc);
1684
1685 // Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
1686 // Latin1 to Unicode conversion. This is handled in buf_write_bytes().
1687 // Prepare the flags for it and allocate bw_conv_buf when needed.
1688 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
1689 {
1690 wb_flags = get_fio_flags(fenc);
1691 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
1692 {
1693 // Need to allocate a buffer to translate into.
1694 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
1695 write_info.bw_conv_buflen = bufsize * 2;
1696 else // FIO_UCS4
1697 write_info.bw_conv_buflen = bufsize * 4;
1698 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1699 if (write_info.bw_conv_buf == NULL)
1700 end = 0;
1701 }
1702 }
1703
1704#ifdef MSWIN
1705 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
1706 {
1707 // Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4:
1708 write_info.bw_conv_buflen = bufsize * 4;
1709 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1710 if (write_info.bw_conv_buf == NULL)
1711 end = 0;
1712 }
1713#endif
1714
1715#ifdef MACOS_CONVERT
1716 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
1717 {
1718 write_info.bw_conv_buflen = bufsize * 3;
1719 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1720 if (write_info.bw_conv_buf == NULL)
1721 end = 0;
1722 }
1723#endif
1724
1725#if defined(FEAT_EVAL) || defined(USE_ICONV)
1726 if (converted && wb_flags == 0)
1727 {
1728# ifdef USE_ICONV
1729 // Use iconv() conversion when conversion is needed and it's not done
1730 // internally.
1731 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
1732 enc_utf8 ? (char_u *)"utf-8" : p_enc);
1733 if (write_info.bw_iconv_fd != (iconv_t)-1)
1734 {
1735 // We're going to use iconv(), allocate a buffer to convert in.
1736 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
1737 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1738 if (write_info.bw_conv_buf == NULL)
1739 end = 0;
1740 write_info.bw_first = TRUE;
1741 }
1742# ifdef FEAT_EVAL
1743 else
1744# endif
1745# endif
1746
1747# ifdef FEAT_EVAL
1748 // When the file needs to be converted with 'charconvert' after
1749 // writing, write to a temp file instead and let the conversion
1750 // overwrite the original file.
1751 if (*p_ccv != NUL)
1752 {
1753 wfname = vim_tempname('w', FALSE);
1754 if (wfname == NULL) // Can't write without a tempfile!
1755 {
Bram Moolenaar6d057012021-12-31 18:49:43 +00001756 errmsg = (char_u *)_(e_cant_find_temp_file_for_writing);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001757 goto restore_backup;
1758 }
1759 }
1760# endif
1761 }
1762#endif
1763 if (converted && wb_flags == 0
1764#ifdef USE_ICONV
1765 && write_info.bw_iconv_fd == (iconv_t)-1
1766# endif
1767# ifdef FEAT_EVAL
1768 && wfname == fname
1769# endif
1770 )
1771 {
1772 if (!forceit)
1773 {
Bram Moolenaar6d057012021-12-31 18:49:43 +00001774 errmsg = (char_u *)_(e_cannot_convert_add_bang_to_write_without_conversion);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001775 goto restore_backup;
1776 }
1777 notconverted = TRUE;
1778 }
1779
1780 // If conversion is taking place, we may first pretend to write and check
1781 // for conversion errors. Then loop again to write for real.
1782 // When not doing conversion this writes for real right away.
1783 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
1784 {
1785 // There is no need to check conversion when:
1786 // - there is no conversion
1787 // - we make a backup file, that can be restored in case of conversion
1788 // failure.
1789 if (!converted || dobackup)
1790 checking_conversion = FALSE;
1791
1792 if (checking_conversion)
1793 {
1794 // Make sure we don't write anything.
1795 fd = -1;
1796 write_info.bw_fd = fd;
1797 }
1798 else
1799 {
1800#ifdef HAVE_FTRUNCATE
1801# define TRUNC_ON_OPEN 0
1802#else
1803# define TRUNC_ON_OPEN O_TRUNC
1804#endif
1805 // Open the file "wfname" for writing.
1806 // We may try to open the file twice: If we can't write to the file
1807 // and forceit is TRUE we delete the existing file and try to
1808 // create a new one. If this still fails we may have lost the
1809 // original file! (this may happen when the user reached his
1810 // quotum for number of files).
1811 // Appending will fail if the file does not exist and forceit is
1812 // FALSE.
1813 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
1814 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
1815 : (O_CREAT | TRUNC_ON_OPEN))
1816 , perm < 0 ? 0666 : (perm & 0777))) < 0)
1817 {
1818 // A forced write will try to create a new file if the old one
1819 // is still readonly. This may also happen when the directory
1820 // is read-only. In that case the mch_remove() will fail.
1821 if (errmsg == NULL)
1822 {
1823#ifdef UNIX
1824 stat_T st;
1825
1826 // Don't delete the file when it's a hard or symbolic link.
1827 if ((!newfile && st_old.st_nlink > 1)
1828 || (mch_lstat((char *)fname, &st) == 0
1829 && (st.st_dev != st_old.st_dev
1830 || st.st_ino != st_old.st_ino)))
Bram Moolenaar1a992222021-12-31 17:25:48 +00001831 errmsg =
1832 (char_u *)_(e_cant_open_linked_file_for_writing);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001833 else
1834#endif
1835 {
Bram Moolenaar6d057012021-12-31 18:49:43 +00001836 errmsg = (char_u *)_(e_cant_open_file_for_writing);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001837 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
1838 && perm >= 0)
1839 {
1840#ifdef UNIX
1841 // we write to the file, thus it should be marked
1842 // writable after all
1843 if (!(perm & 0200))
1844 made_writable = TRUE;
1845 perm |= 0200;
1846 if (st_old.st_uid != getuid()
1847 || st_old.st_gid != getgid())
1848 perm &= 0777;
1849#endif
1850 if (!append) // don't remove when appending
1851 mch_remove(wfname);
1852 continue;
1853 }
1854 }
1855 }
1856
1857restore_backup:
1858 {
1859 stat_T st;
1860
1861 // If we failed to open the file, we don't need a backup.
1862 // Throw it away. If we moved or removed the original file
1863 // try to put the backup in its place.
1864 if (backup != NULL && wfname == fname)
1865 {
1866 if (backup_copy)
1867 {
1868 // There is a small chance that we removed the
1869 // original, try to move the copy in its place.
1870 // This may not work if the vim_rename() fails.
1871 // In that case we leave the copy around.
1872
1873 // If file does not exist, put the copy in its
1874 // place
1875 if (mch_stat((char *)fname, &st) < 0)
1876 vim_rename(backup, fname);
1877 // if original file does exist throw away the copy
1878 if (mch_stat((char *)fname, &st) >= 0)
1879 mch_remove(backup);
1880 }
1881 else
1882 {
1883 // try to put the original file back
1884 vim_rename(backup, fname);
1885 }
1886 }
1887
1888 // if original file no longer exists give an extra warning
1889 if (!newfile && mch_stat((char *)fname, &st) < 0)
1890 end = 0;
1891 }
1892
1893 if (wfname != fname)
1894 vim_free(wfname);
1895 goto fail;
1896 }
1897 write_info.bw_fd = fd;
1898
1899#if defined(UNIX)
1900 {
1901 stat_T st;
1902
1903 // Double check we are writing the intended file before making
1904 // any changes.
1905 if (overwriting
1906 && (!dobackup || backup_copy)
1907 && fname == wfname
1908 && perm >= 0
1909 && mch_fstat(fd, &st) == 0
1910 && st.st_ino != st_old.st_ino)
1911 {
1912 close(fd);
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001913 errmsg = (char_u *)_(e_file_changed_while_writing);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001914 goto fail;
1915 }
1916 }
1917#endif
1918#ifdef HAVE_FTRUNCATE
1919 if (!append)
1920 vim_ignored = ftruncate(fd, (off_t)0);
1921#endif
1922
1923#if defined(MSWIN)
1924 if (backup != NULL && overwriting && !append)
Bram Moolenaar7781ebe2021-02-01 20:35:01 +01001925 (void)mch_copy_file_attribute(backup, wfname);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001926
1927 if (!overwriting && !append)
1928 {
1929 if (buf->b_ffname != NULL)
1930 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
1931 // Should copy resource fork
1932 }
1933#endif
1934
1935#ifdef FEAT_CRYPT
1936 if (*buf->b_p_key != NUL && !filtering)
1937 {
1938 char_u *header;
1939 int header_len;
1940
1941 buf->b_cryptstate = crypt_create_for_writing(
1942 crypt_get_method_nr(buf),
1943 buf->b_p_key, &header, &header_len);
1944 if (buf->b_cryptstate == NULL || header == NULL)
1945 end = 0;
1946 else
1947 {
1948 // Write magic number, so that Vim knows how this file is
1949 // encrypted when reading it back.
1950 write_info.bw_buf = header;
1951 write_info.bw_len = header_len;
1952 write_info.bw_flags = FIO_NOCONVERT;
1953 if (buf_write_bytes(&write_info) == FAIL)
1954 end = 0;
1955 wb_flags |= FIO_ENCRYPTED;
1956 vim_free(header);
1957 }
1958 }
1959#endif
1960 }
1961 errmsg = NULL;
1962
1963 write_info.bw_buf = buffer;
1964 nchars = 0;
1965
1966 // use "++bin", "++nobin" or 'binary'
1967 if (eap != NULL && eap->force_bin != 0)
1968 write_bin = (eap->force_bin == FORCE_BIN);
1969 else
1970 write_bin = buf->b_p_bin;
1971
1972 // The BOM is written just after the encryption magic number.
1973 // Skip it when appending and the file already existed, the BOM only
1974 // makes sense at the start of the file.
1975 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
1976 {
1977 write_info.bw_len = make_bom(buffer, fenc);
1978 if (write_info.bw_len > 0)
1979 {
1980 // don't convert, do encryption
1981 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
1982 if (buf_write_bytes(&write_info) == FAIL)
1983 end = 0;
1984 else
1985 nchars += write_info.bw_len;
1986 }
1987 }
1988 write_info.bw_start_lnum = start;
1989
1990#ifdef FEAT_PERSISTENT_UNDO
1991 write_undo_file = (buf->b_p_udf
1992 && overwriting
1993 && !append
1994 && !filtering
Bram Moolenaar65aee0b2021-06-27 14:08:24 +02001995# ifdef CRYPT_NOT_INPLACE
1996 // writing undo file requires
1997 // crypt_encode_inplace()
Christian Brabandt8a4c8122021-07-25 14:36:05 +02001998 && (buf->b_cryptstate == NULL
1999 || crypt_works_inplace(buf->b_cryptstate))
Bram Moolenaar65aee0b2021-06-27 14:08:24 +02002000# endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002001 && reset_changed
2002 && !checking_conversion);
Christian Brabandt8a4c8122021-07-25 14:36:05 +02002003# ifdef CRYPT_NOT_INPLACE
2004 // remove undo file if encrypting it is not possible
2005 if (buf->b_p_udf
2006 && overwriting
2007 && !append
2008 && !filtering
2009 && !checking_conversion
2010 && buf->b_cryptstate != NULL
2011 && !crypt_works_inplace(buf->b_cryptstate))
2012 u_undofile_reset_and_delete(buf);
2013# endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002014 if (write_undo_file)
2015 // Prepare for computing the hash value of the text.
2016 sha256_start(&sha_ctx);
2017#endif
2018
2019 write_info.bw_len = bufsize;
2020 write_info.bw_flags = wb_flags;
2021 fileformat = get_fileformat_force(buf, eap);
2022 s = buffer;
2023 len = 0;
2024 for (lnum = start; lnum <= end; ++lnum)
2025 {
2026 // The next while loop is done once for each character written.
2027 // Keep it fast!
2028 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
2029#ifdef FEAT_PERSISTENT_UNDO
2030 if (write_undo_file)
2031 sha256_update(&sha_ctx, ptr + 1,
2032 (UINT32_T)(STRLEN(ptr + 1) + 1));
2033#endif
2034 while ((c = *++ptr) != NUL)
2035 {
2036 if (c == NL)
2037 *s = NUL; // replace newlines with NULs
2038 else if (c == CAR && fileformat == EOL_MAC)
2039 *s = NL; // Mac: replace CRs with NLs
2040 else
2041 *s = c;
2042 ++s;
2043 if (++len != bufsize)
2044 continue;
Christian Brabandtf573c6e2021-06-20 14:02:16 +02002045#ifdef FEAT_CRYPT
2046 if (write_info.bw_fd > 0 && lnum == end
2047 && (write_info.bw_flags & FIO_ENCRYPTED)
2048 && *buf->b_p_key != NUL && !filtering
2049 && *ptr == NUL)
2050 write_info.bw_finish = TRUE;
2051 #endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002052 if (buf_write_bytes(&write_info) == FAIL)
2053 {
2054 end = 0; // write error: break loop
2055 break;
2056 }
2057 nchars += bufsize;
2058 s = buffer;
2059 len = 0;
2060 write_info.bw_start_lnum = lnum;
2061 }
2062 // write failed or last line has no EOL: stop here
2063 if (end == 0
2064 || (lnum == end
2065 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarb3c8b1d2020-12-23 18:54:57 +01002066 && ((write_bin && lnum == buf->b_no_eol_lnum)
Bram Moolenaar473952e2019-09-28 16:30:04 +02002067 || (lnum == buf->b_ml.ml_line_count
2068 && !buf->b_p_eol))))
2069 {
2070 ++lnum; // written the line, count it
2071 no_eol = TRUE;
2072 break;
2073 }
2074 if (fileformat == EOL_UNIX)
2075 *s++ = NL;
2076 else
2077 {
2078 *s++ = CAR; // EOL_MAC or EOL_DOS: write CR
2079 if (fileformat == EOL_DOS) // write CR-NL
2080 {
2081 if (++len == bufsize)
2082 {
2083 if (buf_write_bytes(&write_info) == FAIL)
2084 {
2085 end = 0; // write error: break loop
2086 break;
2087 }
2088 nchars += bufsize;
2089 s = buffer;
2090 len = 0;
2091 }
2092 *s++ = NL;
2093 }
2094 }
2095 if (++len == bufsize && end)
2096 {
2097 if (buf_write_bytes(&write_info) == FAIL)
2098 {
2099 end = 0; // write error: break loop
2100 break;
2101 }
2102 nchars += bufsize;
2103 s = buffer;
2104 len = 0;
2105
2106 ui_breakcheck();
2107 if (got_int)
2108 {
2109 end = 0; // Interrupted, break loop
2110 break;
2111 }
2112 }
2113#ifdef VMS
2114 // On VMS there is a problem: newlines get added when writing
2115 // blocks at a time. Fix it by writing a line at a time.
2116 // This is much slower!
2117 // Explanation: VAX/DECC RTL insists that records in some RMS
2118 // structures end with a newline (carriage return) character, and
2119 // if they don't it adds one.
2120 // With other RMS structures it works perfect without this fix.
Bram Moolenaar95f0b6e2019-12-15 12:54:18 +01002121# ifndef MIN
2122// Older DECC compiler for VAX doesn't define MIN()
2123# define MIN(a, b) ((a) < (b) ? (a) : (b))
2124# endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002125 if (buf->b_fab_rfm == FAB$C_VFC
2126 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
2127 {
2128 int b2write;
2129
2130 buf->b_fab_mrs = (buf->b_fab_mrs == 0
2131 ? MIN(4096, bufsize)
2132 : MIN(buf->b_fab_mrs, bufsize));
2133
2134 b2write = len;
2135 while (b2write > 0)
2136 {
2137 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
2138 if (buf_write_bytes(&write_info) == FAIL)
2139 {
2140 end = 0;
2141 break;
2142 }
2143 b2write -= MIN(b2write, buf->b_fab_mrs);
2144 }
2145 write_info.bw_len = bufsize;
2146 nchars += len;
2147 s = buffer;
2148 len = 0;
2149 }
2150#endif
2151 }
2152 if (len > 0 && end > 0)
2153 {
2154 write_info.bw_len = len;
Christian Brabandtf573c6e2021-06-20 14:02:16 +02002155#ifdef FEAT_CRYPT
2156 if (write_info.bw_fd > 0 && lnum >= end
2157 && (write_info.bw_flags & FIO_ENCRYPTED)
2158 && *buf->b_p_key != NUL && !filtering)
2159 write_info.bw_finish = TRUE;
2160 #endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002161 if (buf_write_bytes(&write_info) == FAIL)
2162 end = 0; // write error
2163 nchars += len;
2164 }
2165
2166 // Stop when writing done or an error was encountered.
2167 if (!checking_conversion || end == 0)
2168 break;
2169
2170 // If no error happened until now, writing should be ok, so loop to
2171 // really write the buffer.
2172 }
2173
2174 // If we started writing, finish writing. Also when an error was
2175 // encountered.
2176 if (!checking_conversion)
2177 {
2178#if defined(UNIX) && defined(HAVE_FSYNC)
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01002179 // On many journaling file systems there is a bug that causes both the
Bram Moolenaar473952e2019-09-28 16:30:04 +02002180 // original and the backup file to be lost when halting the system
2181 // right after writing the file. That's because only the meta-data is
2182 // journalled. Syncing the file slows down the system, but assures it
2183 // has been written to disk and we don't lose it.
2184 // For a device do try the fsync() but don't complain if it does not
2185 // work (could be a pipe).
2186 // If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
2187 if (p_fs && vim_fsync(fd) != 0 && !device)
2188 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00002189 errmsg = (char_u *)_(e_fsync_failed);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002190 end = 0;
2191 }
2192#endif
2193
2194#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
2195 // Probably need to set the security context.
2196 if (!backup_copy)
2197 mch_copy_sec(backup, wfname);
2198#endif
2199
2200#ifdef UNIX
2201 // When creating a new file, set its owner/group to that of the
2202 // original file. Get the new device and inode number.
2203 if (backup != NULL && !backup_copy)
2204 {
2205# ifdef HAVE_FCHOWN
2206 stat_T st;
2207
2208 // Don't change the owner when it's already OK, some systems remove
2209 // permission or ACL stuff.
2210 if (mch_stat((char *)wfname, &st) < 0
2211 || st.st_uid != st_old.st_uid
2212 || st.st_gid != st_old.st_gid)
2213 {
2214 // changing owner might not be possible
2215 vim_ignored = fchown(fd, st_old.st_uid, -1);
2216 // if changing group fails clear the group permissions
2217 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
2218 perm &= ~070;
2219 }
2220# endif
2221 buf_setino(buf);
2222 }
2223 else if (!buf->b_dev_valid)
2224 // Set the inode when creating a new file.
2225 buf_setino(buf);
2226#endif
2227
2228#ifdef UNIX
2229 if (made_writable)
2230 perm &= ~0200; // reset 'w' bit for security reasons
2231#endif
2232#ifdef HAVE_FCHMOD
2233 // set permission of new file same as old file
2234 if (perm >= 0)
2235 (void)mch_fsetperm(fd, perm);
2236#endif
2237 if (close(fd) != 0)
2238 {
Bram Moolenaarf1474d82021-12-31 19:59:55 +00002239 errmsg = (char_u *)_(e_close_failed);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002240 end = 0;
2241 }
2242
2243#ifndef HAVE_FCHMOD
2244 // set permission of new file same as old file
2245 if (perm >= 0)
2246 (void)mch_setperm(wfname, perm);
2247#endif
2248#ifdef HAVE_ACL
2249 // Probably need to set the ACL before changing the user (can't set the
2250 // ACL on a file the user doesn't own).
2251 // On Solaris, with ZFS and the aclmode property set to "discard" (the
2252 // default), chmod() discards all part of a file's ACL that don't
2253 // represent the mode of the file. It's non-trivial for us to discover
2254 // whether we're in that situation, so we simply always re-set the ACL.
2255# ifndef HAVE_SOLARIS_ZFS_ACL
2256 if (!backup_copy)
2257# endif
2258 mch_set_acl(wfname, acl);
2259#endif
2260#ifdef FEAT_CRYPT
2261 if (buf->b_cryptstate != NULL)
2262 {
2263 crypt_free_state(buf->b_cryptstate);
2264 buf->b_cryptstate = NULL;
2265 }
2266#endif
2267
2268#if defined(FEAT_EVAL)
2269 if (wfname != fname)
2270 {
2271 // The file was written to a temp file, now it needs to be
2272 // converted with 'charconvert' to (overwrite) the output file.
2273 if (end != 0)
2274 {
2275 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
2276 fenc, wfname, fname) == FAIL)
2277 {
2278 write_info.bw_conv_error = TRUE;
2279 end = 0;
2280 }
2281 }
2282 mch_remove(wfname);
2283 vim_free(wfname);
2284 }
2285#endif
2286 }
2287
2288 if (end == 0)
2289 {
2290 // Error encountered.
2291 if (errmsg == NULL)
2292 {
2293 if (write_info.bw_conv_error)
2294 {
2295 if (write_info.bw_conv_error_lnum == 0)
Bram Moolenaarf1474d82021-12-31 19:59:55 +00002296 errmsg = (char_u *)_(e_write_error_conversion_failed_make_fenc_empty_to_override);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002297 else
2298 {
2299 errmsg_allocated = TRUE;
2300 errmsg = alloc(300);
Bram Moolenaarf1474d82021-12-31 19:59:55 +00002301 vim_snprintf((char *)errmsg, 300, _(e_write_error_conversion_failed_in_line_nr_make_fenc_empty_to_override),
Bram Moolenaar473952e2019-09-28 16:30:04 +02002302 (long)write_info.bw_conv_error_lnum);
2303 }
2304 }
2305 else if (got_int)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002306 errmsg = (char_u *)_(e_interrupted);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002307 else
Bram Moolenaarf1474d82021-12-31 19:59:55 +00002308 errmsg = (char_u *)_(e_write_error_file_system_full);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002309 }
2310
2311 // If we have a backup file, try to put it in place of the new file,
2312 // because the new file is probably corrupt. This avoids losing the
2313 // original file when trying to make a backup when writing the file a
2314 // second time.
2315 // When "backup_copy" is set we need to copy the backup over the new
2316 // file. Otherwise rename the backup file.
2317 // If this is OK, don't give the extra warning message.
2318 if (backup != NULL)
2319 {
2320 if (backup_copy)
2321 {
2322 // This may take a while, if we were interrupted let the user
2323 // know we got the message.
2324 if (got_int)
2325 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002326 msg(_(e_interrupted));
Bram Moolenaar473952e2019-09-28 16:30:04 +02002327 out_flush();
2328 }
2329 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
2330 {
2331 if ((write_info.bw_fd = mch_open((char *)fname,
2332 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
2333 perm & 0777)) >= 0)
2334 {
2335 // copy the file.
2336 write_info.bw_buf = smallbuf;
2337 write_info.bw_flags = FIO_NOCONVERT;
2338 while ((write_info.bw_len = read_eintr(fd, smallbuf,
2339 SMALLBUFSIZE)) > 0)
2340 if (buf_write_bytes(&write_info) == FAIL)
2341 break;
2342
2343 if (close(write_info.bw_fd) >= 0
2344 && write_info.bw_len == 0)
2345 end = 1; // success
2346 }
2347 close(fd); // ignore errors for closing read file
2348 }
2349 }
2350 else
2351 {
2352 if (vim_rename(backup, fname) == 0)
2353 end = 1;
2354 }
2355 }
2356 goto fail;
2357 }
2358
2359 lnum -= start; // compute number of written lines
2360 --no_wait_return; // may wait for return now
2361
2362#if !(defined(UNIX) || defined(VMS))
2363 fname = sfname; // use shortname now, for the messages
2364#endif
2365 if (!filtering)
2366 {
2367 msg_add_fname(buf, fname); // put fname in IObuff with quotes
2368 c = FALSE;
2369 if (write_info.bw_conv_error)
2370 {
2371 STRCAT(IObuff, _(" CONVERSION ERROR"));
2372 c = TRUE;
2373 if (write_info.bw_conv_error_lnum != 0)
2374 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
2375 (long)write_info.bw_conv_error_lnum);
2376 }
2377 else if (notconverted)
2378 {
2379 STRCAT(IObuff, _("[NOT converted]"));
2380 c = TRUE;
2381 }
2382 else if (converted)
2383 {
2384 STRCAT(IObuff, _("[converted]"));
2385 c = TRUE;
2386 }
2387 if (device)
2388 {
2389 STRCAT(IObuff, _("[Device]"));
2390 c = TRUE;
2391 }
2392 else if (newfile)
2393 {
Bram Moolenaar722e5052020-06-12 22:31:00 +02002394 STRCAT(IObuff, new_file_message());
Bram Moolenaar473952e2019-09-28 16:30:04 +02002395 c = TRUE;
2396 }
2397 if (no_eol)
2398 {
2399 msg_add_eol();
2400 c = TRUE;
2401 }
2402 // may add [unix/dos/mac]
2403 if (msg_add_fileformat(fileformat))
2404 c = TRUE;
2405#ifdef FEAT_CRYPT
2406 if (wb_flags & FIO_ENCRYPTED)
2407 {
2408 crypt_append_msg(buf);
2409 c = TRUE;
2410 }
2411#endif
2412 msg_add_lines(c, (long)lnum, nchars); // add line/char count
2413 if (!shortmess(SHM_WRITE))
2414 {
2415 if (append)
2416 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
2417 else
2418 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
2419 }
2420
2421 set_keep_msg((char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0), 0);
2422 }
2423
2424 // When written everything correctly: reset 'modified'. Unless not
2425 // writing to the original file and '+' is not in 'cpoptions'.
2426 if (reset_changed && whole && !append
2427 && !write_info.bw_conv_error
2428 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
2429 {
2430 unchanged(buf, TRUE, FALSE);
Christian Brabandtdb3b4462021-10-16 11:58:55 +01002431 // b:changedtick may be incremented in unchanged() but that should not
2432 // trigger a TextChanged event.
Bram Moolenaar473952e2019-09-28 16:30:04 +02002433 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
2434 buf->b_last_changedtick = CHANGEDTICK(buf);
2435 u_unchanged(buf);
2436 u_update_save_nr(buf);
2437 }
2438
2439 // If written to the current file, update the timestamp of the swap file
2440 // and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
2441 if (overwriting)
2442 {
2443 ml_timestamp(buf);
2444 if (append)
2445 buf->b_flags &= ~BF_NEW;
2446 else
2447 buf->b_flags &= ~BF_WRITE_MASK;
2448 }
2449
2450 // If we kept a backup until now, and we are in patch mode, then we make
2451 // the backup file our 'original' file.
2452 if (*p_pm && dobackup)
2453 {
2454 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
2455 fname, p_pm, FALSE);
2456
2457 if (backup != NULL)
2458 {
2459 stat_T st;
2460
2461 // If the original file does not exist yet
2462 // the current backup file becomes the original file
2463 if (org == NULL)
Bram Moolenaar6d057012021-12-31 18:49:43 +00002464 emsg(_(e_patchmode_cant_save_original_file));
Bram Moolenaar473952e2019-09-28 16:30:04 +02002465 else if (mch_stat(org, &st) < 0)
2466 {
2467 vim_rename(backup, (char_u *)org);
2468 VIM_CLEAR(backup); // don't delete the file
2469#ifdef UNIX
2470 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
2471#endif
2472 }
2473 }
2474 // If there is no backup file, remember that a (new) file was
2475 // created.
2476 else
2477 {
2478 int empty_fd;
2479
2480 if (org == NULL
2481 || (empty_fd = mch_open(org,
2482 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
2483 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar6d057012021-12-31 18:49:43 +00002484 emsg(_(e_patchmode_cant_touch_empty_original_file));
Bram Moolenaar473952e2019-09-28 16:30:04 +02002485 else
2486 close(empty_fd);
2487 }
2488 if (org != NULL)
2489 {
2490 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
2491 vim_free(org);
2492 }
2493 }
2494
2495 // Remove the backup unless 'backup' option is set or there was a
2496 // conversion error.
2497 if (!p_bk && backup != NULL && !write_info.bw_conv_error
2498 && mch_remove(backup) != 0)
Bram Moolenaar6d057012021-12-31 18:49:43 +00002499 emsg(_(e_cant_delete_backup_file));
Bram Moolenaar473952e2019-09-28 16:30:04 +02002500
2501 goto nofail;
2502
2503 // Finish up. We get here either after failure or success.
2504fail:
2505 --no_wait_return; // may wait for return now
2506nofail:
2507
2508 // Done saving, we accept changed buffer warnings again
2509 buf->b_saving = FALSE;
2510
2511 vim_free(backup);
2512 if (buffer != smallbuf)
2513 vim_free(buffer);
2514 vim_free(fenc_tofree);
2515 vim_free(write_info.bw_conv_buf);
2516#ifdef USE_ICONV
2517 if (write_info.bw_iconv_fd != (iconv_t)-1)
2518 {
2519 iconv_close(write_info.bw_iconv_fd);
2520 write_info.bw_iconv_fd = (iconv_t)-1;
2521 }
2522#endif
2523#ifdef HAVE_ACL
2524 mch_free_acl(acl);
2525#endif
2526
2527 if (errmsg != NULL)
2528 {
2529 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
2530
2531 attr = HL_ATTR(HLF_E); // set highlight for error messages
2532 msg_add_fname(buf,
2533#ifndef UNIX
2534 sfname
2535#else
2536 fname
2537#endif
2538 ); // put file name in IObuff with quotes
2539 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
2540 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
2541 // If the error message has the form "is ...", put the error number in
2542 // front of the file name.
2543 if (errnum != NULL)
2544 {
2545 STRMOVE(IObuff + numlen, IObuff);
2546 mch_memmove(IObuff, errnum, (size_t)numlen);
2547 }
2548 STRCAT(IObuff, errmsg);
2549 emsg((char *)IObuff);
2550 if (errmsg_allocated)
2551 vim_free(errmsg);
2552
2553 retval = FAIL;
2554 if (end == 0)
2555 {
2556 msg_puts_attr(_("\nWARNING: Original file may be lost or damaged\n"),
2557 attr | MSG_HIST);
2558 msg_puts_attr(_("don't quit the editor until the file is successfully written!"),
2559 attr | MSG_HIST);
2560
2561 // Update the timestamp to avoid an "overwrite changed file"
2562 // prompt when writing again.
2563 if (mch_stat((char *)fname, &st_old) >= 0)
2564 {
2565 buf_store_time(buf, &st_old, fname);
2566 buf->b_mtime_read = buf->b_mtime;
Leah Neukirchen0a7984a2021-10-14 21:27:55 +01002567 buf->b_mtime_read_ns = buf->b_mtime_ns;
Bram Moolenaar473952e2019-09-28 16:30:04 +02002568 }
2569 }
2570 }
2571 msg_scroll = msg_save;
2572
2573#ifdef FEAT_PERSISTENT_UNDO
2574 // When writing the whole file and 'undofile' is set, also write the undo
2575 // file.
2576 if (retval == OK && write_undo_file)
2577 {
2578 char_u hash[UNDO_HASH_SIZE];
2579
2580 sha256_finish(&sha_ctx, hash);
2581 u_write_undo(NULL, FALSE, buf, hash);
2582 }
2583#endif
2584
2585#ifdef FEAT_EVAL
2586 if (!should_abort(retval))
2587#else
2588 if (!got_int)
2589#endif
2590 {
2591 aco_save_T aco;
2592
2593 curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read
2594
2595 // Apply POST autocommands.
2596 // Careful: The autocommands may call buf_write() recursively!
2597 aucmd_prepbuf(&aco, buf);
2598
2599 if (append)
2600 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
2601 FALSE, curbuf, eap);
2602 else if (filtering)
2603 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
2604 FALSE, curbuf, eap);
2605 else if (reset_changed && whole)
2606 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
2607 FALSE, curbuf, eap);
2608 else
2609 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
2610 FALSE, curbuf, eap);
2611
2612 // restore curwin/curbuf and a few other things
2613 aucmd_restbuf(&aco);
2614
2615#ifdef FEAT_EVAL
2616 if (aborting()) // autocmds may abort script processing
2617 retval = FALSE;
2618#endif
2619 }
2620
Bram Moolenaar8e6be342020-11-23 22:01:26 +01002621#ifdef FEAT_VIMINFO
2622 // Make sure marks will be written out to the viminfo file later, even when
2623 // the file is new.
2624 curbuf->b_marks_read = TRUE;
2625#endif
2626
Bram Moolenaar473952e2019-09-28 16:30:04 +02002627 got_int |= prev_got_int;
2628
2629 return retval;
2630}