Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autocmd check filename in vim?

I want to write some autocmd's that check if the filename is this or that..

I've been trying:

autocmd VimEnter * if % is "preamble" | Explore | endif
autocmd VimEnter * if %=="preamble" | Explore | endif
autocmd VimEnter * if &filename == "preamble" | Explore | endif

but none of this works?

WHat should I do?

(this example is over-simplified, note that I'd also like to have an else statement).

like image 653
romeovs Avatar asked May 15 '11 16:05

romeovs


4 Answers

You should get the current file name as @%. For e.g., echo @% will give you the filename, whereas echo % will not. However, for actions on the file, use %, e.g. source %.

This should probably work for what you want to do:

autocmd VimEnter * if @% == 'preamble' | echo 'hello' | else | echo 'world' | endif
like image 85
abcd Avatar answered Nov 18 '22 10:11

abcd


Additional Info Using '@%' with autocmd

Some autocmd events do not support the @% named register to read the current file name. In these cases it is better to use <afile>:

expand('<afile>')
like image 29
cmcginty Avatar answered Oct 01 '22 02:10

cmcginty


autocmd BufRead,BufNewFile preamble Explore
like image 7
wilhelmtell Avatar answered Nov 18 '22 12:11

wilhelmtell


There are two problems with the examples in the original post:

  1. Neither the % nor &filename will return the filename as you've used them.
    Look at the help for the expand() function to see how to get the filename: :h expand()

  2. You're ignoring the slot in autocmd where a file-matching-pattern would ordinarily be specified. The third slot in the autocmd (* in your versions) is actually a pattern to match filenames. See :h autocmd-patterns. It should work okay if you want to ignore the pattern slot, but if so, you've got to fix the problem in paragraph 1 above. E.g.,

    autocmd BufRead,BufNewFile * if expand('%') =~ "preamble" | Explore | endif

like image 5
Herbert Sitz Avatar answered Nov 18 '22 10:11

Herbert Sitz