Search code examples
emacsinitializationelispkey-bindings

bind key to negative-argument + command in emacs


I am trying to bind to M-b a command preceded by a negative argument. I post my code.

working

(global-unset-key (kbd "M-f"))                                                         
(global-set-key (kbd "M-f") 'forward-whitespace)                                       

not working

(global-unset-key (kbd "M-b"))                                                         
(global-set-key (kbd "M-b") (lambda () (interactive) (negative-argument(forward-whitespace))))    

How can I make it working?


Solution

  • The specific issue you have is solved easily:

    (global-set-key (kbd "M-b") (lambda () (interactive) (forward-whitespace -1)))
    

    You might wonder if you can write a macro that would call an arbitrary command interactively with negative argument.

    It is not really hard:

    (defmacro call-with-negative-argument (command)
      `(lambda ()
         (interactive)
         (prefix-command-preserve-state)
         (setq prefix-arg '-)
         (universal-argument--mode)
         (call-interactively ,command)))
    (global-set-key (kbd "...") (call-with-negative-argument forward-whitespace))
    

    but, really, any compliant function would also work fine like this:

    (defmacro call-with-negative-argument (command)
      `(lambda ()
         (interactive)
         (,command -1)))