2013-04-18 61 views
8

當我們給一個不存在的文件命名時,Vim會創建新的文件。這對我來說是不受歡迎的,因爲有時我會給出錯誤的文件名並且無意打開文件,然後關閉它。如何阻止Vim創建/打開新文件?

有沒有辦法阻止Vim打開新文件?例如,當我做vi file1,應該說File doesn't exist和留在bash終端(不開vi窗口)

回答

4

您可以將此函數添加到您的.bashrc(或等價物)。它在調用vim之前檢查它的命令行參數是否存在。如果你真的想創建一個新文件,你可以通過--new覆蓋檢查。

vim() { 
    local args=("[email protected]") 
    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[@]}" 
} 
5

它只會保存文件,如果使用寫(如:w:x,相當於:wq)選項。

改爲退出:q,並且不會創建任何文件。

+3

謝謝。但我想避免那些額外的擊鍵(':q')+看到空文件的驚喜。我只想留在碼頭上。 – user13107 2013-04-18 03:10:43

+1

'vim notexistencefile'不創建'notexistencefile',但創建相同的已命名緩衝區。 ':q',':q!'和'ZQ'在這種情況下只是從Vim退出,沒有任何文件寫入操作。 – 2013-04-18 08:48:25

相關問題