global-set-key
, as the name suggests, changes a global key binding. Local bindings, determined by the buffer's mode override global bindings. See the Emacs manual for an introduction to multiple keymaps and the Elisp manual for the full story. What you're doing here is each time you open a file in C mode, change the global binding for M-j
, which doesn't make sense.
Since you want to change the binding of M-j
in the CC mode familiy, you need to change it in c-mode-base-map
(that's what c-mode-map
is based on). You can check that c-mode-base-map
is indeed where M-j
is bound, to c-indent-new-comment-line
.
To override that binding, use the define-key
function. You need to invoke it after c-mode-base-map
is defined, which is done when cc-mode
is loaded. Use with-eval-after-load
in Emacs ≥24.4, or eval-after-load
in older versions.
(defun my-after-load-cc-mode ()
(define-key c-mode-base-map (kbd "M-j") 'backward-char))
(eval-after-load "cc-mode" 'my-after-load-cc-mode)
If you want M-j
to be bound to backward-char
all the time, then you need to define it as a global binding, and to stop major modes from overriding it. To remove a binding from a keymap, bind the key to nil
.
(global-set-key "M-j" 'backward-char)
(defun my-after-load-cc-mode ()
(define-key c-mode-base-map (kbd "M-j") nil))
(eval-after-load "cc-mode" 'my-after-load-cc-mode)
nil
, instead of trying to trump it with global. Major trumps global, and minor trumps major. In this particular case, however, perhaps something else is needed and one of the local forum experts can teach us all a thing or two. The current key is bound by the following code:(substitute-key-definition 'indent-new-comment-line 'c-indent-new-comment-line c-mode-base-map global-map)
Perhaps simply creating a major mode binding is sufficient?:(define-key c-mode-base-map (kbd "M-j") 'backward-char)
– lawlist Jun 7 '15 at 3:21define-key
worked! Thanks for the great explanation. If you move this to an answer I'll accept it. – David Jun 7 '15 at 5:12t
before the function actually addst
to the hook list not the function, effectively doing nothing. – Jordon Biondo Jul 7 '15 at 20:27