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