Can I tell vim to assume a filename ends in .tex if no extension is given? e.g. to open bird.tex if I say :e bird (unless there is a file bird with no extension).

  • 3
    Related: vi.stackexchange.com/q/239/205 - you can probably adapt one of those to use a check for extensions (or lack thereof) instead of checking the directory.
    – muru
    Feb 24, 2016 at 18:56

2 Answers 2


Adapting tricks I got from two of my previous questions, this should work:

function! EditTex(name)
    if a:name !~ '\.[^/]*$'
        setlocal bufhidden=wipe
        exe 'e' fnameescape(a:name).'.tex'
        set bufhidden<

autocmd BufNewFile * nested call EditTex(expand('<afile>'))

The function checks if the filename has an extension, and if not, starts editing a TeX file with that name. Since a BufNewFile autocmd will only run for files that don't exist, we can avoid that check.

With this, you can run :e bird as you normally would.


  • There is a problem with this, it creates bird.tex if you typ vi bird at the cmdline.
    – Toothrot
    Feb 27, 2016 at 13:52
  • @Lawrence Is that a problem? I would have thought that expected behaviour.
    – muru
    Feb 27, 2016 at 13:53
  • Oh, sorry, my q. wasn't quite clear. I wanted to open bird.tex unless bird existed, but not create a texfile when neither bird nor bird.tex existed from before. When I think about it, maybe this was just a bad idea: I also want to be able to create bird even though bird,tex exists. Sorry!
    – Toothrot
    Feb 27, 2016 at 14:00
  • 1
    @Lawrence then it is a bad idea, since you want to do both A and not A.
    – muru
    Feb 27, 2016 at 14:01

Maybe you could try the following custom command :E :

command! -nargs=1 -complete=file E
            \ let s:file = fnamemodify('<args>', ':p') |
            \ if fnamemodify(s:file, ':e') ==# '' && !filereadable(s:file) |
            \     edit <args>.tex |
            \ else |
            \     edit <args> |
            \ endif |
            \ unlet s:file

It checks if the filename given as an argument has no extension if it doesn't exist. In this case, it executes :edit {argument}.tex, otherwise it executes :edit {argument}.

So if you type: :E bird it should load a buffer whose name is bird.tex unless a file named bird already exists.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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