Vim creates new files when we give name of a non existing file. This is undesirable to me, as sometimes I give wrong file name and have no intention to open a file, and then close it.
Is there a way that will stop Vim from opening new files? For example, when I do vi file1
, it should say File doesn't exist
and stay on the bash
terminal (without opening vi
window)
That's why Vim always adds a newline by default (because, according to POSIX, it should always be there). It is not the only editor doing that. Gedit, the default text editor in GNOME, does the same exact thing.
When you edit and save files, Vim creates a file with the same name as the original file and an un~ extension at the end. Vim 7.3 contains a new feature persistent undo, that is, undo information won't be lost when quitting Vim and be stored in a file that ends with .un~ .
To save a file in Vim and exit, press Esc > Shift + ZZ. To exit Vim without saving, press Esc > Shift + ZX.
Opening a new file for editing If you're already in vim, then there's no need to exit it just to open a new file. That will open the file for editing. You can also use the tab-key for autocompletion of the path. Please note that the current file must be saved, or you've to use :e! to discard the unsaved changes.
You could add this function to your .bashrc (or equivalent). It checks that its command-line arguments exist before it invokes vim. If you really want to create a new file you can pass --new
to override the checks.
vim() {
local args=("$@")
local new=0
# Check for `--new'.
for ((i = 0; i < ${#args[@]}; ++i)); do
if [[ ${args[$i]} = --new ]]; then
new=1
unset args[$i] # Don't pass `--new' to vim.
fi
done
if ! (( new )); then
for file in "${args[@]}"; do
[[ $file = -* ]] && continue # Ignore options.
if ! [[ -e $file ]]; then
printf '%s: cannot access %s: No such file or directory\n' "$FUNCNAME" "$file" >&2
return 1
fi
done
fi
# Use `command' to invoke the vim binary rather than this function.
command "$FUNCNAME" "${args[@]}"
}
It will only save the file if you use a write (e.g. :w
or :x
, equivalent of :wq
) option.
Exit with :q
instead, and no file will be created.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With