aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/nvim/fileio.c1914
-rw-r--r--src/nvim/os/fs.c2
-rw-r--r--src/nvim/os/os_defs.h6
-rw-r--r--src/nvim/undo.c2
4 files changed, 994 insertions, 930 deletions
diff --git a/src/nvim/fileio.c b/src/nvim/fileio.c
index 8c904f0c0a..a3cdd2bb23 100644
--- a/src/nvim/fileio.c
+++ b/src/nvim/fileio.c
@@ -85,7 +85,6 @@
# define UV_FS_COPYFILE_FICLONE 0
#endif
-#define HAS_BW_FLAGS
enum {
FIO_LATIN1 = 0x01, // convert Latin1
FIO_UTF8 = 0x02, // convert UTF-8
@@ -111,9 +110,7 @@ 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
@@ -125,6 +122,15 @@ struct bw_info {
iconv_t bw_iconv_fd; // descriptor for iconv() or -1
};
+typedef struct {
+ const char *num;
+ char *msg;
+ int arg;
+ bool alloc;
+} Error_T;
+
+static char *err_readonly = "is read-only (cannot override: \"W\" in 'cpoptions')";
+
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "fileio.c.generated.h"
#endif
@@ -387,13 +393,18 @@ 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) {
@@ -511,15 +522,18 @@ int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
}
return OK; // a new file is not an error
}
- 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]") :
-#endif
_("[Permission Denied]")), 0);
+#else
+ filemess(curbuf, sfname, ((fd == UV_EFBIG) ? _("[File too big]") :
+ _("[Permission Denied]")), 0);
+#endif
curbuf->b_p_ro = true; // must use "w!" now
return FAIL;
@@ -2083,6 +2097,658 @@ char *new_file_message(void)
return shortmess(SHM_NEW) ? _("[New]") : _("[New File]");
}
+static int buf_write_do_autocmds(buf_T *buf, char **fnamep, char **sfnamep, char **ffnamep,
+ linenr_T start, linenr_T *endp, exarg_T *eap, bool append,
+ bool filtering, bool reset_changed, bool overwriting, bool whole,
+ const pos_T orig_start, const pos_T orig_end)
+{
+ linenr_T old_line_count = buf->b_ml.ml_line_count;
+ int msg_save = msg_scroll;
+
+ aco_save_T aco;
+ bool did_cmd = false;
+ bool nofile_err = false;
+ bool empty_memline = buf->b_ml.ml_mfp == NULL;
+ bufref_T bufref;
+
+ char *sfname = *sfnamep;
+
+ // Apply PRE autocommands.
+ // Set curbuf to the buffer to be written.
+ // Careful: The autocommands may call buf_write() recursively!
+ bool buf_ffname = *ffnamep == buf->b_ffname;
+ bool buf_sfname = sfname == buf->b_sfname;
+ bool buf_fname_f = *fnamep == buf->b_ffname;
+ bool buf_fname_s = *fnamep == buf->b_sfname;
+
+ // Set curwin/curbuf to buf and save a few things.
+ aucmd_prepbuf(&aco, buf);
+ set_bufref(&bufref, buf);
+
+ if (append) {
+ did_cmd = apply_autocmds_exarg(EVENT_FILEAPPENDCMD, sfname, sfname, false, curbuf, eap);
+ if (!did_cmd) {
+ 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) {
+ bool 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 {
+ did_cmd = apply_autocmds_exarg(EVENT_FILEWRITECMD, sfname, sfname, false, curbuf, eap);
+ if (!did_cmd) {
+ 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
+ *endp = buf->b_ml.ml_line_count;
+ } else if (buf->b_ml.ml_line_count > old_line_count) { // more lines
+ *endp += buf->b_ml.ml_line_count - old_line_count;
+ } else { // less lines
+ *endp -= old_line_count - buf->b_ml.ml_line_count;
+ if (*endp < 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) {
+ *ffnamep = buf->b_ffname;
+ }
+ if (buf_sfname) {
+ *sfnamep = buf->b_sfname;
+ }
+ if (buf_fname_f) {
+ *fnamep = buf->b_ffname;
+ }
+ if (buf_fname_s) {
+ *fnamep = buf->b_sfname;
+ }
+ return NOTDONE;
+}
+
+static void buf_write_do_post_autocmds(buf_T *buf, char *fname, exarg_T *eap, bool append,
+ bool filtering, bool reset_changed, bool whole)
+{
+ 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);
+}
+
+static inline Error_T set_err_num(const char *num, const char *msg)
+{
+ return (Error_T){ .num = num, .msg = (char *)msg, .arg = 0 };
+}
+
+static inline Error_T set_err_arg(const char *msg, int arg)
+{
+ return (Error_T){ .num = NULL, .msg = (char *)msg, .arg = arg };
+}
+
+static inline Error_T set_err(const char *msg)
+{
+ return (Error_T){ .num = NULL, .msg = (char *)msg, .arg = 0 };
+}
+
+static void emit_err(Error_T *e)
+{
+ if (e->num != NULL) {
+ if (e->arg != 0) {
+ semsg("%s: %s%s: %s", e->num, IObuff, e->msg, os_strerror(e->arg));
+ } else {
+ semsg("%s: %s%s", e->num, IObuff, e->msg);
+ }
+ } else if (e->arg != 0) {
+ semsg(e->msg, os_strerror(e->arg));
+ } else {
+ emsg(e->msg);
+ }
+ if (e->alloc) {
+ xfree(e->msg);
+ }
+}
+
+#if defined(UNIX)
+
+static int get_fileinfo_os(char *fname, FileInfo *file_info_old, bool overwriting, long *perm,
+ bool *device, bool *newfile, Error_T *err)
+{
+ *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)) {
+ *err = set_err_num("E502", _("is a directory"));
+ return FAIL;
+ }
+ if (os_nodetype(fname) != NODE_WRITABLE) {
+ *err = set_err_num("E503", _("is not a file or writable device"));
+ return 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;
+ }
+ }
+ return OK;
+}
+
+#else
+
+static int get_fileinfo_os(char *fname, FileInfo *file_info_old, bool overwriting, long *perm,
+ bool *device, bool *newfile, Error_T *err)
+{
+ // Check for a writable device name.
+ char nodetype = fname == NULL ? NODE_OTHER : (char)os_nodetype(fname);
+ if (nodetype == NODE_OTHER) {
+ *err = set_err_num("E503", _("is not a file or writable device"));
+ return FAIL;
+ }
+ if (nodetype == 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)) {
+ *err = set_err_num("E502", _("is a directory"));
+ return FAIL;
+ }
+ if (overwriting) {
+ os_fileinfo(fname, file_info_old);
+ }
+ }
+ return OK;
+}
+
+#endif
+
+/// @param buf
+/// @param fname File name
+/// @param overwriting
+/// @param forceit
+/// @param[out] file_info_old
+/// @param[out] perm
+/// @param[out] device
+/// @param[out] newfile
+/// @param[out] readonly
+static int get_fileinfo(buf_T *buf, char *fname, bool overwriting, bool forceit,
+ FileInfo *file_info_old, long *perm, bool *device, bool *newfile,
+ bool *readonly, Error_T *err)
+{
+ if (get_fileinfo_os(fname, file_info_old, overwriting, perm, device, newfile, err) == FAIL) {
+ return FAIL;
+ }
+
+ *readonly = false; // overwritten file is read-only
+
+ if (!*device && !*newfile) {
+ // Check if the file is really writable (when renaming the file to
+ // make a backup we won't discover it later).
+ *readonly = !os_file_is_writable(fname);
+
+ if (!forceit && *readonly) {
+ if (vim_strchr(p_cpo, CPO_FWRITE) != NULL) {
+ *err = set_err_num("E504", _(err_readonly));
+ } else {
+ *err = set_err_num("E505", _("is read-only (add ! to override)"));
+ }
+ return FAIL;
+ }
+
+ // If 'forceit' is false, check if the timestamp hasn't changed since reading the file.
+ if (overwriting && !forceit) {
+ int retval = check_mtime(buf, file_info_old);
+ if (retval == FAIL) {
+ return FAIL;
+ }
+ }
+ }
+ return OK;
+}
+
+static int buf_write_make_backup(char *fname, bool append, FileInfo *file_info_old, vim_acl_T acl,
+ long perm, unsigned int bkc, bool file_readonly, bool forceit,
+ int *backup_copyp, char **backupp, Error_T *err)
+{
+ FileInfo file_info;
+ const bool no_prepend_dot = false;
+
+ if ((bkc & BKC_YES) || append) { // "yes"
+ *backup_copyp = true;
+ } else if ((bkc & BKC_AUTO)) { // "auto"
+ // 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_copyp = 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 (int 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;
+ }
+ }
+ int fd = os_open(IObuff,
+ O_CREAT|O_WRONLY|O_EXCL|O_NOFOLLOW, (int)perm);
+ if (fd < 0) { // can't write in directory
+ *backup_copyp = 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_copyp = 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_copyp = 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_copyp = false;
+ }
+#endif
+ }
+
+ // make sure we have a valid backup extension to use
+ char *backup_ext = *p_bex == NUL ? ".bak" : p_bex;
+
+ if (*backup_copyp) {
+ int some_error = false;
+
+ // 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.
+ char *dirp = p_bdir;
+ while (*dirp) {
+ // Isolate one directory name, using an entry in 'bdir'.
+ size_t dir_len = copy_option_part(&dirp, IObuff, IOSIZE, ",");
+ char *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) {
+ *backupp = modname(p, backup_ext, no_prepend_dot);
+ xfree(p);
+ }
+ }
+
+ char *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 (*backupp == NULL) {
+ *backupp = modname(rootname, backup_ext, no_prepend_dot);
+ }
+
+ if (*backupp == NULL) {
+ xfree(rootname);
+ some_error = true; // out of memory
+ goto nobackup;
+ }
+
+ // Check if backup file already exists.
+ if (os_fileinfo(*backupp, &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(*backupp); // 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.
+ //
+ char *wp = *backupp + strlen(*backupp) - 1 - strlen(backup_ext);
+ if (wp < *backupp) { // empty file name ???
+ wp = *backupp;
+ }
+ *wp = 'z';
+ while (*wp > 'a' && os_fileinfo(*backupp, &file_info_new)) {
+ (*wp)--;
+ }
+ // They all exist??? Must be something wrong.
+ if (*wp == 'a') {
+ XFREE_CLEAR(*backupp);
+ }
+ }
+ }
+ }
+ xfree(rootname);
+
+ // Try to create the backup file
+ if (*backupp != NULL) {
+ // remove old backup, if present
+ os_remove(*backupp);
+
+ // set file protection same as original file, but
+ // strip s-bit.
+ (void)os_setperm((const char *)(*backupp), 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(*backupp, (uv_uid_t)-1, (uv_gid_t)file_info_old->stat.st_gid) != 0) {
+ os_setperm((const char *)(*backupp),
+ ((int)perm & 0707) | (((int)perm & 07) << 3));
+ }
+#endif
+
+ // copy the file
+ if (os_copy(fname, *backupp, UV_FS_COPYFILE_FICLONE) != 0) {
+ *err = set_err(_("E509: Cannot create backup file (add ! to override)"));
+ XFREE_CLEAR(*backupp);
+ *backupp = NULL;
+ continue;
+ }
+
+#ifdef UNIX
+ os_file_settime(*backupp,
+ (double)file_info_old->stat.st_atim.tv_sec,
+ (double)file_info_old->stat.st_mtim.tv_sec);
+#endif
+ os_set_acl(*backupp, acl);
+ *err = set_err(NULL);
+ break;
+ }
+ }
+
+nobackup:
+ if (*backupp == NULL && err->msg == NULL) {
+ *err = set_err(_("E509: Cannot create backup file (add ! to override)"));
+ }
+ // Ignore errors when forceit is true.
+ if ((some_error || err->msg != NULL) && !forceit) {
+ return FAIL;
+ }
+ *err = set_err(NULL);
+ } else {
+ // 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) {
+ *err = set_err_num("E504", _(err_readonly));
+ return 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.
+ char *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, ",");
+ char *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) {
+ *backupp = modname(p, backup_ext, no_prepend_dot);
+ xfree(p);
+ }
+ }
+
+ if (*backupp == NULL) {
+ char *rootname = get_file_in_dir(fname, IObuff);
+ if (rootname == NULL) {
+ *backupp = NULL;
+ } else {
+ *backupp = modname(rootname, backup_ext, no_prepend_dot);
+ xfree(rootname);
+ }
+ }
+
+ if (*backupp != 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(*backupp)) {
+ p = *backupp + strlen(*backupp) - 1 - strlen(backup_ext);
+ if (p < *backupp) { // empty file name ???
+ p = *backupp;
+ }
+ *p = 'z';
+ while (*p > 'a' && os_path_exists(*backupp)) {
+ (*p)--;
+ }
+ // They all exist??? Must be something wrong!
+ if (*p == 'a') {
+ XFREE_CLEAR(*backupp);
+ }
+ }
+ }
+ if (*backupp != 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, *backupp) == 0) {
+ break;
+ }
+
+ XFREE_CLEAR(*backupp); // don't do the rename below
+ }
+ }
+ if (*backupp == NULL && !forceit) {
+ *err = set_err(_("E510: Can't make backup file (add ! to override)"));
+ return FAIL;
+ }
+ }
+ return OK;
+}
+
/// buf_write() - write to file "fname" lines "start" through "end"
///
/// We do our own buffering here because fwrite() is so slow.
@@ -2104,68 +2770,14 @@ char *new_file_message(void)
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];
- 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;
@@ -2189,6 +2801,7 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
}
// must init bw_conv_buf and bw_iconv_fd before jumping to "fail"
+ struct bw_info write_info; // info for buf_write_bytes()
write_info.bw_conv_buf = NULL;
write_info.bw_conv_error = false;
write_info.bw_conv_error_lnum = 0;
@@ -2226,195 +2839,30 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
// 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
+ char *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;
- }
+// true if writing over original
+ int overwriting = buf->b_ffname != NULL && path_fnamecmp(ffname, buf->b_ffname) == 0;
no_wait_return++; // don't wait for return yet
+ const pos_T orig_start = buf->b_op_start;
+ const pos_T orig_end = buf->b_op_end;
+
// 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;
- }
+ int res = buf_write_do_autocmds(buf, &fname, &sfname, &ffname, start, &end, eap, append,
+ filtering, reset_changed, overwriting, whole, orig_start,
+ orig_end);
+ if (res != NOTDONE) {
+ return res;
}
if (cmdmod.cmod_flags & CMOD_LOCKMARKS) {
@@ -2429,17 +2877,18 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
msg_scroll = true; // don't overwrite previous file message
}
if (!filtering) {
- filemess(buf,
+ // show that we are busy
#ifndef UNIX
- sfname,
+ filemess(buf, sfname, "", 0);
#else
- fname,
+ filemess(buf, fname, "", 0);
#endif
- "", 0); // show that we are busy
}
msg_scroll = false; // always overwrite the file message now
- buffer = verbose_try_malloc(BUFSIZE);
+ char *buffer = verbose_try_malloc(BUFSIZE);
+ int bufsize;
+ char smallbuf[SMBUFSIZE];
// can't allocate big buffer, use small one (to be able to write when out of
// memory)
if (buffer == NULL) {
@@ -2449,91 +2898,38 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
bufsize = BUFSIZE;
}
+ Error_T err = { 0 };
+ long perm; // file permissions
+ bool newfile = false; // true if file doesn't exist yet
+ bool device = false; // writing to a device
+ bool file_readonly = false; // overwritten file is read-only
+ char *backup = NULL;
+ char *fenc_tofree = NULL; // allocated "fenc"
+
// 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;
- }
+ vim_acl_T acl = NULL; // ACL copied from original file to
+ // backup or new file
- // 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;
- }
- }
+ if (get_fileinfo(buf, fname, overwriting, forceit, &file_info_old, &perm, &device, &newfile,
+ &file_readonly, &err) == 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);
+ bool dobackup = (p_wb || p_bk || *p_pm != NUL);
if (dobackup && *p_bsk != NUL && match_file_list(p_bsk, sfname, ffname)) {
dobackup = false;
}
+ int backup_copy = false; // copy the original file?
+
// 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.
@@ -2550,321 +2946,16 @@ int buf_write(buf_T *buf, char *fname, char *sfname, linenr_T start, linenr_T en
// 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"
- // 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 (int 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
- char *backup_ext = *p_bex == NUL ? ".bak" : p_bex;
-
- if (backup_copy) {
- int some_error = false;
-
- // 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.
- char *dirp = p_bdir;
- while (*dirp) {
- // Isolate one directory name, using an entry in 'bdir'.
- size_t dir_len = copy_option_part(&dirp, IObuff, IOSIZE, ",");
- char *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);
- }
- }
-
- char *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.
- //
- char *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 {
- // 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.
- char *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, ",");
- char *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) {
- char *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 (buf_write_make_backup(fname, append, &file_info_old, acl, perm, bkc, file_readonly, forceit,
+ &backup_copy, &backup, &err) == FAIL) {
+ retval = FAIL;
+ goto fail;
}
}
#if defined(UNIX)
+ int made_writable = false; // 'w' bit has been set
+
// 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()
@@ -2890,6 +2981,8 @@ nobackup:
start = end + 1;
}
+ char *wfname = NULL; // name of file to write to
+
// 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
@@ -2899,7 +2992,7 @@ nobackup:
&& !(exiting && backup != NULL)) {
ml_preserve(buf, false, !!p_fs);
if (got_int) {
- SET_ERRMSG(_(e_interr));
+ err = set_err(_(e_interr));
goto restore_backup;
}
}
@@ -2908,6 +3001,8 @@ nobackup:
// multi-byte conversion.
wfname = fname;
+ char *fenc; // effective 'fileencoding'
+
// Check for forced 'fileencoding' from "++opt=val" argument.
if (eap != NULL && eap->force_enc != 0) {
fenc = eap->cmd + eap->force_enc;
@@ -2918,7 +3013,8 @@ nobackup:
}
// Check if the file needs to be converted.
- converted = need_conversion(fenc);
+ int converted = need_conversion(fenc);
+ int wb_flags = 0;
// 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().
@@ -2958,23 +3054,33 @@ nobackup:
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"));
+ err = set_err(_("E214: Can't find temp file for writing"));
goto restore_backup;
}
}
}
}
+ int notconverted = false;
+
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)"));
+ err = set_err(_("E213: Cannot convert (add ! to write without conversion)"));
goto restore_backup;
}
notconverted = true;
}
+ int no_eol = false; // no end-of-line written
+ long nchars;
+ linenr_T lnum;
+ int fileformat;
+ int checking_conversion;
+
+ int fd;
+
// 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.
@@ -3000,18 +3106,16 @@ nobackup:
// 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) {
+ const int fflags = O_WRONLY | (append
+ ? (forceit ? (O_APPEND | O_CREAT) : O_APPEND)
+ : (O_CREAT | O_TRUNC));
+ const int mode = perm < 0 ? 0666 : (perm & 0777);
+
+ while ((fd = os_open(wfname, fflags, mode)) < 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) {
+ if (err.msg == NULL) {
#ifdef UNIX
FileInfo file_info;
@@ -3019,31 +3123,34 @@ nobackup:
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"));
+ err = set_err(_("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;
+ err = set_err_arg(_("E212: Can't open file for writing: %s"), fd);
+ if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL && perm >= 0) {
+ // 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;
+ }
+ if (!append) { // don't remove when appending
+ os_remove(wfname);
+ }
+ continue;
}
-#endif
+ }
+#else
+ err = set_err_arg(_("E212: Can't open file for writing: %s"), fd);
+ if (forceit && vim_strchr(p_cpo, CPO_FWRITE) == NULL && perm >= 0) {
if (!append) { // don't remove when appending
os_remove(wfname);
}
continue;
}
-#ifdef UNIX
- }
#endif
}
@@ -3085,12 +3192,13 @@ restore_backup:
}
write_info.bw_fd = fd;
}
- SET_ERRMSG(NULL);
+ err = set_err(NULL);
write_info.bw_buf = buffer;
nchars = 0;
// use "++bin", "++nobin" or 'binary'
+ int write_bin;
if (eap != NULL && eap->force_bin != 0) {
write_bin = (eap->force_bin == FORCE_BIN);
} else {
@@ -3121,19 +3229,18 @@ restore_backup:
}
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;
+ char *s = buffer;
+ int 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;
+ char *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));
}
+ char c;
while ((c = *++ptr) != NUL) {
if (c == NL) {
*s = NUL; // replace newlines with NULs
@@ -3235,7 +3342,7 @@ restore_backup:
if (p_fs && (error = os_fsync(fd)) != 0 && !device
// fsync not supported on this storage.
&& error != UV_ENOTSUP) {
- SET_ERRMSG_ARG(e_fsync, error);
+ err = set_err_arg(e_fsync, error);
end = 0;
}
@@ -3262,7 +3369,7 @@ restore_backup:
#endif
if ((error = os_close(fd)) != 0) {
- SET_ERRMSG_ARG(_("E512: Close failed: %s"), error);
+ err = set_err_arg(_("E512: Close failed: %s"), error);
end = 0;
}
@@ -3274,13 +3381,11 @@ restore_backup:
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
@@ -3298,23 +3403,23 @@ restore_backup:
if (end == 0) {
// Error encountered.
- if (errmsg == NULL) {
+ if (err.msg == 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)"));
+ err = set_err(_("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)
+ err = set_err(xmalloc(300));
+ err.alloc = true;
+ vim_snprintf(err.msg, 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));
+ err = set_err(_(e_interr));
} else {
- SET_ERRMSG(_("E514: write error (file system full?)"));
+ err = set_err(_("E514: write error (file system full?)"));
}
}
@@ -3356,37 +3461,37 @@ restore_backup:
#endif
if (!filtering) {
add_quoted_fname(IObuff, IOSIZE, buf, (const char *)fname);
- c = false;
+ bool insert_space = false;
if (write_info.bw_conv_error) {
STRCAT(IObuff, _(" CONVERSION ERROR"));
- c = true;
+ insert_space = 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;
+ insert_space = true;
} else if (converted) {
STRCAT(IObuff, _("[converted]"));
- c = true;
+ insert_space = true;
}
if (device) {
STRCAT(IObuff, _("[Device]"));
- c = true;
+ insert_space = true;
} else if (newfile) {
STRCAT(IObuff, new_file_message());
- c = true;
+ insert_space = true;
}
if (no_eol) {
msg_add_eol();
- c = true;
+ insert_space = true;
}
// may add [unix/dos/mac]
if (msg_add_fileformat(fileformat)) {
- c = true;
+ insert_space = true;
}
- msg_add_lines(c, (long)lnum, nchars); // add line/char count
+ msg_add_lines(insert_space, (long)lnum, nchars); // add line/char count
if (!shortmess(SHM_WRITE)) {
if (append) {
STRCAT(IObuff, shortmess(SHM_WRI) ? _(" [a]") : _(" appended"));
@@ -3491,31 +3596,16 @@ nofail:
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) {
+ if (err.msg != 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);
- }
+ emit_err(&err);
retval = FAIL;
if (end == 0) {
@@ -3546,31 +3636,7 @@ nofail:
}
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);
-
+ buf_write_do_post_autocmds(buf, fname, eap, append, filtering, reset_changed, whole);
if (aborting()) { // autocmds may abort script processing
retval = false;
}
@@ -3579,9 +3645,6 @@ nofail:
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
@@ -3725,170 +3788,191 @@ static int check_mtime(buf_T *buf, FileInfo *file_info)
static bool time_differs(const FileInfo *file_info, long mtime, long 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)
+static int buf_write_convert_with_iconv(struct bw_info *ip, char **bufp, int *lenp)
{
- 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
+ const char *from;
+ size_t fromlen;
+ size_t tolen;
+
+ int len = *lenp;
+
+ // Convert with iconv().
+ if (ip->bw_restlen > 0) {
+ // 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;
+ char *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, *bufp, (size_t)len);
+ from = fp;
+ tolen = ip->bw_conv_buflen - fromlen;
+ } else {
+ from = *bufp;
+ fromlen = (size_t)len;
+ tolen = ip->bw_conv_buflen;
+ }
+ char *to = ip->bw_conv_buf;
- // Skip conversion when writing the BOM.
- if (!(flags & FIO_NOCONVERT)) {
- if (flags & FIO_UTF8) {
- // Convert latin1 in the buffer to UTF-8 in the file.
- char *p = ip->bw_conv_buf; // translate to buffer
- for (int 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)) {
- unsigned c;
- int n = 0;
- // Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
- // Latin1 chars in the file.
- // translate in-place (can only get shorter) or to buffer
- char *p = flags & FIO_LATIN1 ? buf : ip->bw_conv_buf;
- for (int wlen = 0; wlen < len; wlen += n) {
- if (wlen == 0 && ip->bw_restlen != 0) {
- // Use remainder of previous call. Append the start of
- // buf[] to get a full sequence. Might still be too
- // short!
- int l = MIN(len, CONV_RESTLEN - ip->bw_restlen);
- 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 (ip->bw_first) {
+ size_t save_len = tolen;
- 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);
- }
+ // 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 (ip->bw_iconv_fd != (iconv_t)-1) {
- const char *from;
- size_t fromlen;
- size_t tolen;
-
- // Convert with iconv().
- if (ip->bw_restlen > 0) {
- // 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;
- char *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;
- }
- char *to = ip->bw_conv_buf;
+ // 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;
- if (ip->bw_first) {
- size_t save_len = tolen;
+ *bufp = ip->bw_conv_buf;
+ *lenp = (int)(to - ip->bw_conv_buf);
- // output the initial shift state sequence
- (void)iconv(ip->bw_iconv_fd, NULL, NULL, &to, &tolen);
+ return OK;
+}
- // 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;
+static int buf_write_convert(struct bw_info *ip, char **bufp, int *lenp)
+{
+ int flags = ip->bw_flags; // extra flags
+
+ if (flags & FIO_UTF8) {
+ // Convert latin1 in the buffer to UTF-8 in the file.
+ char *p = ip->bw_conv_buf; // translate to buffer
+ for (int wlen = 0; wlen < *lenp; wlen++) {
+ p += utf_char2bytes((uint8_t)(*bufp)[wlen], p);
+ }
+ *bufp = ip->bw_conv_buf;
+ *lenp = (int)(p - ip->bw_conv_buf);
+ } else if (flags & (FIO_UCS4 | FIO_UTF16 | FIO_UCS2 | FIO_LATIN1)) {
+ unsigned c;
+ int n = 0;
+ // Convert UTF-8 bytes in the buffer to UCS-2, UCS-4, UTF-16 or
+ // Latin1 chars in the file.
+ // translate in-place (can only get shorter) or to buffer
+ char *p = flags & FIO_LATIN1 ? *bufp : ip->bw_conv_buf;
+ for (int wlen = 0; wlen < *lenp; wlen += n) {
+ if (wlen == 0 && ip->bw_restlen != 0) {
+ // Use remainder of previous call. Append the start of
+ // buf[] to get a full sequence. Might still be too
+ // short!
+ int l = MIN(*lenp, CONV_RESTLEN - ip->bw_restlen);
+ memmove(ip->bw_rest + ip->bw_restlen, *bufp, (size_t)l);
+ n = utf_ptr2len_len((char *)ip->bw_rest, ip->bw_restlen + l);
+ if (n > ip->bw_restlen + *lenp) {
+ // 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 + *lenp > CONV_RESTLEN) {
+ return FAIL;
+ }
+ ip->bw_restlen += *lenp;
+ 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(*bufp + wlen, *lenp - wlen);
+ if (n > *lenp - 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 (*lenp - wlen > CONV_RESTLEN) {
+ return FAIL;
+ }
+ ip->bw_restlen = *lenp - wlen;
+ memmove(ip->bw_rest, *bufp + wlen,
+ (size_t)ip->bw_restlen);
+ break;
+ }
+ if (n > 1) {
+ c = (unsigned)utf_ptr2char(*bufp + wlen);
+ } else {
+ c = (uint8_t)(*bufp)[wlen];
}
- 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) {
+ if (ucs2bytes(c, &p, flags) && !ip->bw_conv_error) {
ip->bw_conv_error = true;
- return FAIL;
+ ip->bw_conv_error_lnum = ip->bw_start_lnum;
}
-
- // copy remainder to ip->bw_rest[] to be used for the next call.
- if (fromlen > 0) {
- memmove(ip->bw_rest, (void *)from, fromlen);
+ if (c == NL) {
+ ip->bw_start_lnum++;
}
- ip->bw_restlen = (int)fromlen;
+ }
+ if (flags & FIO_LATIN1) {
+ *lenp = (int)(p - *bufp);
+ } else {
+ *bufp = ip->bw_conv_buf;
+ *lenp = (int)(p - ip->bw_conv_buf);
+ }
+ }
- buf = ip->bw_conv_buf;
- len = (int)(to - ip->bw_conv_buf);
+ if (ip->bw_iconv_fd != (iconv_t)-1) {
+ if (buf_write_convert_with_iconv(ip, bufp, lenp) == FAIL) {
+ return FAIL;
+ }
+ }
+
+ return OK;
+}
+
+/// 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)
+{
+ char *buf = ip->bw_buf; // data to write
+ int len = ip->bw_len; // length of data
+ int flags = ip->bw_flags; // extra flags
+
+ // Skip conversion when writing the BOM.
+ if (!(flags & FIO_NOCONVERT)) {
+ if (buf_write_convert(ip, &buf, &len) == FAIL) {
+ return FAIL;
}
}
@@ -4414,6 +4498,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
///
@@ -4421,12 +4537,7 @@ 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;
char *errmsg = NULL;
-#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
@@ -4457,34 +4568,7 @@ int vim_rename(const char *from, const char *to)
}
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 (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;
+ return rename_with_tmp(from, to);
}
// Delete the "to" file, this is required on some systems to make the
@@ -4500,26 +4584,19 @@ int vim_rename(const char *from, const char *to)
// Rename() failed, try copying the file.
long perm = os_getperm(from);
-#ifdef HAVE_ACL
// 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((char *)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((char *)to, O_CREAT|O_EXCL|O_WRONLY|O_NOFOLLOW, (int)perm);
if (fd_out < 0) {
close(fd_in);
-#ifdef HAVE_ACL
os_free_acl(acl);
-#endif
return -1;
}
@@ -4529,9 +4606,7 @@ int vim_rename(const char *from, const char *to)
if (buffer == NULL) {
close(fd_out);
close(fd_in);
-#ifdef HAVE_ACL
os_free_acl(acl);
-#endif
return -1;
}
@@ -4555,10 +4630,8 @@ 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;
@@ -5367,13 +5440,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 '/'.
@@ -5548,11 +5615,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 == '}') {
@@ -5563,10 +5626,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++] = '\\';
diff --git a/src/nvim/os/fs.c b/src/nvim/os/fs.c
index 85d95960a7..7eba5ca54c 100644
--- a/src/nvim/os/fs.c
+++ b/src/nvim/os/fs.c
@@ -783,6 +783,7 @@ int os_setperm(const char *const name, int perm)
# ifdef HAVE_SYS_ACCESS_H
# include <sys/access.h>
# endif
+#endif
// Return a pointer to the ACL of file "fname" in allocated memory.
// Return NULL if the ACL is not available for whatever reason.
@@ -806,7 +807,6 @@ void os_free_acl(vim_acl_T aclent)
return;
}
}
-#endif
#ifdef UNIX
/// Checks if the current user owns a file.
diff --git a/src/nvim/os/os_defs.h b/src/nvim/os/os_defs.h
index a30e16eeba..f86c0d3483 100644
--- a/src/nvim/os/os_defs.h
+++ b/src/nvim/os/os_defs.h
@@ -13,6 +13,12 @@
# include "nvim/os/unix_defs.h"
#endif
+#ifdef BACKSLASH_IN_FILENAME
+# define BACKSLASH_IN_FILENAME_BOOL true
+#else
+# define BACKSLASH_IN_FILENAME_BOOL false
+#endif
+
#if !defined(NAME_MAX) && defined(_XOPEN_NAME_MAX)
# define NAME_MAX _XOPEN_NAME_MAX
#endif
diff --git a/src/nvim/undo.c b/src/nvim/undo.c
index 0f12c00f15..2b5dd297b5 100644
--- a/src/nvim/undo.c
+++ b/src/nvim/undo.c
@@ -1339,14 +1339,12 @@ write_error:
semsg(_("E829: write error in undo file: %s"), file_name);
}
-#ifdef HAVE_ACL
if (buf->b_ffname != NULL) {
// For systems that support ACL: get the ACL from the original file.
vim_acl_T acl = os_get_acl(buf->b_ffname);
os_set_acl(file_name, acl);
os_free_acl(acl);
}
-#endif
theend:
if (file_name != name) {