Ask Ubuntu is a question and answer site for Ubuntu users and developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
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 '12 at 14:42

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.

share|improve this answer

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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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