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)
1

3 Answers 3

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.

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)
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.

3
  • Thanks but that doesn't work (you can see I tried that in the last line of my code). M-r is still bound to `anaconda-mode-find-references
    – Brep Brep
    Aug 11, 2017 at 17:33
  • Did you add the kbd function before M-r ?
    – Ray Wang
    Aug 12, 2017 at 3:44
  • Yup, I added that to my .spacemacs and restarted to no avail.
    – Brep Brep
    Aug 21, 2017 at 14:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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