diff options
| author | Lewis Russell <lewis6991@gmail.com> | 2023-02-15 16:45:20 +0000 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-02-15 16:45:20 +0000 |
| commit | f006313e95022340b2b0ae28e8223e6e548f0826 (patch) | |
| tree | 2bf46d9f1b2c236afacefdafbd3d121023714188 /src | |
| parent | ec782211f2305382b3a6cb72ab0bbfcab0efcdf0 (diff) | |
| parent | 6aee2336ca75301bd4db6b99c2392f63f8304335 (diff) | |
| download | rneovim-f006313e95022340b2b0ae28e8223e6e548f0826.tar.gz rneovim-f006313e95022340b2b0ae28e8223e6e548f0826.tar.bz2 rneovim-f006313e95022340b2b0ae28e8223e6e548f0826.zip | |
Merge pull request #22056 from lewis6991/refactor/fileio_more
refactor `fileio.c`
Diffstat (limited to 'src')
| -rw-r--r-- | src/nvim/fileio.c | 1914 | ||||
| -rw-r--r-- | src/nvim/os/fs.c | 2 | ||||
| -rw-r--r-- | src/nvim/os/os_defs.h | 6 | ||||
| -rw-r--r-- | src/nvim/undo.c | 2 |
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 |