1

I use ack.vim, and have below keymap in my .vimrc,

nnoremap ;f :Ack! ^\"

to search for tags in my note files, which are lines that begin with double quote followed by non-space characters.

which works fine, since my note files lies in a common directory, say ~/notes.

Now, say at a git repo, eg, ~/code/some_repo, I want below keymap at that directory,

nnoremap ;f :Ack! ^\/\/\ *\"

I could manually set the keymap if work at given directory, but it soon become tedious.

So I wonder, how can I set keymap base on working directory when I start vim.

-- hopefully vimscript solution, with possible aid of bash command.

qeatzy
  • 1,363
  • 14
  • 21

2 Answers2

1

Have a look at https://stackoverflow.com/a/456889/15934

The solutions exposed can solve your question. Either by defining buffer specific mappings (:h :map-<buffer>, or by defining buffer variables that you could use in your mappings (:h b:var).

Community
  • 1
  • 1
Luc Hermitte
  • 31,979
  • 7
  • 69
  • 83
  • thanks for your response, but local vimrc is not what I pursuit, and I don't want install plugin for this since it should be a single command. I've used `autocmd`, but here I don't like to do config each time the file is read, which is wasteful. – qeatzy Mar 11 '17 at 14:44
  • You could use any solution presented in the other Q/A: strength and caveats have been explained as well. BTW if your autocommand only listens for BufEnter and BufCreate (IIRC) it'll be triggered only once per buffer. This is the minimum required. The caveat being the poor maintainability as it won't support moving stuff around, and it'll clutter the vimrc – Luc Hermitte Mar 11 '17 at 15:04
  • I didn't know `BufEnter` and `BufCreate` before, works like a charm, many thanks!! – qeatzy Mar 11 '17 at 15:17
0

As @Luc suggested, I could use autocmd base on file name with BufEnter and BufCreate. Which works fine.

Then I ask myself, why stick to command only?? Just utilize vim builtin functions and simple vimscript statement!!

So, let's break my requirement to different parts.

  1. get current working directory. -- getcwd().
  2. pattern match on that. -- =~. What does =~ mean in VimScript?
  3. do keymap base on match or not.

below is what's in my vimrc then,

"git, see also " grep
if getcwd() =~ "/code/repoA/"
    nnoremap ;f :Ack! ^\/\/\ *\"
    nnoremap ,a :!cd %:p:h && git add %<CR>
else
    nnoremap ;f :Ack! ^\"
endif
Community
  • 1
  • 1
qeatzy
  • 1,363
  • 14
  • 21