6

Say, the C-M-j is bound to c-indent-new-comment-line for c-mode (and c++-mode) and indent-new-comment-line for other modes, but I want to define a function that will execute C-M-j to c-indent-new-comment-line in c-mode (and c++-mode) and indent-new-comment-line in other modes.

Is there any simple way that I can just embed the shortcut but not check the current major mode and then execute the different functions in defun...?

Example:

(defun example-fn ()
  (interactive)
  (beginning-of-line)
  (execute-C-M-j)
  (next-line))

The (execute-C-M-j) is what I want, execute the key not the command it is bound to, but I don't know how to implement this?

  • Something like this?: (defun example-fn () (interactive) (if (eq major-mode 'c-mode) (message "Hello-world!") (message "Happy birthday!"))) (define-key global-map [f5] 'example-fn) – lawlist Jan 18 '15 at 7:58
  • What does a function which uses C-M-j to do X mean? After executing the function, you would want the desired shortcuts to be bound? – Pradhan Jan 18 '15 at 8:08
  • 2
    @lawlist No, you are saying the normal way(defun and then set-key), I mean the key is part of the function defined, you will execute a lot of commands including the key if you execute the function. – CodyChan Jan 18 '15 at 8:09
9

You can use funcall and key-binding to do this:

(funcall (key-binding (kbd "C-M-j")))

will execute the function currently bound to C-M-j.

funcall lets you pass in arguments as well, if needed.

Alternatively, you can use call-interactively to call a command bound to a key like this:

(call-interactively (key-binding (kbd "C-M-j")))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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