4

I'm using the python-layer and am trying to set M-r to run replace-string while editing Python files. I've tried all of the options below from inside the function dotspacemacs/user-config. Help?

;; NONE OF THESE WORK!
(define-key evil-insert-state-map (kbd "M-r") 'replace-string)
(define-key evil-insert-state-map "\M-r" 'replace-string)
(spacemacs/set-leader-keys "M-r" 'replace-string)
(spacemacs/set-leader-keys-for-major-mode 'python-mode "M-r" 'replace-string)
(spacemacs/set-leader-keys-for-major-mode 'anaconda-mode "M-r" 'replace-string)
(defun my-python-mode-config ()
  "For use in `mode-hooks'."
  (local-set-key (kbd "M-r") `replace-string)
)
(add-hook 'python-mode-hook 'my-python-mode-config)
(add-hook 'anaconda-mode-hook 'my-python-mode-config)
(global-set-key "\M-r"  'replace-string)
Drew
  • 75,699
  • 9
  • 109
  • 225
Brep Brep
  • 41
  • 2
  • +1 would like to see some clear information around this. The documentation coincides with your attempts which seems to just not work. For beginners like myself it is quite a barrier. http://develop.spacemacs.org/doc/DOCUMENTATION.html#binding-keys – nachonachoman Jul 17 '18 at 14:59

3 Answers3

1

I don't know anything about how Spacemacs works, but the attempts with global-set-key or evil-insert-state-map aren't supposed to work, because the local keymaps take precedence!

I think it should work to set it in the anaconda-mode-map. So you can modify the my-python-mode-config function to call (define-key anaconda-mode-map (kbd "M-r") 'replace-string) instead.

Although, instead of defining the key every single time you switch to anaconda-mode, the premature optimizer in me would do it only once:

(eval-after-load 'anaconda-mode
    '(define-key anaconda-mode-map (kbd "M-r") 'replace-string))

Finally, I vaguely remember that Spacemacs uses use-package. If that's the case you can add

:bind (:map anaconda-mode-map ("M-r" . replace-string))

to the (use-package anaconda-mode) form you must have somewhere in your config.

Omar
  • 4,732
  • 1
  • 17
  • 32
1

I just went through a similar ordeal trying to bind a key in ess-mode with spacemacs. Assuming you're using evil-mode, I think the following will work:

  (evil-define-key 'insert python-mode (kbd "M-r") 'replace-string)
David Kent
  • 11
  • 2
0

(global-set-key (kbd "M-r") 'replace-string)

You can also set it the spacemacs way:

spacemacs/set-leader-keys-for-major-mode 'python-mode "oo" 'replace-string

and you can use it by SPACE o o.

Ray Wang
  • 46
  • 1