aboutsummaryrefslogtreecommitdiff
path: root/src/nvim/fileio.c
diff options
context:
space:
mode:
authorJosh Rahm <joshuarahm@gmail.com>2023-11-29 22:40:31 +0000
committerJosh Rahm <joshuarahm@gmail.com>2023-11-29 22:40:31 +0000
commit339e2d15cc26fe86988ea06468d912a46c8d6f29 (patch)
treea6167fc8fcfc6ae2dc102f57b2473858eac34063 /src/nvim/fileio.c
parent067dc73729267c0262438a6fdd66e586f8496946 (diff)
parent4a8bf24ac690004aedf5540fa440e788459e5e34 (diff)
downloadrneovim-339e2d15cc26fe86988ea06468d912a46c8d6f29.tar.gz
rneovim-339e2d15cc26fe86988ea06468d912a46c8d6f29.tar.bz2
rneovim-339e2d15cc26fe86988ea06468d912a46c8d6f29.zip
Merge remote-tracking branch 'upstream/master' into fix_repeatcmdline
Diffstat (limited to 'src/nvim/fileio.c')
-rw-r--r--src/nvim/fileio.c2422
1 files changed, 279 insertions, 2143 deletions
diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c
index 9da9d6199e..0bb664bcf5 100644
--- a/src/nvim/fileio.c
+++ b/src/nvim/fileio.c
@@ -1,6 +1,3 @@
-// This is an open source non-commercial project. Dear PVS-Studio, please check
-// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
-
// fileio.c: read from and write to a file
#include <assert.h>
@@ -10,13 +7,16 @@
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
+#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
+#include <sys/types.h>
+#include <time.h>
#include <uv.h>
#include "auto/config.h"
-#include "nvim/ascii.h"
+#include "nvim/ascii_defs.h"
#include "nvim/autocmd.h"
#include "nvim/buffer.h"
#include "nvim/buffer_defs.h"
@@ -27,19 +27,20 @@
#include "nvim/drawscreen.h"
#include "nvim/edit.h"
#include "nvim/eval.h"
-#include "nvim/ex_cmds.h"
+#include "nvim/ex_cmds_defs.h"
#include "nvim/ex_eval.h"
#include "nvim/fileio.h"
#include "nvim/fold.h"
+#include "nvim/func_attr.h"
#include "nvim/garray.h"
+#include "nvim/garray_defs.h"
#include "nvim/getchar.h"
#include "nvim/gettext.h"
#include "nvim/globals.h"
-#include "nvim/highlight_defs.h"
-#include "nvim/iconv.h"
-#include "nvim/input.h"
+#include "nvim/highlight.h"
+#include "nvim/iconv_defs.h"
#include "nvim/log.h"
-#include "nvim/macros.h"
+#include "nvim/macros_defs.h"
#include "nvim/mbyte.h"
#include "nvim/memfile.h"
#include "nvim/memline.h"
@@ -47,24 +48,30 @@
#include "nvim/message.h"
#include "nvim/move.h"
#include "nvim/option.h"
+#include "nvim/option_vars.h"
#include "nvim/optionstr.h"
+#include "nvim/os/fs.h"
#include "nvim/os/fs_defs.h"
#include "nvim/os/input.h"
#include "nvim/os/os.h"
#include "nvim/os/time.h"
#include "nvim/path.h"
-#include "nvim/pos.h"
+#include "nvim/pos_defs.h"
#include "nvim/regexp.h"
-#include "nvim/screen.h"
#include "nvim/sha256.h"
#include "nvim/shada.h"
+#include "nvim/state_defs.h"
#include "nvim/strings.h"
-#include "nvim/types.h"
+#include "nvim/types_defs.h"
#include "nvim/ui.h"
#include "nvim/undo.h"
-#include "nvim/vim.h"
+#include "nvim/vim_defs.h"
+
+#ifdef BACKSLASH_IN_FILENAME
+# include "nvim/charset.h"
+#endif
-#if defined(HAVE_FLOCK) && defined(HAVE_DIRFD)
+#ifdef HAVE_DIRFD_AND_FLOCK
# include <dirent.h>
# include <sys/file.h>
#endif
@@ -73,87 +80,48 @@
# include "nvim/charset.h"
#endif
-#define BUFSIZE 8192 // size of normal write buffer
-#define SMBUFSIZE 256 // size of emergency write buffer
-
// For compatibility with libuv < 1.20.0 (tested on 1.18.0)
#ifndef UV_FS_COPYFILE_FICLONE
# define UV_FS_COPYFILE_FICLONE 0
#endif
-#define HAS_BW_FLAGS
-enum {
- FIO_LATIN1 = 0x01, // convert Latin1
- FIO_UTF8 = 0x02, // convert UTF-8
- FIO_UCS2 = 0x04, // convert UCS-2
- FIO_UCS4 = 0x08, // convert UCS-4
- FIO_UTF16 = 0x10, // convert UTF-16
- FIO_ENDIAN_L = 0x80, // little endian
- FIO_NOCONVERT = 0x2000, // skip encoding conversion
- FIO_UCSBOM = 0x4000, // check for BOM at start of file
- FIO_ALL = -1, // allow all formats
-};
-
-// When converting, a read() or write() may leave some bytes to be converted
-// for the next call. The value is guessed...
-#define CONV_RESTLEN 30
-
-// We have to guess how much a sequence of bytes may expand when converting
-// with iconv() to be able to allocate a buffer.
-#define ICONV_MULT 8
-
-// Structure to pass arguments from buf_write() to buf_write_bytes().
-struct bw_info {
- int bw_fd; // file descriptor
- char *bw_buf; // buffer with data to be written
- int bw_len; // length of data
-#ifdef HAS_BW_FLAGS
- int bw_flags; // FIO_ flags
-#endif
- char_u bw_rest[CONV_RESTLEN]; // not converted bytes
- int bw_restlen; // nr of bytes in bw_rest[]
- int bw_first; // first write call
- char *bw_conv_buf; // buffer for writing converted chars
- size_t bw_conv_buflen; // size of bw_conv_buf
- int bw_conv_error; // set for conversion error
- linenr_T bw_conv_error_lnum; // first line with error or zero
- linenr_T bw_start_lnum; // line number at start of buffer
- iconv_t bw_iconv_fd; // descriptor for iconv() or -1
-};
-
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "fileio.c.generated.h"
#endif
-static char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
-static char e_no_matching_autocommands_for_buftype_str_buffer[]
- = N_("E676: No matching autocommands for buftype=%s buffer");
+static const char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
void filemess(buf_T *buf, char *name, char *s, int attr)
{
- int msg_scroll_save;
+ int prev_msg_col = msg_col;
if (msg_silent != 0) {
return;
}
- add_quoted_fname(IObuff, IOSIZE - 100, buf, (const char *)name);
+
+ add_quoted_fname(IObuff, IOSIZE - 100, buf, name);
+
// Avoid an over-long translation to cause trouble.
xstrlcat(IObuff, s, IOSIZE);
+
// For the first message may have to start a new line.
// For further ones overwrite the previous one, reset msg_scroll before
// calling filemess().
- msg_scroll_save = msg_scroll;
- if (shortmess(SHM_OVERALL) && !exiting && p_verbose == 0) {
+ int msg_scroll_save = msg_scroll;
+ if (shortmess(SHM_OVERALL) && !msg_listdo_overwrite && !exiting && p_verbose == 0) {
msg_scroll = false;
}
if (!msg_scroll) { // wait a bit when overwriting an error msg
- check_for_delay(false);
+ msg_check_for_delay(false);
}
msg_start();
+ if (prev_msg_col != 0 && msg_col == 0) {
+ msg_putchar('\r'); // overwrite any previous message.
+ }
msg_scroll = msg_scroll_save;
msg_scrolled_ign = true;
// may truncate the message to avoid a hit-return prompt
- msg_outtrans_attr(msg_may_trunc(false, IObuff), attr);
+ msg_outtrans(msg_may_trunc(false, IObuff), attr);
msg_clr_eos();
ui_flush();
msg_scrolled_ign = false;
@@ -188,6 +156,7 @@ void filemess(buf_T *buf, char *name, char *s, int attr)
int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
linenr_T lines_to_read, exarg_T *eap, int flags, bool silent)
{
+ int retval = FAIL; // jump to "theend" instead of returning
int fd = stdin_fd >= 0 ? stdin_fd : 0;
int newfile = (flags & READ_NEW);
int check_readonly;
@@ -207,7 +176,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
char *line_start = NULL; // init to shut up gcc
int wasempty; // buffer was empty before reading
colnr_T len;
- long size = 0;
+ ptrdiff_t size = 0;
uint8_t *p = NULL;
off_T filesize = 0;
bool skip_read = false;
@@ -217,7 +186,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
linenr_T linecnt;
bool error = false; // errors encountered
int ff_error = EOL_UNKNOWN; // file format with errors
- long linerest = 0; // remaining chars in line
+ ptrdiff_t linerest = 0; // remaining chars in line
int perm = 0;
#ifdef UNIX
int swap_mode = -1; // protection bits for swap file
@@ -245,7 +214,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
bool fenc_alloced; // fenc_next is in allocated memory
char *fenc_next = NULL; // next item in 'fencs' or NULL
bool advance_fenc = false;
- long real_size = 0;
+ int real_size = 0;
iconv_t iconv_fd = (iconv_t)-1; // descriptor for iconv() or -1
bool did_iconv = false; // true when iconv() failed and trying
// 'charconvert' next
@@ -275,7 +244,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
&& vim_strchr(p_cpo, CPO_FNAMER) != NULL
&& !(flags & READ_DUMMY)) {
if (set_rw_fname(fname, sfname) == FAIL) {
- return FAIL;
+ goto theend;
}
}
@@ -319,10 +288,9 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
if (newfile) {
if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
false, curbuf, eap)) {
- int status = OK;
-
+ retval = OK;
if (aborting()) {
- status = FAIL;
+ retval = FAIL;
}
// The BufReadCmd code usually uses ":read" to get the text and
@@ -330,14 +298,15 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
// consider this to work like ":edit", thus reset the
// BF_NOTEDITED flag. Then ":write" will work to overwrite the
// same file.
- if (status == OK) {
+ if (retval == OK) {
curbuf->b_flags &= ~BF_NOTEDITED;
}
- return status;
+ goto theend;
}
} else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
false, NULL, eap)) {
- return aborting() ? FAIL : OK;
+ retval = aborting() ? FAIL : OK;
+ goto theend;
}
curbuf->b_op_start = orig_start;
@@ -345,11 +314,12 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
if (flags & READ_NOFILE) {
// Return NOTDONE instead of FAIL so that BufEnter can be triggered
// and other operations don't fail.
- return NOTDONE;
+ retval = NOTDONE;
+ goto theend;
}
}
- if ((shortmess(SHM_OVER) || curbuf->b_help) && p_verbose == 0) {
+ if (((shortmess(SHM_OVER) && !msg_listdo_overwrite) || curbuf->b_help) && p_verbose == 0) {
msg_scroll = false; // overwrite previous file message
} else {
msg_scroll = true; // don't overwrite previous file message
@@ -363,7 +333,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
filemess(curbuf, fname, _("Illegal file name"), 0);
msg_end();
msg_scroll = msg_save;
- return FAIL;
+ goto theend;
}
// If the name ends in a path separator, we can't open it. Check here,
@@ -375,7 +345,8 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
}
msg_end();
msg_scroll = msg_save;
- return NOTDONE;
+ retval = NOTDONE;
+ goto theend;
}
}
@@ -383,24 +354,30 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
perm = os_getperm(fname);
// On Unix it is possible to read a directory, so we have to
// check for it before os_open().
+
+#ifdef OPEN_CHR_FILES
+# define IS_CHR_DEV(perm, fname) S_ISCHR(perm) && is_dev_fd_file(fname)
+#else
+# define IS_CHR_DEV(perm, fname) false
+#endif
+
if (perm >= 0 && !S_ISREG(perm) // not a regular file ...
&& !S_ISFIFO(perm) // ... or fifo
&& !S_ISSOCK(perm) // ... or socket
-#ifdef OPEN_CHR_FILES
- && !(S_ISCHR(perm) && is_dev_fd_file(fname))
+ && !(IS_CHR_DEV(perm, fname))
// ... or a character special file named /dev/fd/<n>
-#endif
) {
if (S_ISDIR(perm)) {
if (!silent) {
filemess(curbuf, fname, _(msg_is_a_directory), 0);
}
+ retval = NOTDONE;
} else {
filemess(curbuf, fname, _("is not a file"), 0);
}
msg_end();
msg_scroll = msg_save;
- return S_ISDIR(perm) ? NOTDONE : FAIL;
+ goto theend;
}
}
@@ -461,7 +438,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
if (fd < 0) { // cannot open at all
msg_scroll = msg_save;
if (!newfile) {
- return FAIL;
+ goto theend;
}
if (perm == UV_ENOENT) { // check if the file exists
// Set the 'new-file' flag, so that when the file has
@@ -480,12 +457,12 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
|| (using_b_fname
&& (old_b_fname != curbuf->b_fname))) {
emsg(_(e_auchangedbuf));
- return FAIL;
+ goto theend;
}
}
if (!silent) {
if (dir_of_file_exists(fname)) {
- filemess(curbuf, sfname, new_file_message(), 0);
+ filemess(curbuf, sfname, _("[New]"), 0);
} else {
filemess(curbuf, sfname, _("[New DIRECTORY]"), 0);
}
@@ -502,23 +479,27 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
// remember the current fileformat
save_file_ff(curbuf);
- if (aborting()) { // autocmds may abort script processing
- return FAIL;
+ if (!aborting()) { // autocmds may abort script processing
+ retval = OK; // a new file is not an error
}
- return OK; // a new file is not an error
+ goto theend;
}
- filemess(curbuf, sfname, ((fd == UV_EFBIG) ? _("[File too big]") :
#if defined(UNIX) && defined(EOVERFLOW)
+ filemess(curbuf, sfname, ((fd == UV_EFBIG) ? _("[File too big]")
+ :
// libuv only returns -errno
// in Unix and in Windows
// open() does not set
// EOVERFLOW
- (fd == -EOVERFLOW) ? _("[File too big]") :
+ (fd == -EOVERFLOW) ? _("[File too big]")
+ : _("[Permission Denied]")), 0);
+#else
+ filemess(curbuf, sfname, ((fd == UV_EFBIG) ? _("[File too big]")
+ : _("[Permission Denied]")), 0);
#endif
- _("[Permission Denied]")), 0);
curbuf->b_p_ro = true; // must use "w!" now
- return FAIL;
+ goto theend;
}
// Only set the 'ro' flag for readonly files the first time they are
@@ -553,13 +534,13 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
if (!read_buffer) {
close(fd);
}
- return FAIL;
+ goto theend;
}
#ifdef UNIX
// Set swap file protection bits after creating it.
if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
&& curbuf->b_ml.ml_mfp->mf_fname != NULL) {
- const char *swap_fname = (const char *)curbuf->b_ml.ml_mfp->mf_fname;
+ const char *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
// If the group-read bit is set but not the world-read bit, then
// the group must be equal to the group of the original file. If
@@ -588,7 +569,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
if (!read_buffer && !read_stdin) {
close(fd);
}
- return FAIL;
+ goto theend;
}
no_wait_return++; // don't wait for return yet
@@ -644,7 +625,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
no_wait_return--;
msg_scroll = msg_save;
curbuf->b_p_ro = true; // must use "w!" now
- return FAIL;
+ goto theend;
}
// Don't allow the autocommands to change the current buffer.
// Try to re-open the file.
@@ -663,7 +644,7 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
emsg(_("E201: *ReadPre autocommands must not change current buffer"));
}
curbuf->b_p_ro = true; // must use "w!" now
- return FAIL;
+ goto theend;
}
}
@@ -740,7 +721,7 @@ retry:
if (read_buffer) {
read_buf_lnum = 1;
read_buf_col = 0;
- } else if (read_stdin || vim_lseek(fd, (off_T)0L, SEEK_SET) != 0) {
+ } else if (read_stdin || vim_lseek(fd, 0, SEEK_SET) != 0) {
// Can't rewind the file, give up.
error = true;
goto failed;
@@ -902,9 +883,9 @@ retry:
// Use buffer >= 64K. Add linerest to double the size if the
// line gets very long, to avoid a lot of copying. But don't
// read more than 1 Mbyte at a time, so we can be interrupted.
- size = 0x10000L + linerest;
- if (size > 0x100000L) {
- size = 0x100000L;
+ size = 0x10000 + linerest;
+ if (size > 0x100000) {
+ size = 0x100000;
}
}
@@ -957,7 +938,7 @@ retry:
if (conv_restlen > 0) {
// Insert unconverted bytes from previous line.
- memmove(ptr, conv_rest, (size_t)conv_restlen); // -V614
+ memmove(ptr, conv_rest, (size_t)conv_restlen);
ptr += conv_restlen;
size -= conv_restlen;
}
@@ -968,14 +949,12 @@ retry:
if (read_buf_lnum > from) {
size = 0;
} else {
- int n, ni;
- long tlen;
-
- tlen = 0;
- for (;;) {
- p = (char_u *)ml_get(read_buf_lnum) + read_buf_col;
- n = (int)strlen((char *)p);
- if ((int)tlen + n + 1 > size) {
+ int ni;
+ int tlen = 0;
+ while (true) {
+ p = (uint8_t *)ml_get(read_buf_lnum) + read_buf_col;
+ int n = (int)strlen((char *)p);
+ if (tlen + n + 1 > size) {
// Filled up to "size", append partial line.
// Change NL to NUL to reverse the effect done
// below.
@@ -1015,7 +994,8 @@ retry:
}
} else {
// Read bytes from the file.
- size = read_eintr(fd, ptr, (size_t)size);
+ size_t read_size = (size_t)size;
+ size = read_eintr(fd, ptr, read_size);
}
if (size <= 0) {
@@ -1081,7 +1061,7 @@ retry:
if (size < 2 || curbuf->b_p_bin) {
ccname = NULL;
} else {
- ccname = check_for_bom(ptr, size, &blen,
+ ccname = check_for_bom(ptr, (int)size, &blen,
fio_flags == FIO_UCSBOM ? FIO_ALL : get_fio_flags(fenc));
}
if (ccname != NULL) {
@@ -1170,7 +1150,7 @@ retry:
}
if (fio_flags != 0) {
- unsigned int u8c;
+ unsigned u8c;
char *dest;
char *tail = NULL;
@@ -1349,7 +1329,6 @@ retry:
// Reading UTF-8: Check if the bytes are valid UTF-8.
for (p = (uint8_t *)ptr;; p++) {
int todo = (int)(((uint8_t *)ptr + size) - p);
- int l;
if (todo <= 0) {
break;
@@ -1359,7 +1338,7 @@ retry:
// an incomplete character at the end though, the next
// read() will get the next bytes, we'll check it
// then.
- l = utf_ptr2len_len((char *)p, todo);
+ int l = utf_ptr2len_len((char *)p, todo);
if (l > todo && !incomplete_tail) {
// Avoid retrying with a different encoding when
// a truncated file is more likely, or attempting
@@ -1554,7 +1533,7 @@ rewind_retry:
if (try_unix
&& !read_stdin
&& (read_buffer
- || vim_lseek(fd, (off_T)0L, SEEK_SET) == 0)) {
+ || vim_lseek(fd, 0, SEEK_SET) == 0)) {
fileformat = EOL_UNIX;
if (set_options) {
set_fileformat(EOL_UNIX, OPT_LOCAL);
@@ -1713,50 +1692,51 @@ failed:
}
msg_scroll = msg_save;
check_marks_read();
- return OK; // an interrupt isn't really an error
+ retval = OK; // an interrupt isn't really an error
+ goto theend;
}
if (!filtering && !(flags & READ_DUMMY) && !silent) {
- add_quoted_fname(IObuff, IOSIZE, curbuf, (const char *)sfname);
+ add_quoted_fname(IObuff, IOSIZE, curbuf, sfname);
c = false;
#ifdef UNIX
if (S_ISFIFO(perm)) { // fifo
- STRCAT(IObuff, _("[fifo]"));
+ xstrlcat(IObuff, _("[fifo]"), IOSIZE);
c = true;
}
if (S_ISSOCK(perm)) { // or socket
- STRCAT(IObuff, _("[socket]"));
+ xstrlcat(IObuff, _("[socket]"), IOSIZE);
c = true;
}
# ifdef OPEN_CHR_FILES
if (S_ISCHR(perm)) { // or character special
- STRCAT(IObuff, _("[character special]"));
+ xstrlcat(IObuff, _("[character special]"), IOSIZE);
c = true;
}
# endif
#endif
if (curbuf->b_p_ro) {
- STRCAT(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"));
+ xstrlcat(IObuff, shortmess(SHM_RO) ? _("[RO]") : _("[readonly]"), IOSIZE);
c = true;
}
if (read_no_eol_lnum) {
- msg_add_eol();
+ xstrlcat(IObuff, _("[noeol]"), IOSIZE);
c = true;
}
if (ff_error == EOL_DOS) {
- STRCAT(IObuff, _("[CR missing]"));
+ xstrlcat(IObuff, _("[CR missing]"), IOSIZE);
c = true;
}
if (split) {
- STRCAT(IObuff, _("[long lines split]"));
+ xstrlcat(IObuff, _("[long lines split]"), IOSIZE);
c = true;
}
if (notconverted) {
- STRCAT(IObuff, _("[NOT converted]"));
+ xstrlcat(IObuff, _("[NOT converted]"), IOSIZE);
c = true;
} else if (converted) {
- STRCAT(IObuff, _("[converted]"));
+ xstrlcat(IObuff, _("[converted]"), IOSIZE);
c = true;
}
if (conv_error != 0) {
@@ -1768,21 +1748,24 @@ failed:
_("[ILLEGAL BYTE in line %" PRId64 "]"), (int64_t)illegal_byte);
c = true;
} else if (error) {
- STRCAT(IObuff, _("[READ ERRORS]"));
+ xstrlcat(IObuff, _("[READ ERRORS]"), IOSIZE);
c = true;
}
if (msg_add_fileformat(fileformat)) {
c = true;
}
- msg_add_lines(c, (long)linecnt, filesize);
+ msg_add_lines(c, linecnt, filesize);
XFREE_CLEAR(keep_msg);
p = NULL;
msg_scrolled_ign = true;
if (!read_stdin && !read_buffer) {
- p = (char_u *)msg_trunc_attr(IObuff, false, 0);
+ if (msg_col > 0) {
+ msg_putchar('\r'); // overwrite previous message
+ }
+ p = (uint8_t *)msg_trunc(IObuff, false, 0);
}
if (read_stdin || read_buffer || restart_edit != 0
@@ -1804,7 +1787,7 @@ failed:
curbuf->b_p_ro = true;
}
- u_clearline(); // cannot use "U" command after adding lines
+ u_clearline(curbuf); // cannot use "U" command after adding lines
// In Ex mode: cursor at last new line.
// Otherwise: cursor at first new line.
@@ -1813,7 +1796,7 @@ failed:
} else {
curwin->w_cursor.lnum = from + 1;
}
- check_cursor_lnum();
+ check_cursor_lnum(curwin);
beginline(BL_WHITE | BL_FIX); // on first non-blank
if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
@@ -1843,7 +1826,7 @@ failed:
// When opening a new file locate undo info and read it.
if (read_undo_file) {
- char_u hash[UNDO_HASH_SIZE];
+ uint8_t hash[UNDO_HASH_SIZE];
sha256_finish(&sha_ctx, hash);
u_read_undo(NULL, hash, fname);
@@ -1886,10 +1869,18 @@ failed:
}
}
- if (recoverymode && error) {
- return FAIL;
+ if (!(recoverymode && error)) {
+ retval = OK;
}
- return OK;
+
+theend:
+ if (curbuf->b_ml.ml_mfp != NULL
+ && curbuf->b_ml.ml_mfp->mf_dirty == MF_DIRTY_YES_NOSYNC) {
+ // OK to sync the swap file now
+ curbuf->b_ml.ml_mfp->mf_dirty = MF_DIRTY_YES;
+ }
+
+ return retval;
}
#ifdef OPEN_CHR_FILES
@@ -1919,11 +1910,8 @@ bool is_dev_fd_file(char *fname)
/// @param endp end of more bytes read
static linenr_T readfile_linenr(linenr_T linecnt, char *p, const char *endp)
{
- char *s;
- linenr_T lnum;
-
- lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
- for (s = p; s < endp; s++) {
+ linenr_T lnum = curbuf->b_ml.ml_line_count - linecnt + 1;
+ for (char *s = p; s < endp; s++) {
if (*s == '\n') {
lnum++;
}
@@ -1991,7 +1979,6 @@ void set_forced_fenc(exarg_T *eap)
static char *next_fenc(char **pp, bool *alloced)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET
{
- char *p;
char *r;
*alloced = false;
@@ -1999,12 +1986,12 @@ static char *next_fenc(char **pp, bool *alloced)
*pp = NULL;
return "";
}
- p = vim_strchr(*pp, ',');
+ char *p = vim_strchr(*pp, ',');
if (p == NULL) {
r = enc_canonize(*pp);
*pp += strlen(*pp);
} else {
- r = xstrnsave(*pp, (size_t)(p - *pp));
+ r = xmemdupz(*pp, (size_t)(p - *pp));
*pp = p + 1;
p = enc_canonize(r);
xfree(r);
@@ -2026,10 +2013,9 @@ static char *next_fenc(char **pp, bool *alloced)
/// Returns NULL if the conversion failed ("*fdp" is not set) .
static char *readfile_charconvert(char *fname, char *fenc, int *fdp)
{
- char *tmpname;
char *errmsg = NULL;
- tmpname = vim_tempname();
+ char *tmpname = vim_tempname();
if (tmpname == NULL) {
errmsg = _("Can't find temp file for conversion");
} else {
@@ -2047,7 +2033,7 @@ static char *readfile_charconvert(char *fname, char *fenc, int *fdp)
if (errmsg != NULL) {
// Don't use emsg(), it breaks mappings, the retry with
// another type of conversion might still work.
- msg(errmsg);
+ msg(errmsg, 0);
if (tmpname != NULL) {
os_remove(tmpname); // delete converted file
XFREE_CLEAR(tmpname);
@@ -2076,1530 +2062,9 @@ static void check_marks_read(void)
curbuf->b_marks_read = true;
}
-char *new_file_message(void)
-{
- return shortmess(SHM_NEW) ? _("[New]") : _("[New File]");
-}
-
-/// buf_write() - write to file "fname" lines "start" through "end"
-///
-/// We do our own buffering here because fwrite() is so slow.
-///
-/// If "forceit" is true, we don't care for errors when attempting backups.
-/// In case of an error everything possible is done to restore the original
-/// file. But when "forceit" is true, we risk losing it.
-///
-/// When "reset_changed" is true and "append" == false and "start" == 1 and
-/// "end" == curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
-///
-/// This function must NOT use NameBuff (because it's called by autowrite()).
-///
-///
-/// @param eap for forced 'ff' and 'fenc', can be NULL!
-/// @param append append to the file
-///
-/// @return FAIL for failure, OK otherwise
-int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T end, exarg_T *eap,
- int append, int forceit, int reset_changed, int filtering)
-{
- int fd;
- char *backup = NULL;
- int backup_copy = false; // copy the original file?
- int dobackup;
- char *ffname;
- char *wfname = NULL; // name of file to write to
- char *s;
- char *ptr;
- char c;
- int len;
- linenr_T lnum;
- long nchars;
-#define SET_ERRMSG_NUM(num, msg) \
- errnum = (num), errmsg = (msg), errmsgarg = 0
-#define SET_ERRMSG_ARG(msg, error) \
- errnum = NULL, errmsg = (msg), errmsgarg = error
-#define SET_ERRMSG(msg) \
- errnum = NULL, errmsg = (msg), errmsgarg = 0
- const char *errnum = NULL;
- char *errmsg = NULL;
- int errmsgarg = 0;
- bool errmsg_allocated = false;
- char *buffer;
- char smallbuf[SMBUFSIZE];
- char *backup_ext;
- int bufsize;
- long perm; // file permissions
- int retval = OK;
- int newfile = false; // true if file doesn't exist yet
- int msg_save = msg_scroll;
- int overwriting; // true if writing over original
- int no_eol = false; // no end-of-line written
- int device = false; // writing to a device
- int prev_got_int = got_int;
- int checking_conversion;
- bool file_readonly = false; // overwritten file is read-only
- static char *err_readonly =
- "is read-only (cannot override: \"W\" in 'cpoptions')";
-#if defined(UNIX)
- int made_writable = false; // 'w' bit has been set
-#endif
- // writing everything
- int whole = (start == 1 && end == buf->b_ml.ml_line_count);
- linenr_T old_line_count = buf->b_ml.ml_line_count;
- int fileformat;
- int write_bin;
- struct bw_info write_info; // info for buf_write_bytes()
- int converted = false;
- int notconverted = false;
- char *fenc; // effective 'fileencoding'
- char *fenc_tofree = NULL; // allocated "fenc"
-#ifdef HAS_BW_FLAGS
- int wb_flags = 0;
-#endif
-#ifdef HAVE_ACL
- vim_acl_T acl = NULL; // ACL copied from original file to
- // backup or new file
-#endif
- int write_undo_file = false;
- context_sha256_T sha_ctx;
- unsigned int bkc = get_bkc_value(buf);
- const pos_T orig_start = buf->b_op_start;
- const pos_T orig_end = buf->b_op_end;
-
- if (fname == NULL || *fname == NUL) { // safety check
- return FAIL;
- }
- if (buf->b_ml.ml_mfp == NULL) {
- // This can happen during startup when there is a stray "w" in the
- // vimrc file.
- emsg(_(e_emptybuf));
- return FAIL;
- }
-
- // Disallow writing in secure mode.
- if (check_secure()) {
- return FAIL;
- }
-
- // Avoid a crash for a long name.
- if (strlen(fname) >= MAXPATHL) {
- emsg(_(e_longname));
- return FAIL;
- }
-
- // must init bw_conv_buf and bw_iconv_fd before jumping to "fail"
- write_info.bw_conv_buf = NULL;
- write_info.bw_conv_error = false;
- write_info.bw_conv_error_lnum = 0;
- write_info.bw_restlen = 0;
- write_info.bw_iconv_fd = (iconv_t)-1;
-
- // After writing a file changedtick changes but we don't want to display
- // the line.
- ex_no_reprint = true;
-
- // If there is no file name yet, use the one for the written file.
- // BF_NOTEDITED is set to reflect this (in case the write fails).
- // Don't do this when the write is for a filter command.
- // Don't do this when appending.
- // Only do this when 'cpoptions' contains the 'F' flag.
- if (buf->b_ffname == NULL
- && reset_changed
- && whole
- && buf == curbuf
- && !bt_nofilename(buf)
- && !filtering
- && (!append || vim_strchr(p_cpo, CPO_FNAMEAPP) != NULL)
- && vim_strchr(p_cpo, CPO_FNAMEW) != NULL) {
- if (set_rw_fname(fname, sfname) == FAIL) {
- return FAIL;
- }
- buf = curbuf; // just in case autocmds made "buf" invalid
- }
-
- if (sfname == NULL) {
- sfname = fname;
- }
-
- // For Unix: Use the short file name whenever possible.
- // Avoids problems with networks and when directory names are changed.
- // Don't do this for Windows, a "cd" in a sub-shell may have moved us to
- // another directory, which we don't detect.
- ffname = fname; // remember full fname
-#ifdef UNIX
- fname = sfname;
-#endif
-
- if (buf->b_ffname != NULL && path_fnamecmp(ffname, buf->b_ffname) == 0) {
- overwriting = true;
- } else {
- overwriting = false;
- }
-
- no_wait_return++; // don't wait for return yet
-
- // Set '[ and '] marks to the lines to be written.
- buf->b_op_start.lnum = start;
- buf->b_op_start.col = 0;
- buf->b_op_end.lnum = end;
- buf->b_op_end.col = 0;
-
- {
- aco_save_T aco;
- int buf_ffname = false;
- int buf_sfname = false;
- int buf_fname_f = false;
- int buf_fname_s = false;
- int did_cmd = false;
- int nofile_err = false;
- int empty_memline = (buf->b_ml.ml_mfp == NULL);
- bufref_T bufref;
-
- // Apply PRE autocommands.
- // Set curbuf to the buffer to be written.
- // Careful: The autocommands may call buf_write() recursively!
- if (ffname == buf->b_ffname) {
- buf_ffname = true;
- }
- if (sfname == buf->b_sfname) {
- buf_sfname = true;
- }
- if (fname == buf->b_ffname) {
- buf_fname_f = true;
- }
- if (fname == buf->b_sfname) {
- buf_fname_s = true;
- }
-
- // Set curwin/curbuf to buf and save a few things.
- aucmd_prepbuf(&aco, buf);
- set_bufref(&bufref, buf);
-
- if (append) {
- if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD,
- sfname, sfname, false, curbuf, eap))) {
- if (overwriting && bt_nofilename(curbuf)) {
- nofile_err = true;
- } else {
- apply_autocmds_exarg(EVENT_FILEAPPENDPRE,
- sfname, sfname, false, curbuf, eap);
- }
- }
- } else if (filtering) {
- apply_autocmds_exarg(EVENT_FILTERWRITEPRE,
- NULL, sfname, false, curbuf, eap);
- } else if (reset_changed && whole) {
- int was_changed = curbufIsChanged();
-
- did_cmd = apply_autocmds_exarg(EVENT_BUFWRITECMD,
- sfname, sfname, false, curbuf, eap);
- if (did_cmd) {
- if (was_changed && !curbufIsChanged()) {
- // Written everything correctly and BufWriteCmd has reset
- // 'modified': Correct the undo information so that an
- // undo now sets 'modified'.
- u_unchanged(curbuf);
- u_update_save_nr(curbuf);
- }
- } else {
- if (overwriting && bt_nofilename(curbuf)) {
- nofile_err = true;
- } else {
- apply_autocmds_exarg(EVENT_BUFWRITEPRE,
- sfname, sfname, false, curbuf, eap);
- }
- }
- } else {
- if (!(did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD,
- sfname, sfname, false, curbuf, eap))) {
- if (overwriting && bt_nofilename(curbuf)) {
- nofile_err = true;
- } else {
- apply_autocmds_exarg(EVENT_FILEWRITEPRE,
- sfname, sfname, false, curbuf, eap);
- }
- }
- }
-
- // restore curwin/curbuf and a few other things
- aucmd_restbuf(&aco);
-
- // In three situations we return here and don't write the file:
- // 1. the autocommands deleted or unloaded the buffer.
- // 2. The autocommands abort script processing.
- // 3. If one of the "Cmd" autocommands was executed.
- if (!bufref_valid(&bufref)) {
- buf = NULL;
- }
- if (buf == NULL || (buf->b_ml.ml_mfp == NULL && !empty_memline)
- || did_cmd || nofile_err
- || aborting()) {
- if (buf != NULL && (cmdmod.cmod_flags & CMOD_LOCKMARKS)) {
- // restore the original '[ and '] positions
- buf->b_op_start = orig_start;
- buf->b_op_end = orig_end;
- }
-
- no_wait_return--;
- msg_scroll = msg_save;
- if (nofile_err) {
- semsg(_(e_no_matching_autocommands_for_buftype_str_buffer), curbuf->b_p_bt);
- }
-
- if (nofile_err
- || aborting()) {
- // An aborting error, interrupt or exception in the
- // autocommands.
- return FAIL;
- }
- if (did_cmd) {
- if (buf == NULL) {
- // The buffer was deleted. We assume it was written
- // (can't retry anyway).
- return OK;
- }
- if (overwriting) {
- // Assume the buffer was written, update the timestamp.
- ml_timestamp(buf);
- if (append) {
- buf->b_flags &= ~BF_NEW;
- } else {
- buf->b_flags &= ~BF_WRITE_MASK;
- }
- }
- if (reset_changed && buf->b_changed && !append
- && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)) {
- // Buffer still changed, the autocommands didn't work properly.
- return FAIL;
- }
- return OK;
- }
- if (!aborting()) {
- emsg(_("E203: Autocommands deleted or unloaded buffer to be written"));
- }
- return FAIL;
- }
-
- // The autocommands may have changed the number of lines in the file.
- // When writing the whole file, adjust the end.
- // When writing part of the file, assume that the autocommands only
- // changed the number of lines that are to be written (tricky!).
- if (buf->b_ml.ml_line_count != old_line_count) {
- if (whole) { // write all
- end = buf->b_ml.ml_line_count;
- } else if (buf->b_ml.ml_line_count > old_line_count) { // more lines
- end += buf->b_ml.ml_line_count - old_line_count;
- } else { // less lines
- end -= old_line_count - buf->b_ml.ml_line_count;
- if (end < start) {
- no_wait_return--;
- msg_scroll = msg_save;
- emsg(_("E204: Autocommand changed number of lines in unexpected way"));
- return FAIL;
- }
- }
- }
-
- // The autocommands may have changed the name of the buffer, which may
- // be kept in fname, ffname and sfname.
- if (buf_ffname) {
- ffname = buf->b_ffname;
- }
- if (buf_sfname) {
- sfname = buf->b_sfname;
- }
- if (buf_fname_f) {
- fname = buf->b_ffname;
- }
- if (buf_fname_s) {
- fname = buf->b_sfname;
- }
- }
-
- if (cmdmod.cmod_flags & CMOD_LOCKMARKS) {
- // restore the original '[ and '] positions
- buf->b_op_start = orig_start;
- buf->b_op_end = orig_end;
- }
-
- if (shortmess(SHM_OVER) && !exiting) {
- msg_scroll = false; // overwrite previous file message
- } else {
- msg_scroll = true; // don't overwrite previous file message
- }
- if (!filtering) {
- filemess(buf,
-#ifndef UNIX
- sfname,
-#else
- fname,
-#endif
- "", 0); // show that we are busy
- }
- msg_scroll = false; // always overwrite the file message now
-
- buffer = verbose_try_malloc(BUFSIZE);
- // can't allocate big buffer, use small one (to be able to write when out of
- // memory)
- if (buffer == NULL) {
- buffer = smallbuf;
- bufsize = SMBUFSIZE;
- } else {
- bufsize = BUFSIZE;
- }
-
- // Get information about original file (if there is one).
- FileInfo file_info_old;
-#if defined(UNIX)
- perm = -1;
- if (!os_fileinfo(fname, &file_info_old)) {
- newfile = true;
- } else {
- perm = (long)file_info_old.stat.st_mode;
- if (!S_ISREG(file_info_old.stat.st_mode)) { // not a file
- if (S_ISDIR(file_info_old.stat.st_mode)) {
- SET_ERRMSG_NUM("E502", _("is a directory"));
- goto fail;
- }
- if (os_nodetype(fname) != NODE_WRITABLE) {
- SET_ERRMSG_NUM("E503", _("is not a file or writable device"));
- goto fail;
- }
- // It's a device of some kind (or a fifo) which we can write to
- // but for which we can't make a backup.
- device = true;
- newfile = true;
- perm = -1;
- }
- }
-#else // win32
- // Check for a writable device name.
- c = fname == NULL ? NODE_OTHER : os_nodetype(fname);
- if (c == NODE_OTHER) {
- SET_ERRMSG_NUM("E503", _("is not a file or writable device"));
- goto fail;
- }
- if (c == NODE_WRITABLE) {
- device = true;
- newfile = true;
- perm = -1;
- } else {
- perm = os_getperm((const char *)fname);
- if (perm < 0) {
- newfile = true;
- } else if (os_isdir(fname)) {
- SET_ERRMSG_NUM("E502", _("is a directory"));
- goto fail;
- }
- if (overwriting) {
- os_fileinfo(fname, &file_info_old);
- }
- }
-#endif // !UNIX
-
- if (!device && !newfile) {
- // Check if the file is really writable (when renaming the file to
- // make a backup we won't discover it later).
- file_readonly = !os_file_is_writable(fname);
-
- if (!forceit && file_readonly) {
- if (vim_strchr(p_cpo, CPO_FWRITE) != NULL) {
- SET_ERRMSG_NUM("E504", _(err_readonly));
- } else {
- SET_ERRMSG_NUM("E505", _("is read-only (add ! to override)"));
- }
- goto fail;
- }
-
- // If 'forceit' is false, check if the timestamp hasn't changed since reading the file.
- if (overwriting && !forceit) {
- retval = check_mtime(buf, &file_info_old);
- if (retval == FAIL) {
- goto fail;
- }
- }
- }
-
-#ifdef HAVE_ACL
- // For systems that support ACL: get the ACL from the original file.
- if (!newfile) {
- acl = os_get_acl(fname);
- }
-#endif
-
- // If 'backupskip' is not empty, don't make a backup for some files.
- dobackup = (p_wb || p_bk || *p_pm != NUL);
- if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname)) {
- dobackup = false;
- }
-
- // Save the value of got_int and reset it. We don't want a previous
- // interruption cancel writing, only hitting CTRL-C while writing should
- // abort it.
- prev_got_int = got_int;
- got_int = false;
-
- // Mark the buffer as 'being saved' to prevent changed buffer warnings
- buf->b_saving = true;
-
- // If we are not appending or filtering, the file exists, and the
- // 'writebackup', 'backup' or 'patchmode' option is set, need a backup.
- // When 'patchmode' is set also make a backup when appending.
- //
- // Do not make any backup, if 'writebackup' and 'backup' are both switched
- // off. This helps when editing large files on almost-full disks.
- if (!(append && *p_pm == NUL) && !filtering && perm >= 0 && dobackup) {
- FileInfo file_info;
- const bool no_prepend_dot = false;
-
- if ((bkc & BKC_YES) || append) { // "yes"
- backup_copy = true;
- } else if ((bkc & BKC_AUTO)) { // "auto"
- int i;
-
- // Don't rename the file when:
- // - it's a hard link
- // - it's a symbolic link
- // - we don't have write permission in the directory
- if (os_fileinfo_hardlinks(&file_info_old) > 1
- || !os_fileinfo_link(fname, &file_info)
- || !os_fileinfo_id_equal(&file_info, &file_info_old)) {
- backup_copy = true;
- } else {
- // Check if we can create a file and set the owner/group to
- // the ones from the original file.
- // First find a file name that doesn't exist yet (use some
- // arbitrary numbers).
- STRCPY(IObuff, fname);
- for (i = 4913;; i += 123) {
- char *tail = path_tail(IObuff);
- size_t size = (size_t)(tail - IObuff);
- snprintf(tail, IOSIZE - size, "%d", i);
- if (!os_fileinfo_link(IObuff, &file_info)) {
- break;
- }
- }
- fd = os_open(IObuff,
- O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, (int)perm);
- if (fd < 0) { // can't write in directory
- backup_copy = true;
- } else {
-#ifdef UNIX
- os_fchown(fd, (uv_uid_t)file_info_old.stat.st_uid, (uv_gid_t)file_info_old.stat.st_gid);
- if (!os_fileinfo(IObuff, &file_info)
- || file_info.stat.st_uid != file_info_old.stat.st_uid
- || file_info.stat.st_gid != file_info_old.stat.st_gid
- || (long)file_info.stat.st_mode != perm) {
- backup_copy = true;
- }
-#endif
- // Close the file before removing it, on MS-Windows we
- // can't delete an open file.
- close(fd);
- os_remove(IObuff);
- }
- }
- }
-
- // Break symlinks and/or hardlinks if we've been asked to.
- if ((bkc & BKC_BREAKSYMLINK) || (bkc & BKC_BREAKHARDLINK)) {
-#ifdef UNIX
- bool file_info_link_ok = os_fileinfo_link(fname, &file_info);
-
- // Symlinks.
- if ((bkc & BKC_BREAKSYMLINK)
- && file_info_link_ok
- && !os_fileinfo_id_equal(&file_info, &file_info_old)) {
- backup_copy = false;
- }
-
- // Hardlinks.
- if ((bkc & BKC_BREAKHARDLINK)
- && os_fileinfo_hardlinks(&file_info_old) > 1
- && (!file_info_link_ok
- || os_fileinfo_id_equal(&file_info, &file_info_old))) {
- backup_copy = false;
- }
-#endif
- }
-
- // make sure we have a valid backup extension to use
- if (*p_bex == NUL) {
- backup_ext = ".bak";
- } else {
- backup_ext = p_bex;
- }
-
- if (backup_copy) {
- char *wp;
- int some_error = false;
- char *dirp;
- char *rootname;
- char *p;
-
- // Try to make the backup in each directory in the 'bdir' option.
- //
- // Unix semantics has it, that we may have a writable file,
- // that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
- // - the directory is not writable,
- // - the file may be a symbolic link,
- // - the file may belong to another user/group, etc.
- //
- // For these reasons, the existing writable file must be truncated
- // and reused. Creation of a backup COPY will be attempted.
- dirp = p_bdir;
- while (*dirp) {
- // Isolate one directory name, using an entry in 'bdir'.
- size_t dir_len = copy_option_part(&dirp, IObuff, IOSIZE, ",");
- p = IObuff + dir_len;
- bool trailing_pathseps = after_pathsep(IObuff, p) && p[-1] == p[-2];
- if (trailing_pathseps) {
- IObuff[dir_len - 2] = NUL;
- }
- if (*dirp == NUL && !os_isdir(IObuff)) {
- int ret;
- char *failed_dir;
- if ((ret = os_mkdir_recurse(IObuff, 0755, &failed_dir)) != 0) {
- semsg(_("E303: Unable to create directory \"%s\" for backup file: %s"),
- failed_dir, os_strerror(ret));
- xfree(failed_dir);
- }
- }
- if (trailing_pathseps) {
- // Ends with '//', Use Full path
- if ((p = make_percent_swname(IObuff, fname))
- != NULL) {
- backup = modname(p, backup_ext, no_prepend_dot);
- xfree(p);
- }
- }
-
- rootname = get_file_in_dir(fname, IObuff);
- if (rootname == NULL) {
- some_error = true; // out of memory
- goto nobackup;
- }
-
- FileInfo file_info_new;
- {
- //
- // Make the backup file name.
- //
- if (backup == NULL) {
- backup = modname(rootname, backup_ext, no_prepend_dot);
- }
-
- if (backup == NULL) {
- xfree(rootname);
- some_error = true; // out of memory
- goto nobackup;
- }
-
- // Check if backup file already exists.
- if (os_fileinfo(backup, &file_info_new)) {
- if (os_fileinfo_id_equal(&file_info_new, &file_info_old)) {
- //
- // Backup file is same as original file.
- // May happen when modname() gave the same file back (e.g. silly
- // link). If we don't check here, we either ruin the file when
- // copying or erase it after writing.
- //
- XFREE_CLEAR(backup); // no backup file to delete
- } else if (!p_bk) {
- // We are not going to keep the backup file, so don't
- // delete an existing one, and try to use another name instead.
- // Change one character, just before the extension.
- //
- wp = backup + strlen(backup) - 1 - strlen(backup_ext);
- if (wp < backup) { // empty file name ???
- wp = backup;
- }
- *wp = 'z';
- while (*wp > 'a' && os_fileinfo(backup, &file_info_new)) {
- (*wp)--;
- }
- // They all exist??? Must be something wrong.
- if (*wp == 'a') {
- XFREE_CLEAR(backup);
- }
- }
- }
- }
- xfree(rootname);
-
- // Try to create the backup file
- if (backup != NULL) {
- // remove old backup, if present
- os_remove(backup);
-
- // set file protection same as original file, but
- // strip s-bit.
- (void)os_setperm((const char *)backup, perm & 0777);
-
-#ifdef UNIX
- //
- // Try to set the group of the backup same as the original file. If
- // this fails, set the protection bits for the group same as the
- // protection bits for others.
- //
- if (file_info_new.stat.st_gid != file_info_old.stat.st_gid
- && os_chown(backup, (uv_uid_t)-1, (uv_gid_t)file_info_old.stat.st_gid) != 0) {
- os_setperm((const char *)backup,
- ((int)perm & 0707) | (((int)perm & 07) << 3));
- }
-#endif
-
- // copy the file
- if (os_copy(fname, backup, UV_FS_COPYFILE_FICLONE) != 0) {
- SET_ERRMSG(_("E509: Cannot create backup file (add ! to override)"));
- XFREE_CLEAR(backup);
- backup = NULL;
- continue;
- }
-
-#ifdef UNIX
- os_file_settime(backup,
- (double)file_info_old.stat.st_atim.tv_sec,
- (double)file_info_old.stat.st_mtim.tv_sec);
-#endif
-#ifdef HAVE_ACL
- os_set_acl(backup, acl);
-#endif
- SET_ERRMSG(NULL);
- break;
- }
- }
-
-nobackup:
- if (backup == NULL && errmsg == NULL) {
- SET_ERRMSG(_("E509: Cannot create backup file (add ! to override)"));
- }
- // Ignore errors when forceit is true.
- if ((some_error || errmsg != NULL) && !forceit) {
- retval = FAIL;
- goto fail;
- }
- SET_ERRMSG(NULL);
- } else {
- char *dirp;
- char *p;
- char *rootname;
-
- // Make a backup by renaming the original file.
-
- // If 'cpoptions' includes the "W" flag, we don't want to
- // overwrite a read-only file. But rename may be possible
- // anyway, thus we need an extra check here.
- if (file_readonly && vim_strchr(p_cpo, CPO_FWRITE) != NULL) {
- SET_ERRMSG_NUM("E504", _(err_readonly));
- goto fail;
- }
-
- // Form the backup file name - change path/fo.o.h to
- // path/fo.o.h.bak Try all directories in 'backupdir', first one
- // that works is used.
- dirp = p_bdir;
- while (*dirp) {
- // Isolate one directory name and make the backup file name.
- size_t dir_len = copy_option_part(&dirp, IObuff, IOSIZE, ",");
- p = IObuff + dir_len;
- bool trailing_pathseps = after_pathsep(IObuff, p) && p[-1] == p[-2];
- if (trailing_pathseps) {
- IObuff[dir_len - 2] = NUL;
- }
- if (*dirp == NUL && !os_isdir(IObuff)) {
- int ret;
- char *failed_dir;
- if ((ret = os_mkdir_recurse(IObuff, 0755, &failed_dir)) != 0) {
- semsg(_("E303: Unable to create directory \"%s\" for backup file: %s"),
- failed_dir, os_strerror(ret));
- xfree(failed_dir);
- }
- }
- if (trailing_pathseps) {
- // path ends with '//', use full path
- if ((p = make_percent_swname(IObuff, fname))
- != NULL) {
- backup = modname(p, backup_ext, no_prepend_dot);
- xfree(p);
- }
- }
-
- if (backup == NULL) {
- rootname = get_file_in_dir(fname, IObuff);
- if (rootname == NULL) {
- backup = NULL;
- } else {
- backup = modname(rootname, backup_ext, no_prepend_dot);
- xfree(rootname);
- }
- }
-
- if (backup != NULL) {
- // If we are not going to keep the backup file, don't
- // delete an existing one, try to use another name.
- // Change one character, just before the extension.
- if (!p_bk && os_path_exists(backup)) {
- p = backup + strlen(backup) - 1 - strlen(backup_ext);
- if (p < backup) { // empty file name ???
- p = backup;
- }
- *p = 'z';
- while (*p > 'a' && os_path_exists(backup)) {
- (*p)--;
- }
- // They all exist??? Must be something wrong!
- if (*p == 'a') {
- XFREE_CLEAR(backup);
- }
- }
- }
- if (backup != NULL) {
- // Delete any existing backup and move the current version
- // to the backup. For safety, we don't remove the backup
- // until the write has finished successfully. And if the
- // 'backup' option is set, leave it around.
-
- // If the renaming of the original file to the backup file
- // works, quit here.
- ///
- if (vim_rename(fname, backup) == 0) {
- break;
- }
-
- XFREE_CLEAR(backup); // don't do the rename below
- }
- }
- if (backup == NULL && !forceit) {
- SET_ERRMSG(_("E510: Can't make backup file (add ! to override)"));
- goto fail;
- }
- }
- }
-
-#if defined(UNIX)
- // When using ":w!" and the file was read-only: make it writable
- if (forceit && perm >= 0 && !(perm & 0200)
- && file_info_old.stat.st_uid == getuid()
- && vim_strchr(p_cpo, CPO_FWRITE) == NULL) {
- perm |= 0200;
- (void)os_setperm((const char *)fname, (int)perm);
- made_writable = true;
- }
-#endif
-
- // When using ":w!" and writing to the current file, 'readonly' makes no
- // sense, reset it, unless 'Z' appears in 'cpoptions'.
- if (forceit && overwriting && vim_strchr(p_cpo, CPO_KEEPRO) == NULL) {
- buf->b_p_ro = false;
- need_maketitle = true; // set window title later
- status_redraw_all(); // redraw status lines later
- }
-
- if (end > buf->b_ml.ml_line_count) {
- end = buf->b_ml.ml_line_count;
- }
- if (buf->b_ml.ml_flags & ML_EMPTY) {
- start = end + 1;
- }
-
- // If the original file is being overwritten, there is a small chance that
- // we crash in the middle of writing. Therefore the file is preserved now.
- // This makes all block numbers positive so that recovery does not need
- // the original file.
- // Don't do this if there is a backup file and we are exiting.
- if (reset_changed && !newfile && overwriting
- && !(exiting && backup != NULL)) {
- ml_preserve(buf, false, !!p_fs);
- if (got_int) {
- SET_ERRMSG(_(e_interr));
- goto restore_backup;
- }
- }
-
- // Default: write the file directly. May write to a temp file for
- // multi-byte conversion.
- wfname = fname;
-
- // Check for forced 'fileencoding' from "++opt=val" argument.
- if (eap != NULL && eap->force_enc != 0) {
- fenc = eap->cmd + eap->force_enc;
- fenc = enc_canonize(fenc);
- fenc_tofree = fenc;
- } else {
- fenc = buf->b_p_fenc;
- }
-
- // Check if the file needs to be converted.
- converted = need_conversion(fenc);
-
- // Check if UTF-8 to UCS-2/4 or Latin1 conversion needs to be done. Or
- // Latin1 to Unicode conversion. This is handled in buf_write_bytes().
- // Prepare the flags for it and allocate bw_conv_buf when needed.
- if (converted) {
- wb_flags = get_fio_flags(fenc);
- if (wb_flags & (FIO_UCS2 | FIO_UCS4 | FIO_UTF16 | FIO_UTF8)) {
- // Need to allocate a buffer to translate into.
- if (wb_flags & (FIO_UCS2 | FIO_UTF16 | FIO_UTF8)) {
- write_info.bw_conv_buflen = (size_t)bufsize * 2;
- } else { // FIO_UCS4
- write_info.bw_conv_buflen = (size_t)bufsize * 4;
- }
- write_info.bw_conv_buf = verbose_try_malloc(write_info.bw_conv_buflen);
- if (!write_info.bw_conv_buf) {
- end = 0;
- }
- }
- }
-
- if (converted && wb_flags == 0) {
- // Use iconv() conversion when conversion is needed and it's not done
- // internally.
- write_info.bw_iconv_fd = (iconv_t)my_iconv_open(fenc, "utf-8");
- if (write_info.bw_iconv_fd != (iconv_t)-1) {
- // We're going to use iconv(), allocate a buffer to convert in.
- write_info.bw_conv_buflen = (size_t)bufsize * ICONV_MULT;
- write_info.bw_conv_buf = verbose_try_malloc(write_info.bw_conv_buflen);
- if (!write_info.bw_conv_buf) {
- end = 0;
- }
- write_info.bw_first = true;
- } else {
- // When the file needs to be converted with 'charconvert' after
- // writing, write to a temp file instead and let the conversion
- // overwrite the original file.
- if (*p_ccv != NUL) {
- wfname = vim_tempname();
- if (wfname == NULL) { // Can't write without a tempfile!
- SET_ERRMSG(_("E214: Can't find temp file for writing"));
- goto restore_backup;
- }
- }
- }
- }
-
- if (converted && wb_flags == 0
- && write_info.bw_iconv_fd == (iconv_t)-1
- && wfname == fname) {
- if (!forceit) {
- SET_ERRMSG(_("E213: Cannot convert (add ! to write without conversion)"));
- goto restore_backup;
- }
- notconverted = true;
- }
-
- // If conversion is taking place, we may first pretend to write and check
- // for conversion errors. Then loop again to write for real.
- // When not doing conversion this writes for real right away.
- for (checking_conversion = true;; checking_conversion = false) {
- // There is no need to check conversion when:
- // - there is no conversion
- // - we make a backup file, that can be restored in case of conversion
- // failure.
- if (!converted || dobackup) {
- checking_conversion = false;
- }
-
- if (checking_conversion) {
- // Make sure we don't write anything.
- fd = -1;
- write_info.bw_fd = fd;
- } else {
- // Open the file "wfname" for writing.
- // We may try to open the file twice: If we can't write to the file
- // and forceit is true we delete the existing file and try to
- // create a new one. If this still fails we may have lost the
- // original file! (this may happen when the user reached his
- // quotum for number of files).
- // Appending will fail if the file does not exist and forceit is
- // false.
- while ((fd = os_open(wfname,
- O_WRONLY |
- (append
- ? (forceit
- ? (O_APPEND | O_CREAT)
- : O_APPEND)
- : (O_CREAT | O_TRUNC)),
- perm < 0 ? 0666 : (perm & 0777))) < 0) {
- // A forced write will try to create a new file if the old one
- // is still readonly. This may also happen when the directory
- // is read-only. In that case the mch_remove() will fail.
- if (errmsg == NULL) {
-#ifdef UNIX
- FileInfo file_info;
-
- // Don't delete the file when it's a hard or symbolic link.
- if ((!newfile && os_fileinfo_hardlinks(&file_info_old) > 1)
- || (os_fileinfo_link(fname, &file_info)
- && !os_fileinfo_id_equal(&file_info, &file_info_old))) {
- SET_ERRMSG(_("E166: Can't open linked file for writing"));
- } else {
-#endif
- SET_ERRMSG_ARG(_("E212: Can't open file for writing: %s"), fd);
- if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL
- && perm >= 0) {
-#ifdef UNIX
- // we write to the file, thus it should be marked
- // writable after all
- if (!(perm & 0200)) {
- made_writable = true;
- }
- perm |= 0200;
- if (file_info_old.stat.st_uid != getuid()
- || file_info_old.stat.st_gid != getgid()) {
- perm &= 0777;
- }
-#endif
- if (!append) { // don't remove when appending
- os_remove(wfname);
- }
- continue;
- }
-#ifdef UNIX
- }
-#endif
- }
-
-restore_backup:
- {
- // If we failed to open the file, we don't need a backup. Throw it
- // away. If we moved or removed the original file try to put the
- // backup in its place.
- if (backup != NULL && wfname == fname) {
- if (backup_copy) {
- // There is a small chance that we removed the original,
- // try to move the copy in its place.
- // This may not work if the vim_rename() fails.
- // In that case we leave the copy around.
- // If file does not exist, put the copy in its place
- if (!os_path_exists(fname)) {
- vim_rename(backup, fname);
- }
- // if original file does exist throw away the copy
- if (os_path_exists(fname)) {
- os_remove(backup);
- }
- } else {
- // try to put the original file back
- vim_rename(backup, fname);
- }
- }
-
- // if original file no longer exists give an extra warning
- if (!newfile && !os_path_exists(fname)) {
- end = 0;
- }
- }
-
- if (wfname != fname) {
- xfree(wfname);
- }
- goto fail;
- }
- write_info.bw_fd = fd;
- }
- SET_ERRMSG(NULL);
-
- write_info.bw_buf = buffer;
- nchars = 0;
-
- // use "++bin", "++nobin" or 'binary'
- if (eap != NULL && eap->force_bin != 0) {
- write_bin = (eap->force_bin == FORCE_BIN);
- } else {
- write_bin = buf->b_p_bin;
- }
-
- // Skip the BOM when appending and the file already existed, the BOM
- // only makes sense at the start of the file.
- if (buf->b_p_bomb && !write_bin && (!append || perm < 0)) {
- write_info.bw_len = make_bom((char_u *)buffer, fenc);
- if (write_info.bw_len > 0) {
- // don't convert
- write_info.bw_flags = FIO_NOCONVERT | wb_flags;
- if (buf_write_bytes(&write_info) == FAIL) {
- end = 0;
- } else {
- nchars += write_info.bw_len;
- }
- }
- }
- write_info.bw_start_lnum = start;
-
- write_undo_file = (buf->b_p_udf && overwriting && !append
- && !filtering && reset_changed && !checking_conversion);
- if (write_undo_file) {
- // Prepare for computing the hash value of the text.
- sha256_start(&sha_ctx);
- }
-
- write_info.bw_len = bufsize;
-#ifdef HAS_BW_FLAGS
- write_info.bw_flags = wb_flags;
-#endif
- fileformat = get_fileformat_force(buf, eap);
- s = buffer;
- len = 0;
- for (lnum = start; lnum <= end; lnum++) {
- // The next while loop is done once for each character written.
- // Keep it fast!
- ptr = ml_get_buf(buf, lnum, false) - 1;
- if (write_undo_file) {
- sha256_update(&sha_ctx, (uint8_t *)ptr + 1, (uint32_t)(strlen(ptr + 1) + 1));
- }
- while ((c = *++ptr) != NUL) {
- if (c == NL) {
- *s = NUL; // replace newlines with NULs
- } else if (c == CAR && fileformat == EOL_MAC) {
- *s = NL; // Mac: replace CRs with NLs
- } else {
- *s = c;
- }
- s++;
- if (++len != bufsize) {
- continue;
- }
- if (buf_write_bytes(&write_info) == FAIL) {
- end = 0; // write error: break loop
- break;
- }
- nchars += bufsize;
- s = buffer;
- len = 0;
- write_info.bw_start_lnum = lnum;
- }
- // write failed or last line has no EOL: stop here
- if (end == 0
- || (lnum == end
- && (write_bin || !buf->b_p_fixeol)
- && ((write_bin && lnum == buf->b_no_eol_lnum)
- || (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol)))) {
- lnum++; // written the line, count it
- no_eol = true;
- break;
- }
- if (fileformat == EOL_UNIX) {
- *s++ = NL;
- } else {
- *s++ = CAR; // EOL_MAC or EOL_DOS: write CR
- if (fileformat == EOL_DOS) { // write CR-NL
- if (++len == bufsize) {
- if (buf_write_bytes(&write_info) == FAIL) {
- end = 0; // write error: break loop
- break;
- }
- nchars += bufsize;
- s = buffer;
- len = 0;
- }
- *s++ = NL;
- }
- }
- if (++len == bufsize) {
- if (buf_write_bytes(&write_info) == FAIL) {
- end = 0; // Write error: break loop.
- break;
- }
- nchars += bufsize;
- s = buffer;
- len = 0;
-
- os_breakcheck();
- if (got_int) {
- end = 0; // Interrupted, break loop.
- break;
- }
- }
- }
- if (len > 0 && end > 0) {
- write_info.bw_len = len;
- if (buf_write_bytes(&write_info) == FAIL) {
- end = 0; // write error
- }
- nchars += len;
- }
-
- if (!buf->b_p_fixeol && buf->b_p_eof) {
- // write trailing CTRL-Z
- (void)write_eintr(write_info.bw_fd, "\x1a", 1);
- }
-
- // Stop when writing done or an error was encountered.
- if (!checking_conversion || end == 0) {
- break;
- }
-
- // If no error happened until now, writing should be ok, so loop to
- // really write the buffer.
- }
-
- // If we started writing, finish writing. Also when an error was
- // encountered.
- if (!checking_conversion) {
- // On many journalling file systems there is a bug that causes both the
- // original and the backup file to be lost when halting the system right
- // after writing the file. That's because only the meta-data is
- // journalled. Syncing the file slows down the system, but assures it has
- // been written to disk and we don't lose it.
- // For a device do try the fsync() but don't complain if it does not work
- // (could be a pipe).
- // If the 'fsync' option is false, don't fsync(). Useful for laptops.
- int error;
- if (p_fs && (error = os_fsync(fd)) != 0 && !device
- // fsync not supported on this storage.
- && error != UV_ENOTSUP) {
- SET_ERRMSG_ARG(e_fsync, error);
- end = 0;
- }
-
-#ifdef UNIX
- // When creating a new file, set its owner/group to that of the original
- // file. Get the new device and inode number.
- if (backup != NULL && !backup_copy) {
- // don't change the owner when it's already OK, some systems remove
- // permission or ACL stuff
- FileInfo file_info;
- if (!os_fileinfo(wfname, &file_info)
- || file_info.stat.st_uid != file_info_old.stat.st_uid
- || file_info.stat.st_gid != file_info_old.stat.st_gid) {
- os_fchown(fd, (uv_uid_t)file_info_old.stat.st_uid, (uv_gid_t)file_info_old.stat.st_gid);
- if (perm >= 0) { // Set permission again, may have changed.
- (void)os_setperm(wfname, (int)perm);
- }
- }
- buf_set_file_id(buf);
- } else if (!buf->file_id_valid) {
- // Set the file_id when creating a new file.
- buf_set_file_id(buf);
- }
-#endif
-
- if ((error = os_close(fd)) != 0) {
- SET_ERRMSG_ARG(_("E512: Close failed: %s"), error);
- end = 0;
- }
-
-#ifdef UNIX
- if (made_writable) {
- perm &= ~0200; // reset 'w' bit for security reasons
- }
-#endif
- if (perm >= 0) { // Set perm. of new file same as old file.
- (void)os_setperm((const char *)wfname, (int)perm);
- }
-#ifdef HAVE_ACL
- // Probably need to set the ACL before changing the user (can't set the
- // ACL on a file the user doesn't own).
- if (!backup_copy) {
- os_set_acl(wfname, acl);
- }
-#endif
-
- if (wfname != fname) {
- // The file was written to a temp file, now it needs to be converted
- // with 'charconvert' to (overwrite) the output file.
- if (end != 0) {
- if (eval_charconvert("utf-8", fenc, wfname, fname) == FAIL) {
- write_info.bw_conv_error = true;
- end = 0;
- }
- }
- os_remove(wfname);
- xfree(wfname);
- }
- }
-
- if (end == 0) {
- // Error encountered.
- if (errmsg == NULL) {
- if (write_info.bw_conv_error) {
- if (write_info.bw_conv_error_lnum == 0) {
- SET_ERRMSG(_("E513: write error, conversion failed "
- "(make 'fenc' empty to override)"));
- } else {
- errmsg_allocated = true;
- SET_ERRMSG(xmalloc(300));
- vim_snprintf(errmsg, 300, // NOLINT(runtime/printf)
- _("E513: write error, conversion failed in line %" PRIdLINENR
- " (make 'fenc' empty to override)"),
- write_info.bw_conv_error_lnum);
- }
- } else if (got_int) {
- SET_ERRMSG(_(e_interr));
- } else {
- SET_ERRMSG(_("E514: write error (file system full?)"));
- }
- }
-
- // If we have a backup file, try to put it in place of the new file,
- // because the new file is probably corrupt. This avoids losing the
- // original file when trying to make a backup when writing the file a
- // second time.
- // When "backup_copy" is set we need to copy the backup over the new
- // file. Otherwise rename the backup file.
- // If this is OK, don't give the extra warning message.
- if (backup != NULL) {
- if (backup_copy) {
- // This may take a while, if we were interrupted let the user
- // know we got the message.
- if (got_int) {
- msg(_(e_interr));
- ui_flush();
- }
-
- // copy the file.
- if (os_copy(backup, fname, UV_FS_COPYFILE_FICLONE)
- == 0) {
- end = 1; // success
- }
- } else {
- if (vim_rename(backup, fname) == 0) {
- end = 1;
- }
- }
- }
- goto fail;
- }
-
- lnum -= start; // compute number of written lines
- no_wait_return--; // may wait for return now
-
-#if !defined(UNIX)
- fname = sfname; // use shortname now, for the messages
-#endif
- if (!filtering) {
- add_quoted_fname(IObuff, IOSIZE, buf, (const char *)fname);
- c = false;
- if (write_info.bw_conv_error) {
- STRCAT(IObuff, _(" CONVERSION ERROR"));
- c = true;
- if (write_info.bw_conv_error_lnum != 0) {
- vim_snprintf_add(IObuff, IOSIZE, _(" in line %" PRId64 ";"),
- (int64_t)write_info.bw_conv_error_lnum);
- }
- } else if (notconverted) {
- STRCAT(IObuff, _("[NOT converted]"));
- c = true;
- } else if (converted) {
- STRCAT(IObuff, _("[converted]"));
- c = true;
- }
- if (device) {
- STRCAT(IObuff, _("[Device]"));
- c = true;
- } else if (newfile) {
- STRCAT(IObuff, new_file_message());
- c = true;
- }
- if (no_eol) {
- msg_add_eol();
- c = true;
- }
- // may add [unix/dos/mac]
- if (msg_add_fileformat(fileformat)) {
- c = true;
- }
- msg_add_lines(c, (long)lnum, nchars); // add line/char count
- if (!shortmess(SHM_WRITE)) {
- if (append) {
- STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
- } else {
- STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [w]") : _(" written"));
- }
- }
-
- set_keep_msg(msg_trunc_attr(IObuff, false, 0), 0);
- }
-
- // When written everything correctly: reset 'modified'. Unless not
- // writing to the original file and '+' is not in 'cpoptions'.
- if (reset_changed && whole && !append
- && !write_info.bw_conv_error
- && (overwriting || vim_strchr(p_cpo, CPO_PLUS) != NULL)) {
- unchanged(buf, true, false);
- const varnumber_T changedtick = buf_get_changedtick(buf);
- if (buf->b_last_changedtick + 1 == changedtick) {
- // b:changedtick may be incremented in unchanged() but that
- // should not trigger a TextChanged event.
- buf->b_last_changedtick = changedtick;
- }
- u_unchanged(buf);
- u_update_save_nr(buf);
- }
-
- // If written to the current file, update the timestamp of the swap file
- // and reset the BF_WRITE_MASK flags. Also sets buf->b_mtime.
- if (overwriting) {
- ml_timestamp(buf);
- if (append) {
- buf->b_flags &= ~BF_NEW;
- } else {
- buf->b_flags &= ~BF_WRITE_MASK;
- }
- }
-
- // If we kept a backup until now, and we are in patch mode, then we make
- // the backup file our 'original' file.
- if (*p_pm && dobackup) {
- char *const org = modname(fname, p_pm, false);
-
- if (backup != NULL) {
- // If the original file does not exist yet
- // the current backup file becomes the original file
- if (org == NULL) {
- emsg(_("E205: Patchmode: can't save original file"));
- } else if (!os_path_exists(org)) {
- vim_rename(backup, org);
- XFREE_CLEAR(backup); // don't delete the file
-#ifdef UNIX
- os_file_settime(org,
- (double)file_info_old.stat.st_atim.tv_sec,
- (double)file_info_old.stat.st_mtim.tv_sec);
-#endif
- }
- } else {
- // If there is no backup file, remember that a (new) file was
- // created.
- int empty_fd;
-
- if (org == NULL
- || (empty_fd = os_open(org,
- O_CREAT | O_EXCL | O_NOFOLLOW,
- perm < 0 ? 0666 : (perm & 0777))) < 0) {
- emsg(_("E206: patchmode: can't touch empty original file"));
- } else {
- close(empty_fd);
- }
- }
- if (org != NULL) {
- os_setperm(org, os_getperm((const char *)fname) & 0777);
- xfree(org);
- }
- }
-
- // Remove the backup unless 'backup' option is set
- if (!p_bk && backup != NULL
- && !write_info.bw_conv_error
- && os_remove(backup) != 0) {
- emsg(_("E207: Can't delete backup file"));
- }
-
- goto nofail;
-
- // Finish up. We get here either after failure or success.
-fail:
- no_wait_return--; // may wait for return now
-nofail:
-
- // Done saving, we accept changed buffer warnings again
- buf->b_saving = false;
-
- xfree(backup);
- if (buffer != smallbuf) {
- xfree(buffer);
- }
- xfree(fenc_tofree);
- xfree(write_info.bw_conv_buf);
- if (write_info.bw_iconv_fd != (iconv_t)-1) {
- iconv_close(write_info.bw_iconv_fd);
- write_info.bw_iconv_fd = (iconv_t)-1;
- }
-#ifdef HAVE_ACL
- os_free_acl(acl);
-#endif
-
- if (errmsg != NULL) {
- // - 100 to save some space for further error message
-#ifndef UNIX
- add_quoted_fname(IObuff, IOSIZE - 100, buf, (const char *)sfname);
-#else
- add_quoted_fname(IObuff, IOSIZE - 100, buf, (const char *)fname);
-#endif
- if (errnum != NULL) {
- if (errmsgarg != 0) {
- semsg("%s: %s%s: %s", errnum, IObuff, errmsg, os_strerror(errmsgarg));
- } else {
- semsg("%s: %s%s", errnum, IObuff, errmsg);
- }
- } else if (errmsgarg != 0) {
- semsg(errmsg, os_strerror(errmsgarg));
- } else {
- emsg(errmsg);
- }
- if (errmsg_allocated) {
- xfree(errmsg);
- }
-
- retval = FAIL;
- if (end == 0) {
- const int attr = HL_ATTR(HLF_E); // Set highlight for error messages.
- msg_puts_attr(_("\nWARNING: Original file may be lost or damaged\n"),
- attr | MSG_HIST);
- msg_puts_attr(_("don't quit the editor until the file is successfully written!"),
- attr | MSG_HIST);
-
- // Update the timestamp to avoid an "overwrite changed file"
- // prompt when writing again.
- if (os_fileinfo(fname, &file_info_old)) {
- buf_store_file_info(buf, &file_info_old);
- buf->b_mtime_read = buf->b_mtime;
- buf->b_mtime_read_ns = buf->b_mtime_ns;
- }
- }
- }
- msg_scroll = msg_save;
-
- // When writing the whole file and 'undofile' is set, also write the undo
- // file.
- if (retval == OK && write_undo_file) {
- uint8_t hash[UNDO_HASH_SIZE];
-
- sha256_finish(&sha_ctx, hash);
- u_write_undo(NULL, false, buf, hash);
- }
-
- if (!should_abort(retval)) {
- aco_save_T aco;
-
- curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read
-
- // Apply POST autocommands.
- // Careful: The autocommands may call buf_write() recursively!
- aucmd_prepbuf(&aco, buf);
-
- if (append) {
- apply_autocmds_exarg(EVENT_FILEAPPENDPOST, fname, fname,
- false, curbuf, eap);
- } else if (filtering) {
- apply_autocmds_exarg(EVENT_FILTERWRITEPOST, NULL, fname,
- false, curbuf, eap);
- } else if (reset_changed && whole) {
- apply_autocmds_exarg(EVENT_BUFWRITEPOST, fname, fname,
- false, curbuf, eap);
- } else {
- apply_autocmds_exarg(EVENT_FILEWRITEPOST, fname, fname,
- false, curbuf, eap);
- }
-
- // restore curwin/curbuf and a few other things
- aucmd_restbuf(&aco);
-
- if (aborting()) { // autocmds may abort script processing
- retval = false;
- }
- }
-
- got_int |= prev_got_int;
-
- return retval;
-#undef SET_ERRMSG
-#undef SET_ERRMSG_ARG
-#undef SET_ERRMSG_NUM
-}
-
/// Set the name of the current buffer. Use when the buffer doesn't have a
/// name and a ":r" or ":w" command with a file name is used.
-static int set_rw_fname(char *fname, char *sfname)
+int set_rw_fname(char *fname, char *sfname)
{
buf_T *buf = curbuf;
@@ -3649,8 +2114,8 @@ static int set_rw_fname(char *fname, char *sfname)
/// @param[in] buf_len ret_buf length.
/// @param[in] buf buf_T file name is coming from.
/// @param[in] fname File name to write.
-static void add_quoted_fname(char *const ret_buf, const size_t buf_len, const buf_T *const buf,
- const char *fname)
+void add_quoted_fname(char *const ret_buf, const size_t buf_len, const buf_T *const buf,
+ const char *fname)
FUNC_ATTR_NONNULL_ARG(1)
{
if (fname == NULL) {
@@ -3666,21 +2131,21 @@ static void add_quoted_fname(char *const ret_buf, const size_t buf_len, const bu
/// @param eol_type line ending type
///
/// @return true if something was appended.
-static bool msg_add_fileformat(int eol_type)
+bool msg_add_fileformat(int eol_type)
{
#ifndef USE_CRNL
if (eol_type == EOL_DOS) {
- STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[dos]") : _("[dos format]"));
+ xstrlcat(IObuff, _("[dos]"), IOSIZE);
return true;
}
#endif
if (eol_type == EOL_MAC) {
- STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[mac]") : _("[mac format]"));
+ xstrlcat(IObuff, _("[mac]"), IOSIZE);
return true;
}
#ifdef USE_CRNL
if (eol_type == EOL_UNIX) {
- STRCAT(IObuff, shortmess(SHM_TEXT) ? _("[unix]") : _("[unix format]"));
+ xstrlcat(IObuff, _("[unix]"), IOSIZE);
return true;
}
#endif
@@ -3688,11 +2153,9 @@ static bool msg_add_fileformat(int eol_type)
}
/// Append line and character count to IObuff.
-void msg_add_lines(int insert_space, long lnum, off_T nchars)
+void msg_add_lines(int insert_space, linenr_T lnum, off_T nchars)
{
- char *p;
-
- p = IObuff + strlen(IObuff);
+ char *p = IObuff + strlen(IObuff);
if (insert_space) {
*p++ = ' ';
@@ -3711,302 +2174,32 @@ void msg_add_lines(int insert_space, long lnum, off_T nchars)
}
}
-/// Append message for missing line separator to IObuff.
-static void msg_add_eol(void)
-{
- STRCAT(IObuff,
- shortmess(SHM_LAST) ? _("[noeol]") : _("[Incomplete last line]"));
-}
-
-/// Check modification time of file, before writing to it.
-/// The size isn't checked, because using a tool like "gzip" takes care of
-/// using the same timestamp but can't set the size.
-static int check_mtime(buf_T *buf, FileInfo *file_info)
-{
- if (buf->b_mtime_read != 0
- && time_differs(file_info, buf->b_mtime_read, buf->b_mtime_read_ns)) {
- msg_scroll = true; // Don't overwrite messages here.
- msg_silent = 0; // Must give this prompt.
- // Don't use emsg() here, don't want to flush the buffers.
- msg_attr(_("WARNING: The file has been changed since reading it!!!"),
- HL_ATTR(HLF_E));
- if (ask_yesno(_("Do you really want to write to it"), true) == 'n') {
- return FAIL;
- }
- msg_scroll = false; // Always overwrite the file message now.
- }
- return OK;
-}
-
-static bool time_differs(const FileInfo *file_info, long mtime, long mtime_ns) FUNC_ATTR_CONST
+bool time_differs(const FileInfo *file_info, int64_t mtime, int64_t mtime_ns)
+ FUNC_ATTR_CONST
{
- return file_info->stat.st_mtim.tv_nsec != mtime_ns
#if defined(__linux__) || defined(MSWIN)
+ return file_info->stat.st_mtim.tv_nsec != mtime_ns
// On a FAT filesystem, esp. under Linux, there are only 5 bits to store
// the seconds. Since the roundoff is done when flushing the inode, the
// time may change unexpectedly by one second!!!
|| file_info->stat.st_mtim.tv_sec - mtime > 1
|| mtime - file_info->stat.st_mtim.tv_sec > 1;
#else
+ return file_info->stat.st_mtim.tv_nsec != mtime_ns
|| file_info->stat.st_mtim.tv_sec != mtime;
#endif
}
-/// Call write() to write a number of bytes to the file.
-/// Handles 'encoding' conversion.
-///
-/// @return FAIL for failure, OK otherwise.
-static int buf_write_bytes(struct bw_info *ip)
-{
- int wlen;
- char *buf = ip->bw_buf; // data to write
- int len = ip->bw_len; // length of data
-#ifdef HAS_BW_FLAGS
- int flags = ip->bw_flags; // extra flags
-#endif
-
- // Skip conversion when writing the BOM.
- if (!(flags & FIO_NOCONVERT)) {
- char *p;
- unsigned c;
- int n;
-
- if (flags & FIO_UTF8) {
- // Convert latin1 in the buffer to UTF-8 in the file.
- p = ip->bw_conv_buf; // translate to buffer
- for (wlen = 0; wlen < len; wlen++) {
- p += utf_char2bytes((uint8_t)buf[wlen], p);
- }
- buf = ip->bw_conv_buf;
- len = (int)(p - ip->bw_conv_buf);
- } else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1)) {
- // Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
- // Latin1 chars in the file.
- if (flags & FIO_LATIN1) {
- p = buf; // translate in-place (can only get shorter)
- } else {
- p = ip->bw_conv_buf; // translate to buffer
- }
- for (wlen = 0; wlen < len; wlen += n) {
- if (wlen == 0 && ip->bw_restlen != 0) {
- int l;
-
- // Use remainder of previous call. Append the start of
- // buf[] to get a full sequence. Might still be too
- // short!
- l = CONV_RESTLEN - ip->bw_restlen;
- if (l > len) {
- l = len;
- }
- memmove(ip->bw_rest + ip->bw_restlen, buf, (size_t)l);
- n = utf_ptr2len_len((char *)ip->bw_rest, ip->bw_restlen + l);
- if (n > ip->bw_restlen + len) {
- // We have an incomplete byte sequence at the end to
- // be written. We can't convert it without the
- // remaining bytes. Keep them for the next call.
- if (ip->bw_restlen + len > CONV_RESTLEN) {
- return FAIL;
- }
- ip->bw_restlen += len;
- break;
- }
- if (n > 1) {
- c = (unsigned)utf_ptr2char((char *)ip->bw_rest);
- } else {
- c = ip->bw_rest[0];
- }
- if (n >= ip->bw_restlen) {
- n -= ip->bw_restlen;
- ip->bw_restlen = 0;
- } else {
- ip->bw_restlen -= n;
- memmove(ip->bw_rest, ip->bw_rest + n,
- (size_t)ip->bw_restlen);
- n = 0;
- }
- } else {
- n = utf_ptr2len_len(buf + wlen, len - wlen);
- if (n > len - wlen) {
- // We have an incomplete byte sequence at the end to
- // be written. We can't convert it without the
- // remaining bytes. Keep them for the next call.
- if (len - wlen > CONV_RESTLEN) {
- return FAIL;
- }
- ip->bw_restlen = len - wlen;
- memmove(ip->bw_rest, buf + wlen,
- (size_t)ip->bw_restlen);
- break;
- }
- if (n > 1) {
- c = (unsigned)utf_ptr2char(buf + wlen);
- } else {
- c = (uint8_t)buf[wlen];
- }
- }
-
- if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error) {
- ip->bw_conv_error = true;
- ip->bw_conv_error_lnum = ip->bw_start_lnum;
- }
- if (c == NL) {
- ip->bw_start_lnum++;
- }
- }
- if (flags & FIO_LATIN1) {
- len = (int)(p - buf);
- } else {
- buf = ip->bw_conv_buf;
- len = (int)(p - ip->bw_conv_buf);
- }
- }
-
- if (ip->bw_iconv_fd != (iconv_t)-1) {
- const char *from;
- size_t fromlen;
- char *to;
- size_t tolen;
-
- // Convert with iconv().
- if (ip->bw_restlen > 0) {
- char *fp;
-
- // Need to concatenate the remainder of the previous call and
- // the bytes of the current call. Use the end of the
- // conversion buffer for this.
- fromlen = (size_t)len + (size_t)ip->bw_restlen;
- fp = ip->bw_conv_buf + ip->bw_conv_buflen - fromlen;
- memmove(fp, ip->bw_rest, (size_t)ip->bw_restlen);
- memmove(fp + ip->bw_restlen, buf, (size_t)len);
- from = fp;
- tolen = ip->bw_conv_buflen - fromlen;
- } else {
- from = buf;
- fromlen = (size_t)len;
- tolen = ip->bw_conv_buflen;
- }
- to = ip->bw_conv_buf;
-
- if (ip->bw_first) {
- size_t save_len = tolen;
-
- // output the initial shift state sequence
- (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
-
- // There is a bug in iconv() on Linux (which appears to be
- // wide-spread) which sets "to" to NULL and messes up "tolen".
- if (to == NULL) {
- to = ip->bw_conv_buf;
- tolen = save_len;
- }
- ip->bw_first = false;
- }
-
- // If iconv() has an error or there is not enough room, fail.
- if ((iconv(ip->bw_iconv_fd, (void *)&from, &fromlen, &to, &tolen)
- == (size_t)-1 && ICONV_ERRNO != ICONV_EINVAL)
- || fromlen > CONV_RESTLEN) {
- ip->bw_conv_error = true;
- return FAIL;
- }
-
- // copy remainder to ip->bw_rest[] to be used for the next call.
- if (fromlen > 0) {
- memmove(ip->bw_rest, (void *)from, fromlen);
- }
- ip->bw_restlen = (int)fromlen;
-
- buf = ip->bw_conv_buf;
- len = (int)(to - ip->bw_conv_buf);
- }
- }
-
- if (ip->bw_fd < 0) {
- // Only checking conversion, which is OK if we get here.
- return OK;
- }
- wlen = (int)write_eintr(ip->bw_fd, buf, (size_t)len);
- return (wlen < len) ? FAIL : OK;
-}
-
-/// Convert a Unicode character to bytes.
-///
-/// @param c character to convert
-/// @param[in,out] pp pointer to store the result at
-/// @param flags FIO_ flags that specify which encoding to use
-///
-/// @return true for an error, false when it's OK.
-static bool ucs2bytes(unsigned c, char **pp, int flags) FUNC_ATTR_NONNULL_ALL
-{
- char_u *p = (char_u *)(*pp);
- bool error = false;
- int cc;
-
- if (flags & FIO_UCS4) {
- if (flags & FIO_ENDIAN_L) {
- *p++ = (uint8_t)c;
- *p++ = (uint8_t)(c >> 8);
- *p++ = (uint8_t)(c >> 16);
- *p++ = (uint8_t)(c >> 24);
- } else {
- *p++ = (uint8_t)(c >> 24);
- *p++ = (uint8_t)(c >> 16);
- *p++ = (uint8_t)(c >> 8);
- *p++ = (uint8_t)c;
- }
- } else if (flags & (FIO_UCS2 | FIO_UTF16)) {
- if (c >= 0x10000) {
- if (flags & FIO_UTF16) {
- // Make two words, ten bits of the character in each. First
- // word is 0xd800 - 0xdbff, second one 0xdc00 - 0xdfff
- c -= 0x10000;
- if (c >= 0x100000) {
- error = true;
- }
- cc = (int)(((c >> 10) & 0x3ff) + 0xd800);
- if (flags & FIO_ENDIAN_L) {
- *p++ = (uint8_t)cc;
- *p++ = (uint8_t)(cc >> 8);
- } else {
- *p++ = (uint8_t)(cc >> 8);
- *p++ = (uint8_t)cc;
- }
- c = (c & 0x3ff) + 0xdc00;
- } else {
- error = true;
- }
- }
- if (flags & FIO_ENDIAN_L) {
- *p++ = (uint8_t)c;
- *p++ = (uint8_t)(c >> 8);
- } else {
- *p++ = (uint8_t)(c >> 8);
- *p++ = (uint8_t)c;
- }
- } else { // Latin1
- if (c >= 0x100) {
- error = true;
- *p++ = 0xBF;
- } else {
- *p++ = (uint8_t)c;
- }
- }
-
- *pp = (char *)p;
- return error;
-}
-
/// Return true if file encoding "fenc" requires conversion from or to
/// 'encoding'.
///
/// @param fenc file encoding to check
///
/// @return true if conversion is required
-static bool need_conversion(const char *fenc)
+bool need_conversion(const char *fenc)
FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
{
int same_encoding;
- int enc_flags;
int fenc_flags;
if (*fenc == NUL || strcmp(p_enc, fenc) == 0) {
@@ -4015,7 +2208,7 @@ static bool need_conversion(const char *fenc)
} else {
// Ignore difference between "ansi" and "latin1", "ucs-4" and
// "ucs-4be", etc.
- enc_flags = get_fio_flags(p_enc);
+ int enc_flags = get_fio_flags(p_enc);
fenc_flags = get_fio_flags(fenc);
same_encoding = (enc_flags != 0 && fenc_flags == enc_flags);
}
@@ -4034,14 +2227,12 @@ static bool need_conversion(const char *fenc)
/// use 'encoding'.
///
/// @param name string to check for encoding
-static int get_fio_flags(const char *name)
+int get_fio_flags(const char *name)
{
- int prop;
-
if (*name == NUL) {
name = p_enc;
}
- prop = enc_canon_props(name);
+ int prop = enc_canon_props(name);
if (prop & ENC_UNICODE) {
if (prop & ENC_2BYTE) {
if (prop & ENC_ENDIAN_L) {
@@ -4075,7 +2266,7 @@ static int get_fio_flags(const char *name)
///
/// @return the name of the encoding and set "*lenp" to the length or,
/// NULL when no BOM found.
-static char *check_for_bom(const char *p_in, long size, int *lenp, int flags)
+static char *check_for_bom(const char *p_in, int size, int *lenp, int flags)
{
const uint8_t *p = (const uint8_t *)p_in;
char *name = NULL;
@@ -4116,32 +2307,6 @@ static char *check_for_bom(const char *p_in, long size, int *lenp, int flags)
return name;
}
-/// Generate a BOM in "buf[4]" for encoding "name".
-///
-/// @return the length of the BOM (zero when no BOM).
-static int make_bom(char_u *buf, char *name)
-{
- int flags;
- char *p;
-
- flags = get_fio_flags(name);
-
- // Can't put a BOM in a non-Unicode file.
- if (flags == FIO_LATIN1 || flags == 0) {
- return 0;
- }
-
- if (flags == FIO_UTF8) { // UTF-8
- buf[0] = 0xef;
- buf[1] = 0xbb;
- buf[2] = 0xbf;
- return 3;
- }
- p = (char *)buf;
- (void)ucs2bytes(0xfeff, &p, flags);
- return (int)((char_u *)p - buf);
-}
-
/// Shorten filename of a buffer.
///
/// @param force when true: Use full path from now on for files currently being
@@ -4153,8 +2318,6 @@ static int make_bom(char_u *buf, char *name)
/// name.
void shorten_buf_fname(buf_T *buf, char *dirname, int force)
{
- char *p;
-
if (buf->b_fname != NULL
&& !bt_nofilename(buf)
&& !path_with_url(buf->b_fname)
@@ -4164,7 +2327,7 @@ void shorten_buf_fname(buf_T *buf, char *dirname, int force)
if (buf->b_sfname != buf->b_ffname) {
XFREE_CLEAR(buf->b_sfname);
}
- p = path_shorten_fname(buf->b_ffname, dirname);
+ char *p = path_shorten_fname(buf->b_ffname, dirname);
if (p != NULL) {
buf->b_sfname = xstrdup(p);
buf->b_fname = buf->b_sfname;
@@ -4182,7 +2345,7 @@ void shorten_fnames(int force)
os_dirname(dirname, MAXPATHL);
FOR_ALL_BUFFERS(buf) {
- shorten_buf_fname(buf, (char *)dirname, force);
+ shorten_buf_fname(buf, dirname, force);
// Always make the swap file name a full path, a "nofile" buffer may
// also have a swap file.
@@ -4316,7 +2479,7 @@ bool vim_fgets(char *buf, int size, FILE *fp)
do {
tbuf[sizeof(tbuf) - 2] = NUL;
errno = 0;
- retval = fgets((char *)tbuf, sizeof(tbuf), fp);
+ retval = fgets(tbuf, sizeof(tbuf), fp);
if (retval == NULL && (feof(fp) || errno != EINTR)) {
break;
}
@@ -4452,6 +2615,38 @@ int put_time(FILE *fd, time_t time_)
return fwrite(buf, sizeof(uint8_t), ARRAY_SIZE(buf), fd) == 1 ? OK : FAIL;
}
+static int rename_with_tmp(const char *const from, const char *const to)
+{
+ // Find a name that doesn't exist and is in the same directory.
+ // Rename "from" to "tempname" and then rename "tempname" to "to".
+ if (strlen(from) >= MAXPATHL - 5) {
+ return -1;
+ }
+
+ char tempname[MAXPATHL + 1];
+ STRCPY(tempname, from);
+ for (int n = 123; n < 99999; n++) {
+ char *tail = path_tail(tempname);
+ snprintf(tail, (size_t)((MAXPATHL + 1) - (tail - tempname - 1)), "%d", n);
+
+ if (!os_path_exists(tempname)) {
+ if (os_rename(from, tempname) == OK) {
+ if (os_rename(tempname, to) == OK) {
+ return 0;
+ }
+ // Strange, the second step failed. Try moving the
+ // file back and return failure.
+ (void)os_rename(tempname, from);
+ return -1;
+ }
+ // If it fails for one temp name it will most likely fail
+ // for any temp name, give up.
+ return -1;
+ }
+ }
+ return -1;
+}
+
/// os_rename() only works if both files are on the same file system, this
/// function will (attempts to?) copy the file across if rename fails -- webb
///
@@ -4459,23 +2654,14 @@ int put_time(FILE *fd, time_t time_)
int vim_rename(const char *from, const char *to)
FUNC_ATTR_NONNULL_ALL
{
- int fd_in;
- int fd_out;
- int n;
char *errmsg = NULL;
- char *buffer;
- long perm;
-#ifdef HAVE_ACL
- vim_acl_T acl; // ACL from original file
-#endif
bool use_tmp_file = false;
// When the names are identical, there is nothing to do. When they refer
// to the same file (ignoring case and slash/backslash differences) but
// the file name differs we need to go through a temp file.
if (path_fnamecmp(from, to) == 0) {
- if (p_fic && (strcmp(path_tail((char *)from), path_tail((char *)to))
- != 0)) {
+ if (p_fic && (strcmp(path_tail(from), path_tail(to)) != 0)) {
use_tmp_file = true;
} else {
return 0;
@@ -4484,7 +2670,7 @@ int vim_rename(const char *from, const char *to)
// Fail if the "from" file doesn't exist. Avoids that "to" is deleted.
FileInfo from_info;
- if (!os_fileinfo((char *)from, &from_info)) {
+ if (!os_fileinfo(from, &from_info)) {
return -1;
}
@@ -4492,47 +2678,19 @@ int vim_rename(const char *from, const char *to)
// This happens when "from" and "to" differ in case and are on a FAT32
// filesystem. In that case go through a temp file name.
FileInfo to_info;
- if (os_fileinfo((char *)to, &to_info)
- && os_fileinfo_id_equal(&from_info, &to_info)) {
+ if (os_fileinfo(to, &to_info) && os_fileinfo_id_equal(&from_info, &to_info)) {
use_tmp_file = true;
}
if (use_tmp_file) {
- char tempname[MAXPATHL + 1];
-
- // Find a name that doesn't exist and is in the same directory.
- // Rename "from" to "tempname" and then rename "tempname" to "to".
- if (strlen(from) >= MAXPATHL - 5) {
- return -1;
- }
- STRCPY(tempname, from);
- for (n = 123; n < 99999; n++) {
- char *tail = path_tail(tempname);
- snprintf(tail, (size_t)((MAXPATHL + 1) - (tail - tempname - 1)), "%d", n);
-
- if (!os_path_exists(tempname)) {
- if (os_rename(from, tempname) == OK) {
- if (os_rename(tempname, to) == OK) {
- return 0;
- }
- // Strange, the second step failed. Try moving the
- // file back and return failure.
- (void)os_rename(tempname, from);
- return -1;
- }
- // If it fails for one temp name it will most likely fail
- // for any temp name, give up.
- return -1;
- }
- }
- return -1;
+ return rename_with_tmp(from, to);
}
// Delete the "to" file, this is required on some systems to make the
// os_rename() work, on other systems it makes sure that we don't have
// two files when the os_rename() fails.
- os_remove((char *)to);
+ os_remove(to);
// First try a normal rename, return if it works.
if (os_rename(from, to) == OK) {
@@ -4540,43 +2698,35 @@ int vim_rename(const char *from, const char *to)
}
// Rename() failed, try copying the file.
- perm = os_getperm(from);
-#ifdef HAVE_ACL
+ int perm = os_getperm(from);
// For systems that support ACL: get the ACL from the original file.
- acl = os_get_acl(from);
-#endif
- fd_in = os_open((char *)from, O_RDONLY, 0);
+ vim_acl_T acl = os_get_acl(from);
+ int fd_in = os_open(from, O_RDONLY, 0);
if (fd_in < 0) {
-#ifdef HAVE_ACL
os_free_acl(acl);
-#endif
return -1;
}
// Create the new file with same permissions as the original.
- fd_out = os_open((char *)to,
- O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW, (int)perm);
+ int fd_out = os_open(to, O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW, perm);
if (fd_out < 0) {
close(fd_in);
-#ifdef HAVE_ACL
os_free_acl(acl);
-#endif
return -1;
}
// Avoid xmalloc() here as vim_rename() is called by buf_write() when nvim
// is `preserve_exit()`ing.
- buffer = try_malloc(BUFSIZE);
+ char *buffer = try_malloc(WRITEBUFSIZE);
if (buffer == NULL) {
close(fd_out);
close(fd_in);
-#ifdef HAVE_ACL
os_free_acl(acl);
-#endif
return -1;
}
- while ((n = (int)read_eintr(fd_in, buffer, BUFSIZE)) > 0) {
+ int n;
+ while ((n = read_eintr(fd_in, buffer, WRITEBUFSIZE)) > 0) {
if (write_eintr(fd_out, buffer, (size_t)n) != n) {
errmsg = _("E208: Error writing to \"%s\"");
break;
@@ -4595,15 +2745,13 @@ int vim_rename(const char *from, const char *to)
#ifndef UNIX // For Unix os_open() already set the permission.
os_setperm(to, perm);
#endif
-#ifdef HAVE_ACL
os_set_acl(to, acl);
os_free_acl(acl);
-#endif
if (errmsg != NULL) {
semsg(errmsg, to);
return -1;
}
- os_remove((char *)from);
+ os_remove(from);
return 0;
}
@@ -4619,8 +2767,6 @@ static int already_warned = false;
/// @return true if some message was written (screen should be redrawn and cursor positioned).
int check_timestamps(int focus)
{
- int didit = 0;
-
// Don't check timestamps while system() or another low-level function may
// cause us to lose and gain focus.
if (no_check_timestamps > 0) {
@@ -4635,6 +2781,8 @@ int check_timestamps(int focus)
return false;
}
+ int didit = 0;
+
if (!stuff_empty() || global_busy || !typebuf_typed()
|| autocmd_busy || curbuf->b_ro_locked > 0
|| allbuf_lock > 0) {
@@ -4678,13 +2826,11 @@ static int move_lines(buf_T *frombuf, buf_T *tobuf)
{
buf_T *tbuf = curbuf;
int retval = OK;
- linenr_T lnum;
- char *p;
// Copy the lines in "frombuf" to "tobuf".
curbuf = tobuf;
- for (lnum = 1; lnum <= frombuf->b_ml.ml_line_count; lnum++) {
- p = xstrdup(ml_get_buf(frombuf, lnum, false));
+ for (linenr_T lnum = 1; lnum <= frombuf->b_ml.ml_line_count; lnum++) {
+ char *p = xstrdup(ml_get_buf(frombuf, lnum));
if (ml_append(lnum - 1, p, 0, false) == FAIL) {
xfree(p);
retval = FAIL;
@@ -4696,7 +2842,7 @@ static int move_lines(buf_T *frombuf, buf_T *tobuf)
// Delete all the lines in "frombuf".
if (retval != FAIL) {
curbuf = frombuf;
- for (lnum = curbuf->b_ml.ml_line_count; lnum > 0; lnum--) {
+ for (linenr_T lnum = curbuf->b_ml.ml_line_count; lnum > 0; lnum--) {
if (ml_delete(lnum, false) == FAIL) {
// Oops! We could try putting back the saved lines, but that
// might fail again...
@@ -4720,7 +2866,6 @@ int buf_check_timestamp(buf_T *buf)
FUNC_ATTR_NONNULL_ALL
{
int retval = 0;
- char *path;
char *mesg = NULL;
char *mesg2 = "";
bool helpmesg = false;
@@ -4735,8 +2880,6 @@ int buf_check_timestamp(buf_T *buf)
uint64_t orig_size = buf->b_orig_size;
int orig_mode = buf->b_orig_mode;
static bool busy = false;
- char *s;
- char *reason;
bufref_T bufref;
set_bufref(&bufref, buf);
@@ -4760,7 +2903,7 @@ int buf_check_timestamp(buf_T *buf)
&& (!(file_info_ok = os_fileinfo(buf->b_ffname, &file_info))
|| time_differs(&file_info, buf->b_mtime, buf->b_mtime_ns)
|| (int)file_info.stat.st_mode != buf->b_orig_mode)) {
- const long prev_b_mtime = buf->b_mtime;
+ const int64_t prev_b_mtime = buf->b_mtime;
retval = 1;
@@ -4784,6 +2927,7 @@ int buf_check_timestamp(buf_T *buf)
// was set, the global option value otherwise.
reload = RELOAD_NORMAL;
} else {
+ char *reason;
if (!file_info_ok) {
reason = "deleted";
} else if (bufIsChanged(buf)) {
@@ -4810,7 +2954,7 @@ int buf_check_timestamp(buf_T *buf)
if (!bufref_valid(&bufref)) {
emsg(_("E246: FileChangedShell autocommand deleted buffer"));
}
- s = get_vim_var_str(VV_FCS_CHOICE);
+ char *s = get_vim_var_str(VV_FCS_CHOICE);
if (strcmp(s, "reload") == 0 && *reason != 'd') {
reload = RELOAD_NORMAL;
} else if (strcmp(s, "edit") == 0) {
@@ -4836,8 +2980,8 @@ int buf_check_timestamp(buf_T *buf)
// checked out of CVS). Always warn when the buffer was
// changed.
if (reason[2] == 'n') {
- mesg = _(
- "W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
+ mesg =
+ _("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well");
mesg2 = _("See \":help W12\" for more info.");
} else if (reason[1] == 'h') {
mesg = _("W11: Warning: File \"%s\" has changed since editing started");
@@ -4863,7 +3007,7 @@ int buf_check_timestamp(buf_T *buf)
}
if (mesg != NULL) {
- path = home_replace_save(buf, buf->b_fname);
+ char *path = home_replace_save(buf, buf->b_fname);
if (!helpmesg) {
mesg2 = "";
}
@@ -4907,7 +3051,7 @@ int buf_check_timestamp(buf_T *buf)
if (emsg_silent == 0 && !in_assert_fails) {
ui_flush();
// give the user some time to think about it
- os_delay(1004L, true);
+ os_delay(1004, true);
// don't redraw and erase the message
redraw_cmdline = false;
@@ -4924,7 +3068,7 @@ int buf_check_timestamp(buf_T *buf)
// Reload the buffer.
buf_reload(buf, orig_mode, reload == RELOAD_DETECT);
if (buf->b_p_udf && buf->b_ffname != NULL) {
- char_u hash[UNDO_HASH_SIZE];
+ uint8_t hash[UNDO_HASH_SIZE];
// Any existing undo file is unusable, write it now.
u_compute_hash(buf, hash);
@@ -4946,8 +3090,6 @@ int buf_check_timestamp(buf_T *buf)
void buf_reload(buf_T *buf, int orig_mode, bool reload_options)
{
exarg_T ea;
- pos_T old_cursor;
- linenr_T old_topline;
int old_ro = buf->b_p_ro;
buf_T *savebuf;
bufref_T bufref;
@@ -4967,8 +3109,8 @@ void buf_reload(buf_T *buf, int orig_mode, bool reload_options)
prep_exarg(&ea, buf);
}
- old_cursor = curwin->w_cursor;
- old_topline = curwin->w_topline;
+ pos_T old_cursor = curwin->w_cursor;
+ linenr_T old_topline = curwin->w_topline;
if (p_ur < 0 || curbuf->b_ml.ml_line_count <= p_ur) {
// Save all the text, so that the reload can be undone.
@@ -4987,7 +3129,7 @@ void buf_reload(buf_T *buf, int orig_mode, bool reload_options)
savebuf = NULL;
} else {
// Allocate a buffer without putting it in the buffer list.
- savebuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
+ savebuf = buflist_new(NULL, NULL, 1, BLN_DUMMY);
set_bufref(&bufref, savebuf);
if (savebuf != NULL && buf == curbuf) {
// Open the memline.
@@ -5008,7 +3150,7 @@ void buf_reload(buf_T *buf, int orig_mode, bool reload_options)
if (saved == OK) {
curbuf->b_flags |= BF_CHECK_RO; // check for RO again
keep_filetype = true; // don't detect 'filetype'
- if (readfile(buf->b_ffname, buf->b_fname, (linenr_T)0, (linenr_T)0,
+ if (readfile(buf->b_ffname, buf->b_fname, 0, 0,
(linenr_T)MAXLNUM, &ea, flags, false) != OK) {
if (!aborting()) {
semsg(_("E321: Could not reload \"%s\""), buf->b_fname);
@@ -5104,12 +3246,10 @@ void write_lnum_adjust(linenr_T offset)
/// unless when it looks like a URL.
void forward_slash(char *fname)
{
- char *p;
-
if (path_with_url(fname)) {
return;
}
- for (p = fname; *p != NUL; p++) {
+ for (char *p = fname; *p != NUL; p++) {
if (*p == '\\') {
*p = '/';
}
@@ -5119,7 +3259,7 @@ void forward_slash(char *fname)
/// Path to Nvim's own temp dir. Ends in a slash.
static char *vim_tempdir = NULL;
-#if defined(HAVE_FLOCK) && defined(HAVE_DIRFD)
+#ifdef HAVE_DIRFD_AND_FLOCK
DIR *vim_tempdir_dp = NULL; ///< File descriptor of temp dir
#endif
@@ -5136,12 +3276,18 @@ static void vim_mktempdir(void)
char tmp[TEMP_FILE_PATH_MAXLEN];
char path[TEMP_FILE_PATH_MAXLEN];
char user[40] = { 0 };
+ char appname[40] = { 0 };
(void)os_get_username(user, sizeof(user));
// Usernames may contain slashes! #19240
memchrsub(user, '/', '_', sizeof(user));
memchrsub(user, '\\', '_', sizeof(user));
+ // Appname may be a relative path, replace slashes to make it name-like.
+ xstrlcpy(appname, get_appname(), sizeof(appname));
+ memchrsub(appname, '/', '%', sizeof(appname));
+ memchrsub(appname, '\\', '%', sizeof(appname));
+
// Make sure the umask doesn't remove the executable bit.
// "repl" has been reported to use "0177".
mode_t umask_save = umask(0077);
@@ -5154,7 +3300,9 @@ static void vim_mktempdir(void)
// "/tmp/" exists, now try to create "/tmp/nvim.<user>/".
add_pathsep(tmp);
- xstrlcat(tmp, "nvim.", sizeof(tmp));
+
+ xstrlcat(tmp, appname, sizeof(tmp));
+ xstrlcat(tmp, ".", sizeof(tmp));
xstrlcat(tmp, user, sizeof(tmp));
(void)os_mkdir(tmp, 0700); // Always create, to avoid a race.
bool owned = os_file_owned(tmp);
@@ -5212,11 +3360,11 @@ int readdir_core(garray_T *gap, const char *path, void *context, CheckItem check
Directory dir;
if (!os_scandir(&dir, path)) {
- smsg(_(e_notopen), path);
+ smsg(0, _(e_notopen), path);
return FAIL;
}
- for (;;) {
+ while (true) {
const char *p = os_scandir_next(&dir);
if (p == NULL) {
break;
@@ -5264,7 +3412,7 @@ int delete_recursive(const char *name)
if (readdir_core(&ga, exp, NULL, NULL) == OK) {
for (int i = 0; i < ga.ga_len; i++) {
vim_snprintf(NameBuff, MAXPATHL, "%s/%s", exp, ((char **)ga.ga_data)[i]);
- if (delete_recursive((const char *)NameBuff) != 0) {
+ if (delete_recursive(NameBuff) != 0) {
// Remember the failure but continue deleting any further
// entries.
result = -1;
@@ -5286,7 +3434,7 @@ int delete_recursive(const char *name)
return result;
}
-#if defined(HAVE_FLOCK) && defined(HAVE_DIRFD)
+#ifdef HAVE_DIRFD_AND_FLOCK
/// Open temporary directory and take file lock to prevent
/// to be auto-cleaned.
static void vim_opentempdir(void)
@@ -5323,7 +3471,7 @@ void vim_deltempdir(void)
return;
}
-#if defined(HAVE_FLOCK) && defined(HAVE_DIRFD)
+#ifdef HAVE_DIRFD_AND_FLOCK
vim_closetempdir();
#endif
// remove the trailing path separator
@@ -5337,10 +3485,20 @@ void vim_deltempdir(void)
/// Creates the directory on the first call.
char *vim_gettempdir(void)
{
- if (vim_tempdir == NULL) {
+ static int notfound = 0;
+ if (vim_tempdir == NULL || !os_isdir(vim_tempdir)) {
+ if (vim_tempdir != NULL) {
+ notfound++;
+ if (notfound == 1) {
+ ELOG("tempdir disappeared (antivirus or broken cleanup job?): %s", vim_tempdir);
+ }
+ if (notfound > 1) {
+ msg_schedule_semsg("E5431: tempdir disappeared (%d times)", notfound);
+ }
+ XFREE_CLEAR(vim_tempdir);
+ }
vim_mktempdir();
}
-
return vim_tempdir;
}
@@ -5361,7 +3519,7 @@ static bool vim_settempdir(char *tempdir)
vim_FullName(tempdir, buf, MAXPATHL, false);
add_pathsep(buf);
vim_tempdir = xstrdup(buf);
-#if defined(HAVE_FLOCK) && defined(HAVE_DIRFD)
+#ifdef HAVE_DIRFD_AND_FLOCK
vim_opentempdir();
#endif
xfree(buf);
@@ -5386,10 +3544,9 @@ char *vim_tempname(void)
// There is no need to check if the file exists, because we own the directory
// and nobody else creates a file in it.
- char template[TEMP_FILE_PATH_MAXLEN];
- snprintf(template, TEMP_FILE_PATH_MAXLEN,
- "%s%" PRIu64, tempdir, temp_count++);
- return xstrdup(template);
+ char templ[TEMP_FILE_PATH_MAXLEN];
+ snprintf(templ, TEMP_FILE_PATH_MAXLEN, "%s%" PRIu64, tempdir, temp_count++);
+ return xstrdup(templ);
}
/// Tries matching a filename with a "pattern" ("prog" is NULL), or use the
@@ -5413,13 +3570,7 @@ bool match_file_pat(char *pattern, regprog_T **prog, char *fname, char *sfname,
bool result = false;
regmatch.rm_ic = p_fic; // ignore case if 'fileignorecase' is set
- {
- if (prog != NULL) {
- regmatch.regprog = *prog;
- } else {
- regmatch.regprog = vim_regcomp(pattern, RE_MAGIC);
- }
- }
+ regmatch.regprog = prog != NULL ? *prog : vim_regcomp(pattern, RE_MAGIC);
// Try for a match with the pattern with:
// 1. the full file name, when the pattern has a '/'.
@@ -5427,10 +3578,10 @@ bool match_file_pat(char *pattern, regprog_T **prog, char *fname, char *sfname,
// 3. the tail of the file name, when the pattern has no '/'.
if (regmatch.regprog != NULL
&& ((allow_dirs
- && (vim_regexec(&regmatch, fname, (colnr_T)0)
+ && (vim_regexec(&regmatch, fname, 0)
|| (sfname != NULL
- && vim_regexec(&regmatch, sfname, (colnr_T)0))))
- || (!allow_dirs && vim_regexec(&regmatch, tail, (colnr_T)0)))) {
+ && vim_regexec(&regmatch, sfname, 0))))
+ || (!allow_dirs && vim_regexec(&regmatch, tail, 0)))) {
result = true;
}
@@ -5454,24 +3605,19 @@ bool match_file_pat(char *pattern, regprog_T **prog, char *fname, char *sfname,
bool match_file_list(char *list, char *sfname, char *ffname)
FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG(1, 3)
{
- char buf[100];
- char *tail;
- char *regpat;
- char allow_dirs;
- bool match;
- char *p;
-
- tail = path_tail(sfname);
+ char *tail = path_tail(sfname);
// try all patterns in 'wildignore'
- p = list;
+ char *p = list;
while (*p) {
+ char buf[MAXPATHL];
copy_option_part(&p, buf, ARRAY_SIZE(buf), ",");
- regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, false);
+ char allow_dirs;
+ char *regpat = file_pat_to_reg_pat(buf, NULL, &allow_dirs, false);
if (regpat == NULL) {
break;
}
- match = match_file_pat(regpat, NULL, ffname, sfname, tail, (int)allow_dirs);
+ bool match = match_file_pat(regpat, NULL, ffname, sfname, tail, (int)allow_dirs);
xfree(regpat);
if (match) {
return true;
@@ -5494,15 +3640,10 @@ bool match_file_list(char *list, char *sfname, char *ffname)
char *file_pat_to_reg_pat(const char *pat, const char *pat_end, char *allow_dirs, int no_bslash)
FUNC_ATTR_NONNULL_ARG(1)
{
- const char *endp;
- char *reg_pat;
- const char *p;
- int nested = 0;
- bool add_dollar = true;
-
if (allow_dirs != NULL) {
*allow_dirs = false;
}
+
if (pat_end == NULL) {
pat_end = pat + strlen(pat);
}
@@ -5513,7 +3654,7 @@ char *file_pat_to_reg_pat(const char *pat, const char *pat_end, char *allow_dirs
size_t size = 2; // '^' at start, '$' at end.
- for (p = pat; p < pat_end; p++) {
+ for (const char *p = pat; p < pat_end; p++) {
switch (*p) {
case '*':
case '.':
@@ -5534,7 +3675,7 @@ char *file_pat_to_reg_pat(const char *pat, const char *pat_end, char *allow_dirs
break;
}
}
- reg_pat = xmalloc(size + 1);
+ char *reg_pat = xmalloc(size + 1);
size_t i = 0;
@@ -5545,14 +3686,16 @@ char *file_pat_to_reg_pat(const char *pat, const char *pat_end, char *allow_dirs
} else {
reg_pat[i++] = '^';
}
- endp = pat_end - 1;
+ const char *endp = pat_end - 1;
+ bool add_dollar = true;
if (endp >= pat && *endp == '*') {
while (endp - pat > 0 && *endp == '*') {
endp--;
}
add_dollar = false;
}
- for (p = pat; *p && nested >= 0 && p <= endp; p++) {
+ int nested = 0;
+ for (const char *p = pat; *p && nested >= 0 && p <= endp; p++) {
switch (*p) {
case '*':
reg_pat[i++] = '.';
@@ -5602,11 +3745,7 @@ char *file_pat_to_reg_pat(const char *pat, const char *pat_end, char *allow_dirs
// regexp.
// An escaped { must be unescaped since we use magic not
// verymagic. Use "\\\{n,m\}"" to get "\{n,m}".
- if (*++p == '?'
-#ifdef BACKSLASH_IN_FILENAME
- && no_bslash
-#endif
- ) {
+ if (*++p == '?' && (!BACKSLASH_IN_FILENAME_BOOL || no_bslash)) {
reg_pat[i++] = '?';
} else if (*p == ',' || *p == '%' || *p == '#'
|| ascii_isspace(*p) || *p == '{' || *p == '}') {
@@ -5617,10 +3756,7 @@ char *file_pat_to_reg_pat(const char *pat, const char *pat_end, char *allow_dirs
p += 2;
} else {
if (allow_dirs != NULL && vim_ispathsep(*p)
-#ifdef BACKSLASH_IN_FILENAME
- && (!no_bslash || *p != '\\')
-#endif
- ) {
+ && (!BACKSLASH_IN_FILENAME_BOOL || (!no_bslash || *p != '\\'))) {
*allow_dirs = true;
}
reg_pat[i++] = '\\';
@@ -5683,35 +3819,35 @@ char *file_pat_to_reg_pat(const char *pat, const char *pat_end, char *allow_dirs
/// Version of read() that retries when interrupted by EINTR (possibly
/// by a SIGWINCH).
-long read_eintr(int fd, void *buf, size_t bufsize)
+int read_eintr(int fd, void *buf, size_t bufsize)
{
- long ret;
+ ssize_t ret;
- for (;;) {
- ret = read(fd, buf, bufsize);
+ while (true) {
+ ret = read(fd, buf, (unsigned)bufsize);
if (ret >= 0 || errno != EINTR) {
break;
}
}
- return ret;
+ return (int)ret;
}
/// Version of write() that retries when interrupted by EINTR (possibly
/// by a SIGWINCH).
-long write_eintr(int fd, void *buf, size_t bufsize)
+int write_eintr(int fd, void *buf, size_t bufsize)
{
- long ret = 0;
+ int ret = 0;
// Repeat the write() so long it didn't fail, other than being interrupted
// by a signal.
- while (ret < (long)bufsize) {
- long wlen = write(fd, (char *)buf + ret, bufsize - (size_t)ret);
+ while (ret < (int)bufsize) {
+ ssize_t wlen = write(fd, (char *)buf + ret, (unsigned)(bufsize - (size_t)ret));
if (wlen < 0) {
if (errno != EINTR) {
break;
}
} else {
- ret += wlen;
+ ret += (int)wlen;
}
}
return ret;