I want to press
- on my keyboard and have
_ be inserted and vice-versa only for a particular mode.
The following does this globally using the
post-self-insert-hook, It checks the character just inserted and makes a replacement accordingly:
(defun my-swap-dash () "Make dash insert and underscore and vice-versa." (interactive) (let ((just-inserted (char-before (point)))) (cond ((equal just-inserted 45) ;; '-' (progn (delete-backward-char 1) (insert "_"))) ((equal just-inserted 95) ;; '_' (progn (delete-backward-char 1) (insert "-")))))) (add-hook 'post-self-insert-hook #'my-swap-dash)
How could I get this same behavior for only
My first thought is to define a minor mode and then enable it through the
python-mode-hook. However, using the
post-self-insert-hook means the replacement must happen globally.
As a work-around, I created a method of toggling the behavior manually:
(defvar swap-dash-state-p nil "Is swap-undash enabled?") (defun toggle-swap-dash () "Toggle `my-swap-dash'." (interactive) (if swap-dash-state-p (progn (remove-hook 'post-self-insert-hook #'my-swap-dash) (setq swap-dash-state-p nil)) (progn (add-hook 'post-self-insert-hook #'my-swap-dash) (setq swap-dash-state-p t))))
Thoughts and coding style comments welcome!