3

Say, I want a specific vim mapping to be applicable only if the file name (better still, path) contains specific characters --- irrespective of filetype.

Can this be done? How? Or am I asking for too much?

1
  • it can be done, create script that checks your file name and contains a if else that changes the .vimrc based on the result from the file name check, then the script starts up vim with your file. last alias vim to your new script.
    – Darkmage
    Nov 21, 2012 at 14:42

2 Answers 2

7

Yes, you can do that with vim's autocmd command, by putting something like the following in your .vimrc file:

autocmd BufRead,BufNewFile /path/* map <buffer> <c-J> gqip

That will cause the map command to be executed whenever you start to edit a new (because of the BufNewFile event) or existing (because of the BufRead event) file that matches the pattern. Since the pattern contains a / it will be matched against the entire path of the file, if it didn't it would be matched against only the base name of the file. Using the <buffer> argument to the map command will apply the mapping only to the current buffer.

You can use :help autocmd to get additional information on defining autocmds, including the available events and details of the patterns that are supported.

1

I wanted a single conditional mapping to switch from the view template to the action and back using the Symfony plugin for Vim. I wanted the condition in the mapping itself because I don't like autocmd's very much.

In this example I match the filename (not the full path) against ".class"

" Symfony switch between action and view
nnoremap <expr> <leader>a match(expand('%:t'),'\.class') == -1 ? ':Saction<CR>' : ':Sview<CR>'

The syntax is:

nnoremap <expr> left_hand_side right_hand_side

and right_hand_side itself must have this format

condition ? mapping_for_when_its_true : mapping_for_when_its_false ;

both mappings must be enclosed in quotes.

See the :help expand() and :help match() to learn how to grab the file name or full path and match it against a string.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .