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?

CodyChan
  • 2,599
  • 1
  • 19
  • 33
  • 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 07: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 08: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 08:09

1 Answers1

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")))
Pradhan
  • 2,330
  • 14
  • 28
  • Thank you, the [call-interactively](http://www.gnu.org/software/emacs/manual/html_node/elisp/Interactive-Call.html) is exactly what I want. – CodyChan Jan 18 '15 at 13:35