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