Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Vim from creating/opening a new file?

Tags:

vim

vi

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)

like image 582
user13107 Avatar asked Apr 18 '13 03:04

user13107


People also ask

Does Vim automatically add newline?

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.

What is a .UN file?

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~ .

How do I close a current file in Vim?

To save a file in Vim and exit, press Esc > Shift + ZZ. To exit Vim without saving, press Esc > Shift + ZX.

How do I open a new file in Vim editor without exit from that?

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.


2 Answers

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[@]}"
}
like image 76
John Kugelman Avatar answered Oct 06 '22 13:10

John Kugelman


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.

like image 29
alex Avatar answered Oct 06 '22 11:10

alex