How can I do the following in emacs:

Suppose the cursor is at position A in my text. Then

  • open a calendar
  • chooses the date by clicking with the mouse or navigating with the keyboard
  • insert the choosen date at A

The solution should work in all modes and the date format should be configurable.

  • while I understand what you mean :), what is the current point? Because when you choose a date in a calendar, current point is the place in your calendar.
    – Maxim Kim
    Commented Jul 11, 2018 at 11:36
  • Thanks. I tried to make it clearer, see my edit.
    – student
    Commented Jul 11, 2018 at 11:48

3 Answers 3

(defun calendar-insert-date ()
  "Capture the date at point, exit the Calendar, insert the date."
  (seq-let (month day year) (save-match-data (calendar-cursor-to-date))
    (insert (format "%d-%02d-%02d" year month day))))

(define-key calendar-mode-map (kbd "RET") 'calendar-insert-date)

To insert a date at point, use

  1. M-x calendar
  2. Adjust the date as needed
  3. RET

By the way, I am not familiar with the Calendar at all, thus maybe there is a better way I don't know.

  • Is it also possible to get the date numbers with leading zeros, for example 2018-03-07 instead of 2018-3-7?
    – student
    Commented Jul 11, 2018 at 13:37
  • @student Yes, I've update the answer to use that format. Beside format, another option is format-time-string, though you have to use encode-time to convert year/month/day into a time value..
    – xuchunyang
    Commented Jul 11, 2018 at 15:27
  • Defining keys for calendar-mode-map appears to only work once the calendar had been opened before during the current Emacs session. Otherwise, the define-key statement will fail (e.g. if above code would go into your ~/.emacs.d/init.el file). If placed inside the defun, it will work as the calendar is open by the time this statement is called.
    – Phoenix
    Commented Nov 18, 2021 at 18:36
(defun org-insert-date ()
"Insert a date at point using `org-read-date' with its optional argument
of TO-TIME so that the user can customize the date format more easily."
  (require 'org)
  (let ((time (org-read-date nil 'to-time nil "Date:  ")))
    (insert (format-time-string "%Y-%m-%d" time))))

As far as I know -- there is no built in function to do what you want.

But you can try to do it yourself.

  1. there is How to retrieve the date under the cursor in emacs calendar as the format day.month.year like 15.07.2018

    Using the solution from the answer you will be able to open calendar, press M-w on a date, close calendar and paste the date with C-y. (And I usually do this)

  2. Now if it is not enough, you can learn some emacs lisp and try to automate the process from the 1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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