blob: b283b5eb64dbd512ba34895e3d45699de228c192 [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
Bram Moolenaar473952e2019-09-28 16:30:04 +0200745 && !bt_nofilename(buf)
Bram Moolenaar473952e2019-09-28 16:30:04 +0200746 && !filtering
747 && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
748 && vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
749 {
750 if (set_rw_fname(fname, sfname) == FAIL)
751 return FAIL;
752 buf = curbuf; // just in case autocmds made "buf" invalid
753 }
754
755 if (sfname == NULL)
756 sfname = fname;
757 // For Unix: Use the short file name whenever possible.
758 // Avoids problems with networks and when directory names are changed.
759 // Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
760 // another directory, which we don't detect
761 ffname = fname; // remember full fname
762#ifdef UNIX
763 fname = sfname;
764#endif
765
766 if (buf->b_ffname != NULL && fnamecmp(ffname, buf->b_ffname) == 0)
767 overwriting = TRUE;
768 else
769 overwriting = FALSE;
770
771 if (exiting)
772 settmode(TMODE_COOK); // when exiting allow typeahead now
773
774 ++no_wait_return; // don't wait for return yet
775
776 // Set '[ and '] marks to the lines to be written.
777 buf->b_op_start.lnum = start;
778 buf->b_op_start.col = 0;
779 buf->b_op_end.lnum = end;
780 buf->b_op_end.col = 0;
781
782 {
783 aco_save_T aco;
784 int buf_ffname = FALSE;
785 int buf_sfname = FALSE;
786 int buf_fname_f = FALSE;
787 int buf_fname_s = FALSE;
788 int did_cmd = FALSE;
789 int nofile_err = FALSE;
790 int empty_memline = (buf->b_ml.ml_mfp == NULL);
791 bufref_T bufref;
792
793 // Apply PRE autocommands.
794 // Set curbuf to the buffer to be written.
795 // Careful: The autocommands may call buf_write() recursively!
796 if (ffname == buf->b_ffname)
797 buf_ffname = TRUE;
798 if (sfname == buf->b_sfname)
799 buf_sfname = TRUE;
800 if (fname == buf->b_ffname)
801 buf_fname_f = TRUE;
802 if (fname == buf->b_sfname)
803 buf_fname_s = TRUE;
804
805 // set curwin/curbuf to buf and save a few things
806 aucmd_prepbuf(&aco, buf);
807 set_bufref(&bufref, buf);
808
809 if (append)
810 {
811 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
812 sfname, sfname, FALSE, curbuf, eap)))
813 {
Bram Moolenaar473952e2019-09-28 16:30:04 +0200814 if (overwriting && bt_nofilename(curbuf))
815 nofile_err = TRUE;
816 else
Bram Moolenaar473952e2019-09-28 16:30:04 +0200817 apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
818 sfname, sfname, FALSE, curbuf, eap);
819 }
820 }
821 else if (filtering)
822 {
823 apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
824 NULL, sfname, FALSE, curbuf, eap);
825 }
826 else if (reset_changed && whole)
827 {
828 int was_changed = curbufIsChanged();
829
830 did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
831 sfname, sfname, FALSE, curbuf, eap);
832 if (did_cmd)
833 {
834 if (was_changed && !curbufIsChanged())
835 {
836 // Written everything correctly and BufWriteCmd has reset
837 // 'modified': Correct the undo information so that an
838 // undo now sets 'modified'.
839 u_unchanged(curbuf);
840 u_update_save_nr(curbuf);
841 }
842 }
843 else
844 {
Bram Moolenaar473952e2019-09-28 16:30:04 +0200845 if (overwriting && bt_nofilename(curbuf))
846 nofile_err = TRUE;
847 else
Bram Moolenaar473952e2019-09-28 16:30:04 +0200848 apply_autocmds_exarg(EVENT_BUFWRITEPRE,
849 sfname, sfname, FALSE, curbuf, eap);
850 }
851 }
852 else
853 {
854 if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
855 sfname, sfname, FALSE, curbuf, eap)))
856 {
Bram Moolenaar473952e2019-09-28 16:30:04 +0200857 if (overwriting && bt_nofilename(curbuf))
858 nofile_err = TRUE;
859 else
Bram Moolenaar473952e2019-09-28 16:30:04 +0200860 apply_autocmds_exarg(EVENT_FILEWRITEPRE,
861 sfname, sfname, FALSE, curbuf, eap);
862 }
863 }
864
865 // restore curwin/curbuf and a few other things
866 aucmd_restbuf(&aco);
867
868 // In three situations we return here and don't write the file:
869 // 1. the autocommands deleted or unloaded the buffer.
870 // 2. The autocommands abort script processing.
871 // 3. If one of the "Cmd" autocommands was executed.
872 if (!bufref_valid(&bufref))
873 buf = NULL;
874 if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
875 || did_cmd || nofile_err
876#ifdef FEAT_EVAL
877 || aborting()
878#endif
879 )
880 {
Bram Moolenaare1004402020-10-24 20:49:43 +0200881 if (buf != NULL && (cmdmod.cmod_flags & CMOD_LOCKMARKS))
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100882 {
883 // restore the original '[ and '] positions
884 buf->b_op_start = orig_start;
885 buf->b_op_end = orig_end;
886 }
887
Bram Moolenaar473952e2019-09-28 16:30:04 +0200888 --no_wait_return;
889 msg_scroll = msg_save;
890 if (nofile_err)
Bram Moolenaarf1474d82021-12-31 19:59:55 +0000891 emsg(_(e_no_matching_autocommands_for_acwrite_buffer));
Bram Moolenaar473952e2019-09-28 16:30:04 +0200892
893 if (nofile_err
894#ifdef FEAT_EVAL
895 || aborting()
896#endif
897 )
898 // An aborting error, interrupt or exception in the
899 // autocommands.
900 return FAIL;
901 if (did_cmd)
902 {
903 if (buf == NULL)
904 // The buffer was deleted. We assume it was written
905 // (can't retry anyway).
906 return OK;
907 if (overwriting)
908 {
909 // Assume the buffer was written, update the timestamp.
910 ml_timestamp(buf);
911 if (append)
912 buf->b_flags &= ~BF_NEW;
913 else
914 buf->b_flags &= ~BF_WRITE_MASK;
915 }
916 if (reset_changed && buf->b_changed && !append
917 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
918 // Buffer still changed, the autocommands didn't work
919 // properly.
920 return FAIL;
921 return OK;
922 }
923#ifdef FEAT_EVAL
924 if (!aborting())
925#endif
Bram Moolenaar6d057012021-12-31 18:49:43 +0000926 emsg(_(e_autocommands_deleted_or_unloaded_buffer_to_be_written));
Bram Moolenaar473952e2019-09-28 16:30:04 +0200927 return FAIL;
928 }
929
930 // The autocommands may have changed the number of lines in the file.
931 // When writing the whole file, adjust the end.
932 // When writing part of the file, assume that the autocommands only
933 // changed the number of lines that are to be written (tricky!).
934 if (buf->b_ml.ml_line_count != old_line_count)
935 {
936 if (whole) // write all
937 end = buf->b_ml.ml_line_count;
938 else if (buf->b_ml.ml_line_count > old_line_count) // more lines
939 end += buf->b_ml.ml_line_count - old_line_count;
940 else // less lines
941 {
942 end -= old_line_count - buf->b_ml.ml_line_count;
943 if (end < start)
944 {
945 --no_wait_return;
946 msg_scroll = msg_save;
Bram Moolenaar6d057012021-12-31 18:49:43 +0000947 emsg(_(e_autocommands_changed_number_of_lines_in_unexpected_way));
Bram Moolenaar473952e2019-09-28 16:30:04 +0200948 return FAIL;
949 }
950 }
951 }
952
953 // The autocommands may have changed the name of the buffer, which may
954 // be kept in fname, ffname and sfname.
955 if (buf_ffname)
956 ffname = buf->b_ffname;
957 if (buf_sfname)
958 sfname = buf->b_sfname;
959 if (buf_fname_f)
960 fname = buf->b_ffname;
961 if (buf_fname_s)
962 fname = buf->b_sfname;
963 }
964
Bram Moolenaare1004402020-10-24 20:49:43 +0200965 if (cmdmod.cmod_flags & CMOD_LOCKMARKS)
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +0100966 {
967 // restore the original '[ and '] positions
968 buf->b_op_start = orig_start;
969 buf->b_op_end = orig_end;
970 }
971
Bram Moolenaar473952e2019-09-28 16:30:04 +0200972#ifdef FEAT_NETBEANS_INTG
973 if (netbeans_active() && isNetbeansBuffer(buf))
974 {
975 if (whole)
976 {
977 // b_changed can be 0 after an undo, but we still need to write
978 // the buffer to NetBeans.
979 if (buf->b_changed || isNetbeansModified(buf))
980 {
981 --no_wait_return; // may wait for return now
982 msg_scroll = msg_save;
983 netbeans_save_buffer(buf); // no error checking...
984 return retval;
985 }
986 else
987 {
988 errnum = (char_u *)"E656: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +0000989 errmsg = (char_u *)_(e_netbeans_disallows_writes_of_unmodified_buffers);
Bram Moolenaar473952e2019-09-28 16:30:04 +0200990 buffer = NULL;
991 goto fail;
992 }
993 }
994 else
995 {
996 errnum = (char_u *)"E657: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +0000997 errmsg = (char_u *)_(e_partial_writes_disallowed_for_netbeans_buffers);
Bram Moolenaar473952e2019-09-28 16:30:04 +0200998 buffer = NULL;
999 goto fail;
1000 }
1001 }
1002#endif
1003
1004 if (shortmess(SHM_OVER) && !exiting)
1005 msg_scroll = FALSE; // overwrite previous file message
1006 else
1007 msg_scroll = TRUE; // don't overwrite previous file message
1008 if (!filtering)
1009 filemess(buf,
1010#ifndef UNIX
1011 sfname,
1012#else
1013 fname,
1014#endif
1015 (char_u *)"", 0); // show that we are busy
1016 msg_scroll = FALSE; // always overwrite the file message now
1017
1018 buffer = alloc(WRITEBUFSIZE);
1019 if (buffer == NULL) // can't allocate big buffer, use small
1020 // one (to be able to write when out of
1021 // memory)
1022 {
1023 buffer = smallbuf;
1024 bufsize = SMALLBUFSIZE;
1025 }
1026 else
1027 bufsize = WRITEBUFSIZE;
1028
1029 // Get information about original file (if there is one).
1030#if defined(UNIX)
1031 st_old.st_dev = 0;
1032 st_old.st_ino = 0;
1033 perm = -1;
1034 if (mch_stat((char *)fname, &st_old) < 0)
1035 newfile = TRUE;
1036 else
1037 {
1038 perm = st_old.st_mode;
1039 if (!S_ISREG(st_old.st_mode)) // not a file
1040 {
1041 if (S_ISDIR(st_old.st_mode))
1042 {
1043 errnum = (char_u *)"E502: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001044 errmsg = (char_u *)_(e_is_a_directory);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001045 goto fail;
1046 }
1047 if (mch_nodetype(fname) != NODE_WRITABLE)
1048 {
1049 errnum = (char_u *)"E503: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001050 errmsg = (char_u *)_(e_is_not_file_or_writable_device);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001051 goto fail;
1052 }
1053 // It's a device of some kind (or a fifo) which we can write to
1054 // but for which we can't make a backup.
1055 device = TRUE;
1056 newfile = TRUE;
1057 perm = -1;
1058 }
1059 }
1060#else // !UNIX
1061 // Check for a writable device name.
1062 c = mch_nodetype(fname);
1063 if (c == NODE_OTHER)
1064 {
1065 errnum = (char_u *)"E503: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001066 errmsg = (char_u *)_(e_is_not_file_or_writable_device);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001067 goto fail;
1068 }
1069 if (c == NODE_WRITABLE)
1070 {
1071# if defined(MSWIN)
1072 // MS-Windows allows opening a device, but we will probably get stuck
1073 // trying to write to it.
1074 if (!p_odev)
1075 {
1076 errnum = (char_u *)"E796: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001077 errmsg = (char_u *)_(e_writing_to_device_disabled_with_opendevice_option);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001078 goto fail;
1079 }
1080# endif
1081 device = TRUE;
1082 newfile = TRUE;
1083 perm = -1;
1084 }
1085 else
1086 {
1087 perm = mch_getperm(fname);
1088 if (perm < 0)
1089 newfile = TRUE;
1090 else if (mch_isdir(fname))
1091 {
1092 errnum = (char_u *)"E502: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001093 errmsg = (char_u *)_(e_is_a_directory);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001094 goto fail;
1095 }
1096 if (overwriting)
1097 (void)mch_stat((char *)fname, &st_old);
1098 }
1099#endif // !UNIX
1100
1101 if (!device && !newfile)
1102 {
1103 // Check if the file is really writable (when renaming the file to
1104 // make a backup we won't discover it later).
1105 file_readonly = check_file_readonly(fname, (int)perm);
1106
1107 if (!forceit && file_readonly)
1108 {
1109 if (vim_strchr(p_cpo, CPO_FWRITE) != NULL)
1110 {
1111 errnum = (char_u *)"E504: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001112 errmsg = (char_u *)_(e_is_read_only_cannot_override_W_in_cpoptions);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001113 }
1114 else
1115 {
1116 errnum = (char_u *)"E505: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001117 errmsg = (char_u *)_(e_is_read_only_add_bang_to_override);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001118 }
1119 goto fail;
1120 }
1121
1122 // Check if the timestamp hasn't changed since reading the file.
1123 if (overwriting)
1124 {
1125 retval = check_mtime(buf, &st_old);
1126 if (retval == FAIL)
1127 goto fail;
1128 }
1129 }
1130
1131#ifdef HAVE_ACL
1132 // For systems that support ACL: get the ACL from the original file.
1133 if (!newfile)
1134 acl = mch_get_acl(fname);
1135#endif
1136
1137 // If 'backupskip' is not empty, don't make a backup for some files.
1138 dobackup = (p_wb || p_bk || *p_pm != NUL);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001139 if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname))
1140 dobackup = FALSE;
Bram Moolenaar473952e2019-09-28 16:30:04 +02001141
1142 // Save the value of got_int and reset it. We don't want a previous
1143 // interruption cancel writing, only hitting CTRL-C while writing should
1144 // abort it.
1145 prev_got_int = got_int;
1146 got_int = FALSE;
1147
1148 // Mark the buffer as 'being saved' to prevent changed buffer warnings
1149 buf->b_saving = TRUE;
1150
1151 // If we are not appending or filtering, the file exists, and the
1152 // 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
1153 // When 'patchmode' is set also make a backup when appending.
1154 //
1155 // Do not make any backup, if 'writebackup' and 'backup' are both switched
1156 // off. This helps when editing large files on almost-full disks.
1157 if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup)
1158 {
1159#if defined(UNIX) || defined(MSWIN)
1160 stat_T st;
1161#endif
1162
1163 if ((bkc & BKC_YES) || append) // "yes"
1164 backup_copy = TRUE;
1165#if defined(UNIX) || defined(MSWIN)
1166 else if ((bkc & BKC_AUTO)) // "auto"
1167 {
1168 int i;
1169
1170# ifdef UNIX
1171 // Don't rename the file when:
1172 // - it's a hard link
1173 // - it's a symbolic link
1174 // - we don't have write permission in the directory
1175 // - we can't set the owner/group of the new file
1176 if (st_old.st_nlink > 1
1177 || mch_lstat((char *)fname, &st) < 0
1178 || st.st_dev != st_old.st_dev
1179 || st.st_ino != st_old.st_ino
1180# ifndef HAVE_FCHOWN
1181 || st.st_uid != st_old.st_uid
1182 || st.st_gid != st_old.st_gid
1183# endif
1184 )
1185 backup_copy = TRUE;
1186 else
1187# else
1188# ifdef MSWIN
1189 // On NTFS file systems hard links are possible.
1190 if (mch_is_linked(fname))
1191 backup_copy = TRUE;
1192 else
1193# endif
1194# endif
1195 {
1196 // Check if we can create a file and set the owner/group to
1197 // the ones from the original file.
1198 // First find a file name that doesn't exist yet (use some
1199 // arbitrary numbers).
1200 STRCPY(IObuff, fname);
K.Takatadbdcc792022-07-31 11:50:42 +01001201 fd = -1;
Bram Moolenaar473952e2019-09-28 16:30:04 +02001202 for (i = 4913; ; i += 123)
1203 {
1204 sprintf((char *)gettail(IObuff), "%d", i);
1205 if (mch_lstat((char *)IObuff, &st) < 0)
K.Takatadbdcc792022-07-31 11:50:42 +01001206 {
1207 fd = mch_open((char *)IObuff,
Bram Moolenaar473952e2019-09-28 16:30:04 +02001208 O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, perm);
K.Takatadbdcc792022-07-31 11:50:42 +01001209 if (fd < 0 && errno == EEXIST)
1210 // If the same file name is created by another
1211 // process between lstat() and open(), find another
1212 // name.
1213 continue;
1214 break;
1215 }
1216 }
Bram Moolenaar473952e2019-09-28 16:30:04 +02001217 if (fd < 0) // can't write in directory
1218 backup_copy = TRUE;
1219 else
1220 {
1221# ifdef UNIX
1222# ifdef HAVE_FCHOWN
1223 vim_ignored = fchown(fd, st_old.st_uid, st_old.st_gid);
1224# endif
1225 if (mch_stat((char *)IObuff, &st) < 0
1226 || st.st_uid != st_old.st_uid
1227 || st.st_gid != st_old.st_gid
1228 || (long)st.st_mode != perm)
1229 backup_copy = TRUE;
1230# endif
1231 // Close the file before removing it, on MS-Windows we
1232 // can't delete an open file.
1233 close(fd);
1234 mch_remove(IObuff);
1235# ifdef MSWIN
1236 // MS-Windows may trigger a virus scanner to open the
1237 // file, we can't delete it then. Keep trying for half a
1238 // second.
1239 {
1240 int try;
1241
1242 for (try = 0; try < 10; ++try)
1243 {
1244 if (mch_lstat((char *)IObuff, &st) < 0)
1245 break;
1246 ui_delay(50L, TRUE); // wait 50 msec
1247 mch_remove(IObuff);
1248 }
1249 }
1250# endif
1251 }
1252 }
1253 }
1254
1255 // Break symlinks and/or hardlinks if we've been asked to.
1256 if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK))
1257 {
1258# ifdef UNIX
1259 int lstat_res;
1260
1261 lstat_res = mch_lstat((char *)fname, &st);
1262
1263 // Symlinks.
1264 if ((bkc & BKC_BREAKSYMLINK)
1265 && lstat_res == 0
1266 && st.st_ino != st_old.st_ino)
1267 backup_copy = FALSE;
1268
1269 // Hardlinks.
1270 if ((bkc & BKC_BREAKHARDLINK)
1271 && st_old.st_nlink > 1
1272 && (lstat_res != 0 || st.st_ino == st_old.st_ino))
1273 backup_copy = FALSE;
1274# else
1275# if defined(MSWIN)
1276 // Symlinks.
1277 if ((bkc & BKC_BREAKSYMLINK) && mch_is_symbolic_link(fname))
1278 backup_copy = FALSE;
1279
1280 // Hardlinks.
1281 if ((bkc & BKC_BREAKHARDLINK) && mch_is_hard_link(fname))
1282 backup_copy = FALSE;
1283# endif
1284# endif
1285 }
1286
1287#endif
1288
1289 // make sure we have a valid backup extension to use
1290 if (*p_bex == NUL)
1291 backup_ext = (char_u *)".bak";
1292 else
1293 backup_ext = p_bex;
1294
1295 if (backup_copy
1296 && (fd = mch_open((char *)fname, O_RDONLY | O_EXTRA, 0)) >= 0)
1297 {
1298 int bfd;
1299 char_u *copybuf, *wp;
1300 int some_error = FALSE;
1301 stat_T st_new;
1302 char_u *dirp;
1303 char_u *rootname;
1304#if defined(UNIX) || defined(MSWIN)
1305 char_u *p;
1306#endif
1307#if defined(UNIX)
1308 int did_set_shortname;
1309 mode_t umask_save;
1310#endif
1311
1312 copybuf = alloc(WRITEBUFSIZE + 1);
1313 if (copybuf == NULL)
1314 {
1315 some_error = TRUE; // out of memory
1316 goto nobackup;
1317 }
1318
1319 // Try to make the backup in each directory in the 'bdir' option.
1320 //
1321 // Unix semantics has it, that we may have a writable file,
1322 // that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
1323 // - the directory is not writable,
1324 // - the file may be a symbolic link,
1325 // - the file may belong to another user/group, etc.
1326 //
1327 // For these reasons, the existing writable file must be truncated
1328 // and reused. Creation of a backup COPY will be attempted.
1329 dirp = p_bdir;
1330 while (*dirp)
1331 {
1332#ifdef UNIX
1333 st_new.st_ino = 0;
1334 st_new.st_dev = 0;
1335 st_new.st_gid = 0;
1336#endif
1337
1338 // Isolate one directory name, using an entry in 'bdir'.
1339 (void)copy_option_part(&dirp, copybuf, WRITEBUFSIZE, ",");
1340
1341#if defined(UNIX) || defined(MSWIN)
1342 p = copybuf + STRLEN(copybuf);
1343 if (after_pathsep(copybuf, p) && p[-1] == p[-2])
1344 // Ends with '//', use full path
1345 if ((p = make_percent_swname(copybuf, fname)) != NULL)
1346 {
1347 backup = modname(p, backup_ext, FALSE);
1348 vim_free(p);
1349 }
1350#endif
1351 rootname = get_file_in_dir(fname, copybuf);
1352 if (rootname == NULL)
1353 {
1354 some_error = TRUE; // out of memory
1355 goto nobackup;
1356 }
1357
1358#if defined(UNIX)
1359 did_set_shortname = FALSE;
1360#endif
1361
1362 // May try twice if 'shortname' not set.
1363 for (;;)
1364 {
1365 // Make the backup file name.
1366 if (backup == NULL)
1367 backup = buf_modname((buf->b_p_sn || buf->b_shortname),
1368 rootname, backup_ext, FALSE);
1369 if (backup == NULL)
1370 {
1371 vim_free(rootname);
1372 some_error = TRUE; // out of memory
1373 goto nobackup;
1374 }
1375
1376 // Check if backup file already exists.
1377 if (mch_stat((char *)backup, &st_new) >= 0)
1378 {
1379#ifdef UNIX
1380 // Check if backup file is same as original file.
1381 // May happen when modname() gave the same file back.
1382 // E.g. silly link, or file name-length reached.
1383 // If we don't check here, we either ruin the file
1384 // when copying or erase it after writing. jw.
1385 if (st_new.st_dev == st_old.st_dev
1386 && st_new.st_ino == st_old.st_ino)
1387 {
1388 VIM_CLEAR(backup); // no backup file to delete
1389 // may try again with 'shortname' set
1390 if (!(buf->b_shortname || buf->b_p_sn))
1391 {
1392 buf->b_shortname = TRUE;
1393 did_set_shortname = TRUE;
1394 continue;
1395 }
1396 // setting shortname didn't help
1397 if (did_set_shortname)
1398 buf->b_shortname = FALSE;
1399 break;
1400 }
1401#endif
1402
1403 // If we are not going to keep the backup file, don't
1404 // delete an existing one, try to use another name.
1405 // Change one character, just before the extension.
1406 if (!p_bk)
1407 {
1408 wp = backup + STRLEN(backup) - 1
1409 - STRLEN(backup_ext);
1410 if (wp < backup) // empty file name ???
1411 wp = backup;
1412 *wp = 'z';
1413 while (*wp > 'a'
1414 && mch_stat((char *)backup, &st_new) >= 0)
1415 --*wp;
1416 // They all exist??? Must be something wrong.
1417 if (*wp == 'a')
1418 VIM_CLEAR(backup);
1419 }
1420 }
1421 break;
1422 }
1423 vim_free(rootname);
1424
1425 // Try to create the backup file
1426 if (backup != NULL)
1427 {
1428 // remove old backup, if present
1429 mch_remove(backup);
1430 // Open with O_EXCL to avoid the file being created while
1431 // we were sleeping (symlink hacker attack?). Reset umask
1432 // if possible to avoid mch_setperm() below.
1433#ifdef UNIX
1434 umask_save = umask(0);
1435#endif
1436 bfd = mch_open((char *)backup,
1437 O_WRONLY|O_CREAT|O_EXTRA|O_EXCL|O_NOFOLLOW,
1438 perm & 0777);
1439#ifdef UNIX
1440 (void)umask(umask_save);
1441#endif
1442 if (bfd < 0)
1443 VIM_CLEAR(backup);
1444 else
1445 {
1446 // Set file protection same as original file, but
1447 // strip s-bit. Only needed if umask() wasn't used
1448 // above.
1449#ifndef UNIX
1450 (void)mch_setperm(backup, perm & 0777);
1451#else
1452 // Try to set the group of the backup same as the
1453 // original file. If this fails, set the protection
1454 // bits for the group same as the protection bits for
1455 // others.
1456 if (st_new.st_gid != st_old.st_gid
1457# ifdef HAVE_FCHOWN // sequent-ptx lacks fchown()
1458 && fchown(bfd, (uid_t)-1, st_old.st_gid) != 0
1459# endif
1460 )
1461 mch_setperm(backup,
1462 (perm & 0707) | ((perm & 07) << 3));
1463# if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1464 mch_copy_sec(fname, backup);
1465# endif
1466#endif
1467
1468 // copy the file.
1469 write_info.bw_fd = bfd;
1470 write_info.bw_buf = copybuf;
1471 write_info.bw_flags = FIO_NOCONVERT;
1472 while ((write_info.bw_len = read_eintr(fd, copybuf,
1473 WRITEBUFSIZE)) > 0)
1474 {
1475 if (buf_write_bytes(&write_info) == FAIL)
1476 {
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001477 errmsg = (char_u *)_(e_canot_write_to_backup_file_add_bang_to_override);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001478 break;
1479 }
1480 ui_breakcheck();
1481 if (got_int)
1482 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00001483 errmsg = (char_u *)_(e_interrupted);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001484 break;
1485 }
1486 }
1487
1488 if (close(bfd) < 0 && errmsg == NULL)
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001489 errmsg = (char_u *)_(e_close_error_for_backup_file_add_bang_to_write_anyway);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001490 if (write_info.bw_len < 0)
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001491 errmsg = (char_u *)_(e_cant_read_file_for_backup_add_bang_to_write_anyway);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001492#ifdef UNIX
1493 set_file_time(backup, st_old.st_atime, st_old.st_mtime);
1494#endif
1495#ifdef HAVE_ACL
1496 mch_set_acl(backup, acl);
1497#endif
1498#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
1499 mch_copy_sec(fname, backup);
1500#endif
Bram Moolenaar7781ebe2021-02-01 20:35:01 +01001501#ifdef MSWIN
1502 (void)mch_copy_file_attribute(fname, backup);
1503#endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02001504 break;
1505 }
1506 }
1507 }
1508 nobackup:
1509 close(fd); // ignore errors for closing read file
1510 vim_free(copybuf);
1511
1512 if (backup == NULL && errmsg == NULL)
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001513 errmsg = (char_u *)_(e_cannot_create_backup_file_add_bang_to_write_anyway);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001514 // ignore errors when forceit is TRUE
1515 if ((some_error || errmsg != NULL) && !forceit)
1516 {
1517 retval = FAIL;
1518 goto fail;
1519 }
1520 errmsg = NULL;
1521 }
1522 else
1523 {
1524 char_u *dirp;
1525 char_u *p;
1526 char_u *rootname;
1527
1528 // Make a backup by renaming the original file.
1529
1530 // If 'cpoptions' includes the "W" flag, we don't want to
1531 // overwrite a read-only file. But rename may be possible
1532 // anyway, thus we need an extra check here.
1533 if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL)
1534 {
1535 errnum = (char_u *)"E504: ";
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001536 errmsg = (char_u *)_(e_is_read_only_cannot_override_W_in_cpoptions);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001537 goto fail;
1538 }
1539
1540 // Form the backup file name - change path/fo.o.h to
1541 // path/fo.o.h.bak Try all directories in 'backupdir', first one
1542 // that works is used.
1543 dirp = p_bdir;
1544 while (*dirp)
1545 {
1546 // Isolate one directory name and make the backup file name.
1547 (void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
1548
1549#if defined(UNIX) || defined(MSWIN)
1550 p = IObuff + STRLEN(IObuff);
1551 if (after_pathsep(IObuff, p) && p[-1] == p[-2])
1552 // path ends with '//', use full path
1553 if ((p = make_percent_swname(IObuff, fname)) != NULL)
1554 {
1555 backup = modname(p, backup_ext, FALSE);
1556 vim_free(p);
1557 }
1558#endif
1559 if (backup == NULL)
1560 {
1561 rootname = get_file_in_dir(fname, IObuff);
1562 if (rootname == NULL)
1563 backup = NULL;
1564 else
1565 {
1566 backup = buf_modname(
1567 (buf->b_p_sn || buf->b_shortname),
1568 rootname, backup_ext, FALSE);
1569 vim_free(rootname);
1570 }
1571 }
1572
1573 if (backup != NULL)
1574 {
1575 // If we are not going to keep the backup file, don't
1576 // delete an existing one, try to use another name.
1577 // Change one character, just before the extension.
1578 if (!p_bk && mch_getperm(backup) >= 0)
1579 {
1580 p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
1581 if (p < backup) // empty file name ???
1582 p = backup;
1583 *p = 'z';
1584 while (*p > 'a' && mch_getperm(backup) >= 0)
1585 --*p;
1586 // They all exist??? Must be something wrong!
1587 if (*p == 'a')
1588 VIM_CLEAR(backup);
1589 }
1590 }
1591 if (backup != NULL)
1592 {
1593 // Delete any existing backup and move the current version
1594 // to the backup. For safety, we don't remove the backup
1595 // until the write has finished successfully. And if the
1596 // 'backup' option is set, leave it around.
1597
1598 // If the renaming of the original file to the backup file
1599 // works, quit here.
1600 if (vim_rename(fname, backup) == 0)
1601 break;
1602
1603 VIM_CLEAR(backup); // don't do the rename below
1604 }
1605 }
1606 if (backup == NULL && !forceit)
1607 {
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001608 errmsg = (char_u *)_(e_cant_make_backup_file_add_bang_to_write_anyway);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001609 goto fail;
1610 }
1611 }
1612 }
1613
1614#if defined(UNIX)
1615 // When using ":w!" and the file was read-only: make it writable
1616 if (forceit && perm >= 0 && !(perm & 0200) && st_old.st_uid == getuid()
1617 && vim_strchr(p_cpo, CPO_FWRITE) == NULL)
1618 {
1619 perm |= 0200;
1620 (void)mch_setperm(fname, perm);
1621 made_writable = TRUE;
1622 }
1623#endif
1624
1625 // When using ":w!" and writing to the current file, 'readonly' makes no
1626 // sense, reset it, unless 'Z' appears in 'cpoptions'.
1627 if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL)
1628 {
1629 buf->b_p_ro = FALSE;
Bram Moolenaar473952e2019-09-28 16:30:04 +02001630 need_maketitle = TRUE; // set window title later
Bram Moolenaar473952e2019-09-28 16:30:04 +02001631 status_redraw_all(); // redraw status lines later
1632 }
1633
1634 if (end > buf->b_ml.ml_line_count)
1635 end = buf->b_ml.ml_line_count;
1636 if (buf->b_ml.ml_flags & ML_EMPTY)
1637 start = end + 1;
1638
1639 // If the original file is being overwritten, there is a small chance that
1640 // we crash in the middle of writing. Therefore the file is preserved now.
1641 // This makes all block numbers positive so that recovery does not need
1642 // the original file.
1643 // Don't do this if there is a backup file and we are exiting.
1644 if (reset_changed && !newfile && overwriting
1645 && !(exiting && backup != NULL))
1646 {
1647 ml_preserve(buf, FALSE);
1648 if (got_int)
1649 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00001650 errmsg = (char_u *)_(e_interrupted);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001651 goto restore_backup;
1652 }
1653 }
1654
1655#ifdef VMS
1656 vms_remove_version(fname); // remove version
1657#endif
1658 // Default: write the file directly. May write to a temp file for
1659 // multi-byte conversion.
1660 wfname = fname;
1661
1662 // Check for forced 'fileencoding' from "++opt=val" argument.
1663 if (eap != NULL && eap->force_enc != 0)
1664 {
1665 fenc = eap->cmd + eap->force_enc;
1666 fenc = enc_canonize(fenc);
1667 fenc_tofree = fenc;
1668 }
1669 else
1670 fenc = buf->b_p_fenc;
1671
1672 // Check if the file needs to be converted.
1673 converted = need_conversion(fenc);
1674
1675 // Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
1676 // Latin1 to Unicode conversion. This is handled in buf_write_bytes().
1677 // Prepare the flags for it and allocate bw_conv_buf when needed.
1678 if (converted && (enc_utf8 || STRCMP(p_enc, "latin1") == 0))
1679 {
1680 wb_flags = get_fio_flags(fenc);
1681 if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8))
1682 {
1683 // Need to allocate a buffer to translate into.
1684 if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8))
1685 write_info.bw_conv_buflen = bufsize * 2;
1686 else // FIO_UCS4
1687 write_info.bw_conv_buflen = bufsize * 4;
1688 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1689 if (write_info.bw_conv_buf == NULL)
1690 end = 0;
1691 }
1692 }
1693
1694#ifdef MSWIN
1695 if (converted && wb_flags == 0 && (wb_flags = get_win_fio_flags(fenc)) != 0)
1696 {
1697 // Convert UTF-8 -> UCS-2 and UCS-2 -> DBCS. Worst-case * 4:
1698 write_info.bw_conv_buflen = bufsize * 4;
1699 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1700 if (write_info.bw_conv_buf == NULL)
1701 end = 0;
1702 }
1703#endif
1704
1705#ifdef MACOS_CONVERT
1706 if (converted && wb_flags == 0 && (wb_flags = get_mac_fio_flags(fenc)) != 0)
1707 {
1708 write_info.bw_conv_buflen = bufsize * 3;
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#if defined(FEAT_EVAL) || defined(USE_ICONV)
1716 if (converted && wb_flags == 0)
1717 {
1718# ifdef USE_ICONV
1719 // Use iconv() conversion when conversion is needed and it's not done
1720 // internally.
1721 write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc,
1722 enc_utf8 ? (char_u *)"utf-8" : p_enc);
1723 if (write_info.bw_iconv_fd != (iconv_t)-1)
1724 {
1725 // We're going to use iconv(), allocate a buffer to convert in.
1726 write_info.bw_conv_buflen = bufsize * ICONV_MULT;
1727 write_info.bw_conv_buf = alloc(write_info.bw_conv_buflen);
1728 if (write_info.bw_conv_buf == NULL)
1729 end = 0;
1730 write_info.bw_first = TRUE;
1731 }
1732# ifdef FEAT_EVAL
1733 else
1734# endif
1735# endif
1736
1737# ifdef FEAT_EVAL
1738 // When the file needs to be converted with 'charconvert' after
1739 // writing, write to a temp file instead and let the conversion
1740 // overwrite the original file.
1741 if (*p_ccv != NUL)
1742 {
1743 wfname = vim_tempname('w', FALSE);
1744 if (wfname == NULL) // Can't write without a tempfile!
1745 {
Bram Moolenaar6d057012021-12-31 18:49:43 +00001746 errmsg = (char_u *)_(e_cant_find_temp_file_for_writing);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001747 goto restore_backup;
1748 }
1749 }
1750# endif
1751 }
1752#endif
1753 if (converted && wb_flags == 0
1754#ifdef USE_ICONV
1755 && write_info.bw_iconv_fd == (iconv_t)-1
1756# endif
1757# ifdef FEAT_EVAL
1758 && wfname == fname
1759# endif
1760 )
1761 {
1762 if (!forceit)
1763 {
Bram Moolenaar6d057012021-12-31 18:49:43 +00001764 errmsg = (char_u *)_(e_cannot_convert_add_bang_to_write_without_conversion);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001765 goto restore_backup;
1766 }
1767 notconverted = TRUE;
1768 }
1769
1770 // If conversion is taking place, we may first pretend to write and check
1771 // for conversion errors. Then loop again to write for real.
1772 // When not doing conversion this writes for real right away.
1773 for (checking_conversion = TRUE; ; checking_conversion = FALSE)
1774 {
1775 // There is no need to check conversion when:
1776 // - there is no conversion
1777 // - we make a backup file, that can be restored in case of conversion
1778 // failure.
1779 if (!converted || dobackup)
1780 checking_conversion = FALSE;
1781
1782 if (checking_conversion)
1783 {
1784 // Make sure we don't write anything.
1785 fd = -1;
1786 write_info.bw_fd = fd;
1787 }
1788 else
1789 {
1790#ifdef HAVE_FTRUNCATE
1791# define TRUNC_ON_OPEN 0
1792#else
1793# define TRUNC_ON_OPEN O_TRUNC
1794#endif
1795 // Open the file "wfname" for writing.
1796 // We may try to open the file twice: If we can't write to the file
1797 // and forceit is TRUE we delete the existing file and try to
1798 // create a new one. If this still fails we may have lost the
1799 // original file! (this may happen when the user reached his
1800 // quotum for number of files).
1801 // Appending will fail if the file does not exist and forceit is
1802 // FALSE.
1803 while ((fd = mch_open((char *)wfname, O_WRONLY | O_EXTRA | (append
1804 ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
1805 : (O_CREAT | TRUNC_ON_OPEN))
1806 , perm < 0 ? 0666 : (perm & 0777))) < 0)
1807 {
1808 // A forced write will try to create a new file if the old one
1809 // is still readonly. This may also happen when the directory
1810 // is read-only. In that case the mch_remove() will fail.
1811 if (errmsg == NULL)
1812 {
1813#ifdef UNIX
1814 stat_T st;
1815
1816 // Don't delete the file when it's a hard or symbolic link.
1817 if ((!newfile && st_old.st_nlink > 1)
1818 || (mch_lstat((char *)fname, &st) == 0
1819 && (st.st_dev != st_old.st_dev
1820 || st.st_ino != st_old.st_ino)))
Bram Moolenaar1a992222021-12-31 17:25:48 +00001821 errmsg =
1822 (char_u *)_(e_cant_open_linked_file_for_writing);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001823 else
1824#endif
1825 {
Bram Moolenaar6d057012021-12-31 18:49:43 +00001826 errmsg = (char_u *)_(e_cant_open_file_for_writing);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001827 if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
1828 && perm >= 0)
1829 {
1830#ifdef UNIX
1831 // we write to the file, thus it should be marked
1832 // writable after all
1833 if (!(perm & 0200))
1834 made_writable = TRUE;
1835 perm |= 0200;
1836 if (st_old.st_uid != getuid()
1837 || st_old.st_gid != getgid())
1838 perm &= 0777;
1839#endif
1840 if (!append) // don't remove when appending
1841 mch_remove(wfname);
1842 continue;
1843 }
1844 }
1845 }
1846
1847restore_backup:
1848 {
1849 stat_T st;
1850
1851 // If we failed to open the file, we don't need a backup.
1852 // Throw it away. If we moved or removed the original file
1853 // try to put the backup in its place.
1854 if (backup != NULL && wfname == fname)
1855 {
1856 if (backup_copy)
1857 {
1858 // There is a small chance that we removed the
1859 // original, try to move the copy in its place.
1860 // This may not work if the vim_rename() fails.
1861 // In that case we leave the copy around.
1862
1863 // If file does not exist, put the copy in its
1864 // place
1865 if (mch_stat((char *)fname, &st) < 0)
1866 vim_rename(backup, fname);
1867 // if original file does exist throw away the copy
1868 if (mch_stat((char *)fname, &st) >= 0)
1869 mch_remove(backup);
1870 }
1871 else
1872 {
1873 // try to put the original file back
1874 vim_rename(backup, fname);
1875 }
1876 }
1877
1878 // if original file no longer exists give an extra warning
1879 if (!newfile && mch_stat((char *)fname, &st) < 0)
1880 end = 0;
1881 }
1882
1883 if (wfname != fname)
1884 vim_free(wfname);
1885 goto fail;
1886 }
1887 write_info.bw_fd = fd;
1888
1889#if defined(UNIX)
1890 {
1891 stat_T st;
1892
1893 // Double check we are writing the intended file before making
1894 // any changes.
1895 if (overwriting
1896 && (!dobackup || backup_copy)
1897 && fname == wfname
1898 && perm >= 0
1899 && mch_fstat(fd, &st) == 0
1900 && st.st_ino != st_old.st_ino)
1901 {
1902 close(fd);
Bram Moolenaarf1474d82021-12-31 19:59:55 +00001903 errmsg = (char_u *)_(e_file_changed_while_writing);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001904 goto fail;
1905 }
1906 }
1907#endif
1908#ifdef HAVE_FTRUNCATE
1909 if (!append)
1910 vim_ignored = ftruncate(fd, (off_t)0);
1911#endif
1912
1913#if defined(MSWIN)
1914 if (backup != NULL && overwriting && !append)
Bram Moolenaar7781ebe2021-02-01 20:35:01 +01001915 (void)mch_copy_file_attribute(backup, wfname);
Bram Moolenaar473952e2019-09-28 16:30:04 +02001916
1917 if (!overwriting && !append)
1918 {
1919 if (buf->b_ffname != NULL)
1920 (void)mch_copy_file_attribute(buf->b_ffname, wfname);
1921 // Should copy resource fork
1922 }
1923#endif
1924
1925#ifdef FEAT_CRYPT
1926 if (*buf->b_p_key != NUL && !filtering)
1927 {
1928 char_u *header;
1929 int header_len;
1930
1931 buf->b_cryptstate = crypt_create_for_writing(
1932 crypt_get_method_nr(buf),
1933 buf->b_p_key, &header, &header_len);
1934 if (buf->b_cryptstate == NULL || header == NULL)
1935 end = 0;
1936 else
1937 {
1938 // Write magic number, so that Vim knows how this file is
1939 // encrypted when reading it back.
1940 write_info.bw_buf = header;
1941 write_info.bw_len = header_len;
1942 write_info.bw_flags = FIO_NOCONVERT;
1943 if (buf_write_bytes(&write_info) == FAIL)
1944 end = 0;
1945 wb_flags |= FIO_ENCRYPTED;
1946 vim_free(header);
1947 }
1948 }
1949#endif
1950 }
1951 errmsg = NULL;
1952
1953 write_info.bw_buf = buffer;
1954 nchars = 0;
1955
1956 // use "++bin", "++nobin" or 'binary'
1957 if (eap != NULL && eap->force_bin != 0)
1958 write_bin = (eap->force_bin == FORCE_BIN);
1959 else
1960 write_bin = buf->b_p_bin;
1961
1962 // The BOM is written just after the encryption magic number.
1963 // Skip it when appending and the file already existed, the BOM only
1964 // makes sense at the start of the file.
1965 if (buf->b_p_bomb && !write_bin && (!append || perm < 0))
1966 {
1967 write_info.bw_len = make_bom(buffer, fenc);
1968 if (write_info.bw_len > 0)
1969 {
1970 // don't convert, do encryption
1971 write_info.bw_flags = FIO_NOCONVERT | wb_flags;
1972 if (buf_write_bytes(&write_info) == FAIL)
1973 end = 0;
1974 else
1975 nchars += write_info.bw_len;
1976 }
1977 }
1978 write_info.bw_start_lnum = start;
1979
1980#ifdef FEAT_PERSISTENT_UNDO
1981 write_undo_file = (buf->b_p_udf
1982 && overwriting
1983 && !append
1984 && !filtering
Bram Moolenaar65aee0b2021-06-27 14:08:24 +02001985# ifdef CRYPT_NOT_INPLACE
1986 // writing undo file requires
1987 // crypt_encode_inplace()
Christian Brabandt8a4c8122021-07-25 14:36:05 +02001988 && (buf->b_cryptstate == NULL
1989 || crypt_works_inplace(buf->b_cryptstate))
Bram Moolenaar65aee0b2021-06-27 14:08:24 +02001990# endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02001991 && reset_changed
1992 && !checking_conversion);
Christian Brabandt8a4c8122021-07-25 14:36:05 +02001993# ifdef CRYPT_NOT_INPLACE
1994 // remove undo file if encrypting it is not possible
1995 if (buf->b_p_udf
1996 && overwriting
1997 && !append
1998 && !filtering
1999 && !checking_conversion
2000 && buf->b_cryptstate != NULL
2001 && !crypt_works_inplace(buf->b_cryptstate))
2002 u_undofile_reset_and_delete(buf);
2003# endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002004 if (write_undo_file)
2005 // Prepare for computing the hash value of the text.
2006 sha256_start(&sha_ctx);
2007#endif
2008
2009 write_info.bw_len = bufsize;
2010 write_info.bw_flags = wb_flags;
2011 fileformat = get_fileformat_force(buf, eap);
2012 s = buffer;
2013 len = 0;
2014 for (lnum = start; lnum <= end; ++lnum)
2015 {
2016 // The next while loop is done once for each character written.
2017 // Keep it fast!
2018 ptr = ml_get_buf(buf, lnum, FALSE) - 1;
2019#ifdef FEAT_PERSISTENT_UNDO
2020 if (write_undo_file)
2021 sha256_update(&sha_ctx, ptr + 1,
2022 (UINT32_T)(STRLEN(ptr + 1) + 1));
2023#endif
2024 while ((c = *++ptr) != NUL)
2025 {
2026 if (c == NL)
2027 *s = NUL; // replace newlines with NULs
2028 else if (c == CAR && fileformat == EOL_MAC)
2029 *s = NL; // Mac: replace CRs with NLs
2030 else
2031 *s = c;
2032 ++s;
2033 if (++len != bufsize)
2034 continue;
Christian Brabandtf573c6e2021-06-20 14:02:16 +02002035#ifdef FEAT_CRYPT
2036 if (write_info.bw_fd > 0 && lnum == end
2037 && (write_info.bw_flags & FIO_ENCRYPTED)
2038 && *buf->b_p_key != NUL && !filtering
2039 && *ptr == NUL)
2040 write_info.bw_finish = TRUE;
2041 #endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002042 if (buf_write_bytes(&write_info) == FAIL)
2043 {
2044 end = 0; // write error: break loop
2045 break;
2046 }
2047 nchars += bufsize;
2048 s = buffer;
2049 len = 0;
2050 write_info.bw_start_lnum = lnum;
2051 }
2052 // write failed or last line has no EOL: stop here
2053 if (end == 0
2054 || (lnum == end
2055 && (write_bin || !buf->b_p_fixeol)
Bram Moolenaarb3c8b1d2020-12-23 18:54:57 +01002056 && ((write_bin && lnum == buf->b_no_eol_lnum)
Bram Moolenaar473952e2019-09-28 16:30:04 +02002057 || (lnum == buf->b_ml.ml_line_count
2058 && !buf->b_p_eol))))
2059 {
2060 ++lnum; // written the line, count it
2061 no_eol = TRUE;
2062 break;
2063 }
2064 if (fileformat == EOL_UNIX)
2065 *s++ = NL;
2066 else
2067 {
2068 *s++ = CAR; // EOL_MAC or EOL_DOS: write CR
2069 if (fileformat == EOL_DOS) // write CR-NL
2070 {
2071 if (++len == bufsize)
2072 {
2073 if (buf_write_bytes(&write_info) == FAIL)
2074 {
2075 end = 0; // write error: break loop
2076 break;
2077 }
2078 nchars += bufsize;
2079 s = buffer;
2080 len = 0;
2081 }
2082 *s++ = NL;
2083 }
2084 }
2085 if (++len == bufsize && end)
2086 {
2087 if (buf_write_bytes(&write_info) == FAIL)
2088 {
2089 end = 0; // write error: break loop
2090 break;
2091 }
2092 nchars += bufsize;
2093 s = buffer;
2094 len = 0;
2095
2096 ui_breakcheck();
2097 if (got_int)
2098 {
2099 end = 0; // Interrupted, break loop
2100 break;
2101 }
2102 }
2103#ifdef VMS
2104 // On VMS there is a problem: newlines get added when writing
2105 // blocks at a time. Fix it by writing a line at a time.
2106 // This is much slower!
2107 // Explanation: VAX/DECC RTL insists that records in some RMS
2108 // structures end with a newline (carriage return) character, and
2109 // if they don't it adds one.
2110 // With other RMS structures it works perfect without this fix.
Bram Moolenaar95f0b6e2019-12-15 12:54:18 +01002111# ifndef MIN
2112// Older DECC compiler for VAX doesn't define MIN()
2113# define MIN(a, b) ((a) < (b) ? (a) : (b))
2114# endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002115 if (buf->b_fab_rfm == FAB$C_VFC
2116 || ((buf->b_fab_rat & (FAB$M_FTN | FAB$M_CR)) != 0))
2117 {
2118 int b2write;
2119
2120 buf->b_fab_mrs = (buf->b_fab_mrs == 0
2121 ? MIN(4096, bufsize)
2122 : MIN(buf->b_fab_mrs, bufsize));
2123
2124 b2write = len;
2125 while (b2write > 0)
2126 {
2127 write_info.bw_len = MIN(b2write, buf->b_fab_mrs);
2128 if (buf_write_bytes(&write_info) == FAIL)
2129 {
2130 end = 0;
2131 break;
2132 }
2133 b2write -= MIN(b2write, buf->b_fab_mrs);
2134 }
2135 write_info.bw_len = bufsize;
2136 nchars += len;
2137 s = buffer;
2138 len = 0;
2139 }
2140#endif
2141 }
2142 if (len > 0 && end > 0)
2143 {
2144 write_info.bw_len = len;
Christian Brabandtf573c6e2021-06-20 14:02:16 +02002145#ifdef FEAT_CRYPT
2146 if (write_info.bw_fd > 0 && lnum >= end
2147 && (write_info.bw_flags & FIO_ENCRYPTED)
2148 && *buf->b_p_key != NUL && !filtering)
2149 write_info.bw_finish = TRUE;
2150 #endif
Bram Moolenaar473952e2019-09-28 16:30:04 +02002151 if (buf_write_bytes(&write_info) == FAIL)
2152 end = 0; // write error
2153 nchars += len;
2154 }
2155
2156 // Stop when writing done or an error was encountered.
2157 if (!checking_conversion || end == 0)
2158 break;
2159
2160 // If no error happened until now, writing should be ok, so loop to
2161 // really write the buffer.
2162 }
2163
2164 // If we started writing, finish writing. Also when an error was
2165 // encountered.
2166 if (!checking_conversion)
2167 {
2168#if defined(UNIX) && defined(HAVE_FSYNC)
Bram Moolenaar8e7d6222020-12-18 19:49:56 +01002169 // On many journaling file systems there is a bug that causes both the
Bram Moolenaar473952e2019-09-28 16:30:04 +02002170 // original and the backup file to be lost when halting the system
2171 // right after writing the file. That's because only the meta-data is
2172 // journalled. Syncing the file slows down the system, but assures it
2173 // has been written to disk and we don't lose it.
2174 // For a device do try the fsync() but don't complain if it does not
2175 // work (could be a pipe).
2176 // If the 'fsync' option is FALSE, don't fsync(). Useful for laptops.
2177 if (p_fs && vim_fsync(fd) != 0 && !device)
2178 {
Bram Moolenaar460ae5d2022-01-01 14:19:49 +00002179 errmsg = (char_u *)_(e_fsync_failed);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002180 end = 0;
2181 }
2182#endif
2183
2184#if defined(HAVE_SELINUX) || defined(HAVE_SMACK)
2185 // Probably need to set the security context.
2186 if (!backup_copy)
2187 mch_copy_sec(backup, wfname);
2188#endif
2189
2190#ifdef UNIX
2191 // When creating a new file, set its owner/group to that of the
2192 // original file. Get the new device and inode number.
2193 if (backup != NULL && !backup_copy)
2194 {
2195# ifdef HAVE_FCHOWN
2196 stat_T st;
2197
2198 // Don't change the owner when it's already OK, some systems remove
2199 // permission or ACL stuff.
2200 if (mch_stat((char *)wfname, &st) < 0
2201 || st.st_uid != st_old.st_uid
2202 || st.st_gid != st_old.st_gid)
2203 {
2204 // changing owner might not be possible
2205 vim_ignored = fchown(fd, st_old.st_uid, -1);
2206 // if changing group fails clear the group permissions
2207 if (fchown(fd, -1, st_old.st_gid) == -1 && perm > 0)
2208 perm &= ~070;
2209 }
2210# endif
2211 buf_setino(buf);
2212 }
2213 else if (!buf->b_dev_valid)
2214 // Set the inode when creating a new file.
2215 buf_setino(buf);
2216#endif
2217
2218#ifdef UNIX
2219 if (made_writable)
2220 perm &= ~0200; // reset 'w' bit for security reasons
2221#endif
2222#ifdef HAVE_FCHMOD
2223 // set permission of new file same as old file
2224 if (perm >= 0)
2225 (void)mch_fsetperm(fd, perm);
2226#endif
2227 if (close(fd) != 0)
2228 {
Bram Moolenaarf1474d82021-12-31 19:59:55 +00002229 errmsg = (char_u *)_(e_close_failed);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002230 end = 0;
2231 }
2232
2233#ifndef HAVE_FCHMOD
2234 // set permission of new file same as old file
2235 if (perm >= 0)
2236 (void)mch_setperm(wfname, perm);
2237#endif
2238#ifdef HAVE_ACL
2239 // Probably need to set the ACL before changing the user (can't set the
2240 // ACL on a file the user doesn't own).
2241 // On Solaris, with ZFS and the aclmode property set to "discard" (the
2242 // default), chmod() discards all part of a file's ACL that don't
2243 // represent the mode of the file. It's non-trivial for us to discover
2244 // whether we're in that situation, so we simply always re-set the ACL.
2245# ifndef HAVE_SOLARIS_ZFS_ACL
2246 if (!backup_copy)
2247# endif
2248 mch_set_acl(wfname, acl);
2249#endif
2250#ifdef FEAT_CRYPT
2251 if (buf->b_cryptstate != NULL)
2252 {
2253 crypt_free_state(buf->b_cryptstate);
2254 buf->b_cryptstate = NULL;
2255 }
2256#endif
2257
2258#if defined(FEAT_EVAL)
2259 if (wfname != fname)
2260 {
2261 // The file was written to a temp file, now it needs to be
2262 // converted with 'charconvert' to (overwrite) the output file.
2263 if (end != 0)
2264 {
2265 if (eval_charconvert(enc_utf8 ? (char_u *)"utf-8" : p_enc,
2266 fenc, wfname, fname) == FAIL)
2267 {
2268 write_info.bw_conv_error = TRUE;
2269 end = 0;
2270 }
2271 }
2272 mch_remove(wfname);
2273 vim_free(wfname);
2274 }
2275#endif
2276 }
2277
2278 if (end == 0)
2279 {
2280 // Error encountered.
2281 if (errmsg == NULL)
2282 {
2283 if (write_info.bw_conv_error)
2284 {
2285 if (write_info.bw_conv_error_lnum == 0)
Bram Moolenaarf1474d82021-12-31 19:59:55 +00002286 errmsg = (char_u *)_(e_write_error_conversion_failed_make_fenc_empty_to_override);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002287 else
2288 {
2289 errmsg_allocated = TRUE;
2290 errmsg = alloc(300);
Bram Moolenaarf1474d82021-12-31 19:59:55 +00002291 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 +02002292 (long)write_info.bw_conv_error_lnum);
2293 }
2294 }
2295 else if (got_int)
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002296 errmsg = (char_u *)_(e_interrupted);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002297 else
Bram Moolenaarf1474d82021-12-31 19:59:55 +00002298 errmsg = (char_u *)_(e_write_error_file_system_full);
Bram Moolenaar473952e2019-09-28 16:30:04 +02002299 }
2300
2301 // If we have a backup file, try to put it in place of the new file,
2302 // because the new file is probably corrupt. This avoids losing the
2303 // original file when trying to make a backup when writing the file a
2304 // second time.
2305 // When "backup_copy" is set we need to copy the backup over the new
2306 // file. Otherwise rename the backup file.
2307 // If this is OK, don't give the extra warning message.
2308 if (backup != NULL)
2309 {
2310 if (backup_copy)
2311 {
2312 // This may take a while, if we were interrupted let the user
2313 // know we got the message.
2314 if (got_int)
2315 {
Bram Moolenaar436b5ad2021-12-31 22:49:24 +00002316 msg(_(e_interrupted));
Bram Moolenaar473952e2019-09-28 16:30:04 +02002317 out_flush();
2318 }
2319 if ((fd = mch_open((char *)backup, O_RDONLY | O_EXTRA, 0)) >= 0)
2320 {
2321 if ((write_info.bw_fd = mch_open((char *)fname,
2322 O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA,
2323 perm & 0777)) >= 0)
2324 {
2325 // copy the file.
2326 write_info.bw_buf = smallbuf;
2327 write_info.bw_flags = FIO_NOCONVERT;
2328 while ((write_info.bw_len = read_eintr(fd, smallbuf,
2329 SMALLBUFSIZE)) > 0)
2330 if (buf_write_bytes(&write_info) == FAIL)
2331 break;
2332
2333 if (close(write_info.bw_fd) >= 0
2334 && write_info.bw_len == 0)
2335 end = 1; // success
2336 }
2337 close(fd); // ignore errors for closing read file
2338 }
2339 }
2340 else
2341 {
2342 if (vim_rename(backup, fname) == 0)
2343 end = 1;
2344 }
2345 }
2346 goto fail;
2347 }
2348
2349 lnum -= start; // compute number of written lines
2350 --no_wait_return; // may wait for return now
2351
2352#if !(defined(UNIX) || defined(VMS))
2353 fname = sfname; // use shortname now, for the messages
2354#endif
2355 if (!filtering)
2356 {
2357 msg_add_fname(buf, fname); // put fname in IObuff with quotes
2358 c = FALSE;
2359 if (write_info.bw_conv_error)
2360 {
2361 STRCAT(IObuff, _(" CONVERSION ERROR"));
2362 c = TRUE;
2363 if (write_info.bw_conv_error_lnum != 0)
2364 vim_snprintf_add((char *)IObuff, IOSIZE, _(" in line %ld;"),
2365 (long)write_info.bw_conv_error_lnum);
2366 }
2367 else if (notconverted)
2368 {
2369 STRCAT(IObuff, _("[NOT converted]"));
2370 c = TRUE;
2371 }
2372 else if (converted)
2373 {
2374 STRCAT(IObuff, _("[converted]"));
2375 c = TRUE;
2376 }
2377 if (device)
2378 {
2379 STRCAT(IObuff, _("[Device]"));
2380 c = TRUE;
2381 }
2382 else if (newfile)
2383 {
Bram Moolenaar722e5052020-06-12 22:31:00 +02002384 STRCAT(IObuff, new_file_message());
Bram Moolenaar473952e2019-09-28 16:30:04 +02002385 c = TRUE;
2386 }
2387 if (no_eol)
2388 {
2389 msg_add_eol();
2390 c = TRUE;
2391 }
2392 // may add [unix/dos/mac]
2393 if (msg_add_fileformat(fileformat))
2394 c = TRUE;
2395#ifdef FEAT_CRYPT
2396 if (wb_flags & FIO_ENCRYPTED)
2397 {
2398 crypt_append_msg(buf);
2399 c = TRUE;
2400 }
2401#endif
2402 msg_add_lines(c, (long)lnum, nchars); // add line/char count
2403 if (!shortmess(SHM_WRITE))
2404 {
2405 if (append)
2406 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
2407 else
2408 STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
2409 }
2410
2411 set_keep_msg((char_u *)msg_trunc_attr((char *)IObuff, FALSE, 0), 0);
2412 }
2413
2414 // When written everything correctly: reset 'modified'. Unless not
2415 // writing to the original file and '+' is not in 'cpoptions'.
2416 if (reset_changed && whole && !append
2417 && !write_info.bw_conv_error
2418 && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL))
2419 {
2420 unchanged(buf, TRUE, FALSE);
Christian Brabandtdb3b4462021-10-16 11:58:55 +01002421 // b:changedtick may be incremented in unchanged() but that should not
2422 // trigger a TextChanged event.
Bram Moolenaar473952e2019-09-28 16:30:04 +02002423 if (buf->b_last_changedtick + 1 == CHANGEDTICK(buf))
2424 buf->b_last_changedtick = CHANGEDTICK(buf);
2425 u_unchanged(buf);
2426 u_update_save_nr(buf);
2427 }
2428
2429 // If written to the current file, update the timestamp of the swap file
2430 // and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
2431 if (overwriting)
2432 {
2433 ml_timestamp(buf);
2434 if (append)
2435 buf->b_flags &= ~BF_NEW;
2436 else
2437 buf->b_flags &= ~BF_WRITE_MASK;
2438 }
2439
2440 // If we kept a backup until now, and we are in patch mode, then we make
2441 // the backup file our 'original' file.
2442 if (*p_pm && dobackup)
2443 {
2444 char *org = (char *)buf_modname((buf->b_p_sn || buf->b_shortname),
2445 fname, p_pm, FALSE);
2446
2447 if (backup != NULL)
2448 {
2449 stat_T st;
2450
2451 // If the original file does not exist yet
2452 // the current backup file becomes the original file
2453 if (org == NULL)
Bram Moolenaar6d057012021-12-31 18:49:43 +00002454 emsg(_(e_patchmode_cant_save_original_file));
Bram Moolenaar473952e2019-09-28 16:30:04 +02002455 else if (mch_stat(org, &st) < 0)
2456 {
2457 vim_rename(backup, (char_u *)org);
2458 VIM_CLEAR(backup); // don't delete the file
2459#ifdef UNIX
2460 set_file_time((char_u *)org, st_old.st_atime, st_old.st_mtime);
2461#endif
2462 }
2463 }
2464 // If there is no backup file, remember that a (new) file was
2465 // created.
2466 else
2467 {
2468 int empty_fd;
2469
2470 if (org == NULL
2471 || (empty_fd = mch_open(org,
2472 O_CREAT | O_EXTRA | O_EXCL | O_NOFOLLOW,
2473 perm < 0 ? 0666 : (perm & 0777))) < 0)
Bram Moolenaar6d057012021-12-31 18:49:43 +00002474 emsg(_(e_patchmode_cant_touch_empty_original_file));
Bram Moolenaar473952e2019-09-28 16:30:04 +02002475 else
2476 close(empty_fd);
2477 }
2478 if (org != NULL)
2479 {
2480 mch_setperm((char_u *)org, mch_getperm(fname) & 0777);
2481 vim_free(org);
2482 }
2483 }
2484
2485 // Remove the backup unless 'backup' option is set or there was a
2486 // conversion error.
2487 if (!p_bk && backup != NULL && !write_info.bw_conv_error
2488 && mch_remove(backup) != 0)
Bram Moolenaar6d057012021-12-31 18:49:43 +00002489 emsg(_(e_cant_delete_backup_file));
Bram Moolenaar473952e2019-09-28 16:30:04 +02002490
2491 goto nofail;
2492
2493 // Finish up. We get here either after failure or success.
2494fail:
2495 --no_wait_return; // may wait for return now
2496nofail:
2497
2498 // Done saving, we accept changed buffer warnings again
2499 buf->b_saving = FALSE;
2500
2501 vim_free(backup);
2502 if (buffer != smallbuf)
2503 vim_free(buffer);
2504 vim_free(fenc_tofree);
2505 vim_free(write_info.bw_conv_buf);
2506#ifdef USE_ICONV
2507 if (write_info.bw_iconv_fd != (iconv_t)-1)
2508 {
2509 iconv_close(write_info.bw_iconv_fd);
2510 write_info.bw_iconv_fd = (iconv_t)-1;
2511 }
2512#endif
2513#ifdef HAVE_ACL
2514 mch_free_acl(acl);
2515#endif
2516
2517 if (errmsg != NULL)
2518 {
2519 int numlen = errnum != NULL ? (int)STRLEN(errnum) : 0;
2520
2521 attr = HL_ATTR(HLF_E); // set highlight for error messages
2522 msg_add_fname(buf,
2523#ifndef UNIX
2524 sfname
2525#else
2526 fname
2527#endif
2528 ); // put file name in IObuff with quotes
2529 if (STRLEN(IObuff) + STRLEN(errmsg) + numlen >= IOSIZE)
2530 IObuff[IOSIZE - STRLEN(errmsg) - numlen - 1] = NUL;
2531 // If the error message has the form "is ...", put the error number in
2532 // front of the file name.
2533 if (errnum != NULL)
2534 {
2535 STRMOVE(IObuff + numlen, IObuff);
2536 mch_memmove(IObuff, errnum, (size_t)numlen);
2537 }
2538 STRCAT(IObuff, errmsg);
2539 emsg((char *)IObuff);
2540 if (errmsg_allocated)
2541 vim_free(errmsg);
2542
2543 retval = FAIL;
2544 if (end == 0)
2545 {
2546 msg_puts_attr(_("\nWARNING: Original file may be lost or damaged\n"),
2547 attr | MSG_HIST);
2548 msg_puts_attr(_("don't quit the editor until the file is successfully written!"),
2549 attr | MSG_HIST);
2550
2551 // Update the timestamp to avoid an "overwrite changed file"
2552 // prompt when writing again.
2553 if (mch_stat((char *)fname, &st_old) >= 0)
2554 {
2555 buf_store_time(buf, &st_old, fname);
2556 buf->b_mtime_read = buf->b_mtime;
Leah Neukirchen0a7984a2021-10-14 21:27:55 +01002557 buf->b_mtime_read_ns = buf->b_mtime_ns;
Bram Moolenaar473952e2019-09-28 16:30:04 +02002558 }
2559 }
2560 }
2561 msg_scroll = msg_save;
2562
2563#ifdef FEAT_PERSISTENT_UNDO
2564 // When writing the whole file and 'undofile' is set, also write the undo
2565 // file.
2566 if (retval == OK && write_undo_file)
2567 {
2568 char_u hash[UNDO_HASH_SIZE];
2569
2570 sha256_finish(&sha_ctx, hash);
2571 u_write_undo(NULL, FALSE, buf, hash);
2572 }
2573#endif
2574
2575#ifdef FEAT_EVAL
2576 if (!should_abort(retval))
2577#else
2578 if (!got_int)
2579#endif
2580 {
2581 aco_save_T aco;
2582
2583 curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read
2584
2585 // Apply POST autocommands.
2586 // Careful: The autocommands may call buf_write() recursively!
2587 aucmd_prepbuf(&aco, buf);
2588
2589 if (append)
2590 apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
2591 FALSE, curbuf, eap);
2592 else if (filtering)
2593 apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
2594 FALSE, curbuf, eap);
2595 else if (reset_changed && whole)
2596 apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
2597 FALSE, curbuf, eap);
2598 else
2599 apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
2600 FALSE, curbuf, eap);
2601
2602 // restore curwin/curbuf and a few other things
2603 aucmd_restbuf(&aco);
2604
2605#ifdef FEAT_EVAL
2606 if (aborting()) // autocmds may abort script processing
2607 retval = FALSE;
2608#endif
2609 }
2610
Bram Moolenaar8e6be342020-11-23 22:01:26 +01002611#ifdef FEAT_VIMINFO
2612 // Make sure marks will be written out to the viminfo file later, even when
2613 // the file is new.
2614 curbuf->b_marks_read = TRUE;
2615#endif
2616
Bram Moolenaar473952e2019-09-28 16:30:04 +02002617 got_int |= prev_got_int;
2618
2619 return retval;
2620}