2

I'd like to use the key binding M-n p for ess-swv-purl in .Rmd documents and thus tried (define-key global-set-key (kbd "M-n p") 'ess-swv-purl). If I'm in an .Rmd (Rmarkdown) document, M-n p still shows (M-n p is undefined).

I understand that global key settings are overwritten in many ways, but if the key combination is not bound, where is the problem? (I can execute the function with M-x ess-swv-purl). In case this helps, C-h b shows that M-n is a "Prefix Command" under poly-markdown+r-mode. I tried something like (define-key poly-markdown+r-mode-map (kbd "M-n p") 'ess-swv-purl) (which was just a guess, I don't know what should come after define-key in this case) but then get

Warning (initialization): An error occurred while loading ‘/Users/<user>/.emacs’:
Symbol's value as variable is void: poly-markdown+r-mode-map
Marius Hofert
  • 349
  • 1
  • 9

1 Answers1

2
  1. M-n is not a prefix key in the global-map (unless you define it as such).

  2. If you want to define a key in poly-markdown+r-mode-map then that variable needs to be defined and bound to a keymap. Use with-eval-after-load to bind the key in that map after (as soon as) its defining library is loaded.

Drew
  • 75,699
  • 9
  • 109
  • 225
  • Thanks for helping, Drew. I'm not sure how this is done. Is saw [this link](https://emacs.stackexchange.com/questions/12592/how-to-bind-your-keys-to-keymaps-that-arent-loaded-yet) and tried `(with-eval-after-load "poly-markdown+r-mode" (bind-key "M-n p" #'ess-swv-purl poly-markdown+r-mode-map)) `, but I still get `M-n p is undefined`. And what do you mean by 'defining library'? – Marius Hofert Feb 20 '19 at 13:08
  • poly-markdown+R-mode is defined in the file poly-R, so your code should be: `(with-eval-after-load "poly-R" (bind-key "M-n p" #'ess-swv-purl poly-markdown+R-mode-map))` – Tyler Feb 20 '19 at 14:52
  • Thanks, Tyler. If I open an .Rmd file now, it is not in polymode anymore and I see `File mode specification error: (void-function bind-key)` in the `*Messages*` buffer. I also tried `(with-eval-after-load "poly-R" (define-key poly-markdown+R-mode-map (kbd "M-n p") #'ess-swv-purl))` because `bind-key` requires an extra library I believe. – Marius Hofert Feb 20 '19 at 20:02
  • Yes, in the general case you need to *load* libraries before you can *use* their functions etc. Either load the library that defines `bind-key` or cause it to be loaded before you use that function. Or just use the vanilla Emacs function `define-key`, as you said - you don't need `bind-key`. – Drew Feb 20 '19 at 21:24
  • Since `M-n` is apparently a prefix key in the mode you want, it's likely that there is a specific variable bound to the keymap that `M-n` is bound to. In that case, just bind `p` in that keymap. You need to investigate the code a bit, to find out what you should be doing. You need to know what keymap you're binding a key in. – Drew Feb 20 '19 at 21:27