18

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.

Martin Tournoij
  • 62,054
  • 25
  • 192
  • 271
muru
  • 24,838
  • 8
  • 82
  • 143

2 Answers2

11

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
John O'M.
  • 8,552
  • 2
  • 42
  • 58
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
saginaw
  • 6,756
  • 2
  • 26
  • 47
user50136
  • 191
  • 4