Search code examples
functionemacscommandkey-bindingscpu-word

Emacs, how to write a shortcut calling a function with as argument the word at the cursor position?


How do I set up a shortcut for Emacs that will call a function and take as an argument the word at the cursor position? Like alt . in rtags package.


Solution

  • Version that reads only names of functions, with completion:

    (defun call-fun-on-word-at-point (function word)
      "Call FUNCTION with argument WORD, the word at point."
      (interactive 
       (list (intern (completing-read "Function: " obarray 'functionp t))
             (word-at-point)))
      (funcall function word))
    

    Version that reads a Lisp expression as a function (name or lambda expression):

    (defun call-fun-on-word-at-point (function word)
      "Call FUNCTION with argument WORD, the word at point."
      (interactive 
       (let (fun)
         (while (not (functionp fun))
           (setq fun  (read--expression "Function: "))
           (when (stringp fun) (setq fun  (intern fun))))
         (list fun (word-at-point))))
      (funcall function word))
    

    As for a "shortcut", I guess you're asking to bind the command to a key.

    (global-set-key (kbd "M-.") 'call-fun-on-word-at-point)