2

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.

student
  • 1,007
  • 9
  • 29
  • 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 Jul 11 '18 at 11:36
  • Thanks. I tried to make it clearer, see my edit. – student Jul 11 '18 at 11:48

3 Answers3

5
(defun calendar-insert-date ()
  "Capture the date at point, exit the Calendar, insert the date."
  (interactive)
  (seq-let (month day year) (save-match-data (calendar-cursor-to-date))
    (calendar-exit)
    (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.

xuchunyang
  • 14,302
  • 1
  • 18
  • 39
  • Is it also possible to get the date numbers with leading zeros, for example 2018-03-07 instead of 2018-3-7? – student Jul 11 '18 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 Jul 11 '18 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 Nov 18 '21 at 18:36
2
(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."
(interactive)
  (require 'org)
  (let ((time (org-read-date nil 'to-time nil "Date:  ")))
    (insert (format-time-string "%Y-%m-%d" time))))
lawlist
  • 18,826
  • 5
  • 37
  • 118
1

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.

Maxim Kim
  • 1,516
  • 9
  • 17