Background: I’m using this mapping map ,r :! bundle exec ruby %<CR> all the time to easily run test file I’m currently editing. However I also do:
map ,t :! bundle exec ruby test/integration/some_integration_test.rb<CR>
so that I can run this particular integration test with two key strokes while working on some other file. It has hard-coded path, when I move to some other area of the application I type above command with another integration test file path.
How to make a command that creates such mapping automatically?
map ,T :map ,t :! bundle exec ruby %<CR> won’t work because it doesn’t expand % while creating the mapping, so ,t will always run current file (while I want it to run file I was editing at the time of creating the mapping).
[EDIT]:
Slightly adjusted solution from the answer:
nnoremap ,r :! bundle exec ruby %<CR>
nnoremap ,T :let g:testfile = expand('%:p')
nnoremap ,t :! bundle exec ruby <C-r><C-r>=g:testfile<CR><CR>
,ralways runs file under cursor,Tsaves current file path under in a variable for running later,truns file path stored previously
Just save the current file name (best with a full absolute path to be immune against changes to the current directory; the
:pmodifier does that) in a variable, and insert the variable instead of%via<C-r>:PS: I used
:noremap, because that is generally safer and should be the first choice unless you really need remapping to occur.