I use the method stated here : globally-override-key-binding-in-emacs
(defvar my-keys-minor-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-i") 'some-function)
map)
"my-keys-minor-mode keymap.")
(define-minor-mode my-keys-minor-mode
"A minor mode so that my key settings override annoying major modes."
;; Define-minor-mode will use `my-keys-minor-mode-map' for us.
:init-value t
:lighter " my-keys")
(defun my-keys-keep-on-top (&rest _)
"Try to ensure that my keybindings always have priority."
(unless (eq (caar minor-mode-map-alist) 'my-keys-minor-mode)
(let ((mykeys (assq 'my-keys-minor-mode minor-mode-map-alist)))
(assq-delete-all 'my-keys-minor-mode minor-mode-map-alist)
(add-to-list 'minor-mode-map-alist mykeys))))
(add-hook 'after-load-functions #'my-keys-keep-on-top)
(my-keys-minor-mode 1)
How to I explicitly override this? The methods in the link is not working to me.
EDIT2 :
Issue is not only applied to read only mode. The eval-after-load
is not a good method since it makes change to my-minor-mode-keymap
in long term.
I put another example here:
I use program mode for most of the time. Suppose I want to have C-q
bind to syntax-check in program mode. However, I jot notes in text mode sometime. It makes no sense to have syntax check in text mode. So I decide to have C-q
bind to spell-check.
Under normal circumstances, I would do this
(global-set-key (kbd "C-q") 'syntax-check)
(define-key text-mode-map (kbd "C-q") 'spell-check)
How to have such effect if I define my-keys-minor-mode-map? Assume I put this in my keymap:
(define-key 'my-keys-minor-mode-map (kbd "C-q") 'syntax-check)
(define-key text-mode-map (kbd "C-q") 'spell-check)
doesn't work since my keymap always has precedence over other minor mode mapping.
Neither
(eval-after-load "text-mode"
(define-key my-keys-minor-mode-map (kbd "C-q") 'spell-check))
nor
(add-hook 'text-mode-map (lambda ()
(define-key my-keys-minor-mode-map (kbd "C-q") 'spell-check)))
do a good job because they change the my-keys-minor-mode-map in long term. That means when I switch back from text mode to program mode, I lose syntax check function.
EDIT :
For example,
(define-key my-keys-minor-mode-map (kbd "<return>") 'newline-and-indent)
this works 99% of time and is good to prevent any other minor modes or major modes to modify this.
However, the key map has problem in read only mode. So I need to have "super priority" function to remap this key. I want something like
(defun super-priority-map()
(define-key super-my-keys-minor-mode-map (kbd "<return>") 'something-else))
(add-hook 'some-modes 'super-priority-map)
And more important, the super-priority-map should take off as long as that specified mode is left.