0

So, I can create custom key mapping for specific directories like this:

autocmd BufNewFile,BufRead <name of directory>* map <key> :! <command here>

This only executes the command in that specific directory. Say I have F5 as key, then outside of that directory, F5 does not do anything special. To add F5 to another directory, I simply repeat the above code and change name of directory and commands. This would get make my vimrc to be very messy if I have many directories that I need F5 to do stuff (just for example).

Is it possible to do something like this? `

if (directory = <dirA>) then 
   execute this command 
else if (directory = <dirB>) then 
   execute this command instead 
  • 1
    I'm pretty sure we already have a duplicate of this question on the site. – statox Mar 19 at 8:34
  • @statox i think i found it... should have searched prior to answering i suppose. – D. Ben Knoble Mar 19 at 13:09
  • @D.BenKnoble Thank you for finding it! It's not that bad that you wrote an answer as long as we are able to link the duplicates :) – statox Mar 19 at 13:53
3

Sure: use an <expr> mapping.

nnoremap <expr> <F5> My_mapping()

function! My_mapping
  if getcwd() ==# 'special'
    return 'special mapping'
  else
    return ''
  endif
endfunction

This differs slightly from the example given, in that it is re-evaluated each time the key is hit. I do this so that changes to the pwd during editing are propagated to the mapping. If you only care about directory at startup, you can use

if getcwd() ==# 'special'
  nnoremap <F5> <blah>
endif

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