如何阻止Vim创建/打开新文件?

时间:2013-04-18 03:05:31

标签: vim vi

当我们提供非现有文件的名称时,Vim会创建新文件。这对我来说是不可取的,因为有时候我会给出错误的文件名并且无意打开文件,然后关闭它。

有没有办法阻止Vim打开新文件?例如,当我执行vi file1时,应该说File doesn't exist并留在bash终端上(不打开vi窗口)

2 个答案:

答案 0 :(得分:6)

如果您使用写入(例如:w:x,相当于:wq)选项,它将仅保存文件。

改为退出:q,不会创建任何文件。

答案 1 :(得分:4)

您可以将此功能添加到.bashrc(或等效版本)。它在调用vim之前检查其命令行参数是否存在。如果您确实想要创建新文件,可以通过--new覆盖检查。

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[@]}"
}
相关问题