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