Search code examples
emacscommandorg-modekey-bindings

How to create Emacs key bindings for interactive org-mode functions / org-mode commands with arguments?


with the function org-deadline, it is possible to define a due date for tasks in Emacs org-mode. The description looks like this:

(org-deadline ARG &optional TIME)

Insert the "DEADLINE:" string with a timestamp to make a deadline.
With one universal prefix argument, remove any deadline from the item.
With two universal prefix arguments, prompt for a warning delay.
With argument TIME, set the deadline at the corresponding date.  TIME
can either be an Org date like "2011-07-24" or a delta like "+2d".

I want to create a key binding to set the due date to 1 week in the future directly. So the keybinding should call the org-deadline function and give +1w as an argument. Writing (org-deadline nil "+1w") and then doing an eval on that region works as expected.

But why can't I bind that to a key? I tried the following two options:

  1. (defun org-deadline-in-one-week ()
      (interactive)
      (org-deadline nil "+1w"))
    (global-set-key (kbd "C-c C-s") 'org-deadline-in-one-week)
    
  2. (global-set-key (kbd "C-c C-s") (lambda () (interactive) (org-deadline nil "+1w")))
    

Both ways fail in the sense that the interactive menu for selecting a date is still shown. It prompts me to select a date with the cursor keys and then confirm with RET. But I want to use the interactive function non-interactively and just set the due date to one week in the future. What am I missing?

Update: I am using Org mode version 9.1.9 (release_9.1.9-65-g5e4542 @ /usr/share/emacs/26.1/lisp/org/).


Solution

  • You are running into keymap problems: C-c C-s is bound in the org-mode-map (to org-schedule). That's the major mode keymap for Org mode, and it overrides the global map in Org mode buffers. See Active keymaps in the Emacs Lisp manual - in fact, reading (and rereading) the whole chapter is a good idea.

    You should do two things: define the key in the org-mode-map, not in the global map; and make sure that the key is not defined already (or at least you don't mind losing its current setting). E.g C-c s is undefined in the org-mode-map (by default), so I would do

    (define-key org-mode-map (kbd "C-c s") 'org-deadline-in-one-week)