Shell – How to stop vim from editing directories

shellvim

Sometimes I accidentally tell vim to edit a directory instead of a file in it

vim directory-name           # what I typed
vim directory-name/blah.txt  # what I meant to type

Instead of immediately giving an error message, vim will open the directory in a "file editor" mode that I personally don't like:

The file browser I don't like

How can I make vim refuse to open directories instead?

One possible avenue could be by changing some settings in my .vimrc but I don't know what they would be.

Another possibility would be to create a wrapper shell alias around vim that checks with something along the lines of test -d "$1" to see if I'm trying to open a file. However, I don't know to make this alias robust so that it can tell apart which command-line arguments are flags and which are file names.

Best Answer

You can put the following lines in your vimrc to quit vim if any of its arguments are a directory:

for f in argv()
  if isdirectory(f)
    echomsg "vimrc: Cowardly refusing to edit directory " . f
    quit
  endif
endfor

Alternatively, if you only want to quit if all arguments are directories, you can try something like this:

let ndirs = 0
for f in argv()
  if isdirectory(f)
    let ndirs += 1
  endif
endfor
if ndirs > 0 && ndirs == argc()
  echomsg "vimrc: Cowardly refusing to edit directories"
  quit
endif
Related Question