17

I rarely, if ever, just open vim without filenames. Often enough, I want to test something out, usually a quick throwaway script, and I usually name them test.sh (or some variant thereof, like test.py). Can I make vim assume a test.sh filename if I ran vim without any filenames? I'd usually use aliases (like vims for vim test.sh and vimp for vim test.py, or go the whole :w test.sh), but I wonder if there's a way from within vim. It would be even better if I can restrict this to certain directories, like /tmp, or ~/dev.

10

Try putting this at the end of your .vimrc (modify as appropriate)

if @% == "" && getcwd() == "/tmp"
    :silent edit test.sh
endif

This checks if the current filename is empty (@% references the current filename), and checks if vim's current directory is /tmp. You could add other directories as well like so

(getcwd() == "/tmp" || getcwd() == "~/dev")

It then silently edits test.sh. If that file already exists, it'll load it. Otherwise, you'll start a new buffer with that name and the file will be created if you write it.

I did silent to suppress the following message during startup:

"test.sh" [New File]
Press ENTER or type command to continue
5

A modification of John's answer may be useful:

if @% == "" && getcwd() == "/tmp"
    :silent edit `=glob("test\.*", 1, 1)[0]`
endif

That opens the first file which begins with test..

Instead of just the first file, if you wanted to open other matching files as well, do:

if @% == "" && getcwd() == "/tmp"
    for i in glob("test\.*", 1, 1)
        :silent edit `=i`
    endfor
endif

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.