Search code examples
vimautocmd

How to write a pattern that excludes a string from the filename in a vim autocmd


I'd like to define different mappings for files which have the same suffix.

E.g. define a general mapping for all ruby files and a different mapping only for rspec files:

au BufNewFile,BufRead *_spec.rb map <Leader>t :w!<cr>:!rspec %<cr>
au BufNewFile,BufRead *.rb map <Leader>t :w!<cr>:!rspec %:r_spec.rb<cr>

The above solution does not work on my machine, because the second au "overwrites" the first one.

Is it possible to write this kind of au?

Update: just placing the most specific (spec) one below the generic one (rb) works if I have only one buffer opened. As soon as I open a spec file, the *.rb mapping is lost for the regular ruby files.


Solution

  • Reversing the autocommands and adding <buffer> should get you the desired behavior in this case, i.e.:

    au BufNewFile,BufRead *.rb      map <buffer> ,t action2
    au BufNewFile,BufRead *_spec.rb map <buffer> ,t action1
    

    This ordering will achieve the proper per-filename mappings.

    But you should note that when opening *_spec.rb files, both map commands will run: action1 and action2. This can be un-desireable for certain commands.

    Also, if you've set <Leader> to comma: ,, then your mappings should look like this:

    au BufNewFile,BufRead *.rb      map <buffer> <Leader>t action2
    au BufNewFile,BufRead *_spec.rb map <buffer> <Leader>t action1