ox-icalendar.el 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. ;;; ox-icalendar.el --- iCalendar Back-End for Org Export Engine -*- lexical-binding: t; -*-
  2. ;; Copyright (C) 2004-2022 Free Software Foundation, Inc.
  3. ;; Author: Carsten Dominik <carsten.dominik@gmail.com>
  4. ;; Nicolas Goaziou <mail@nicolasgoaziou.fr>
  5. ;; Maintainer: Nicolas Goaziou <mail@nicolasgoaziou.fr>
  6. ;; Keywords: outlines, hypermedia, calendar, wp
  7. ;; URL: https://orgmode.org
  8. ;; This file is part of GNU Emacs.
  9. ;; GNU Emacs is free software: you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation, either version 3 of the License, or
  12. ;; (at your option) any later version.
  13. ;; GNU Emacs is distributed in the hope that it will be useful,
  14. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;; GNU General Public License for more details.
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
  19. ;;; Commentary:
  20. ;;
  21. ;; This library implements an iCalendar back-end for Org generic
  22. ;; exporter. See Org manual for more information.
  23. ;;
  24. ;; It is expected to conform to RFC 5545.
  25. ;;; Code:
  26. (require 'org-macs)
  27. (org-assert-version)
  28. (require 'cl-lib)
  29. (require 'org-agenda)
  30. (require 'ox-ascii)
  31. (declare-function org-bbdb-anniv-export-ical "ol-bbdb" nil)
  32. (declare-function org-at-heading-p "org" (&optional _))
  33. (declare-function org-back-to-heading "org" (&optional invisible-ok))
  34. (declare-function org-next-visible-heading "org" (arg))
  35. ;;; User-Configurable Variables
  36. (defgroup org-export-icalendar nil
  37. "Options specific for iCalendar export back-end."
  38. :tag "Org Export iCalendar"
  39. :group 'org-export)
  40. (defcustom org-icalendar-combined-agenda-file "~/org.ics"
  41. "The file name for the iCalendar file covering all agenda files.
  42. This file is created with the command `\\[org-icalendar-combine-agenda-files]'.
  43. The file name should be absolute. It will be overwritten without warning."
  44. :group 'org-export-icalendar
  45. :type 'file)
  46. (defcustom org-icalendar-alarm-time 0
  47. "Number of minutes for triggering an alarm for exported timed events.
  48. A zero value (the default) turns off the definition of an alarm trigger
  49. for timed events. If non-zero, alarms are created.
  50. - a single alarm per entry is defined
  51. - The alarm will go off N minutes before the event
  52. - only a DISPLAY action is defined."
  53. :group 'org-export-icalendar
  54. :version "24.1"
  55. :type 'integer)
  56. (defcustom org-icalendar-force-alarm nil
  57. "Non-nil means alarm will be created even if is set to zero.
  58. This overrides default behaviour where zero means no alarm. With
  59. this set to non-nil and alarm set to zero, alarm will be created
  60. and will fire at the event start."
  61. :group 'org-export-icalendar
  62. :type 'boolean
  63. :package-version '(Org . "9.6")
  64. :safe #'booleanp)
  65. (defcustom org-icalendar-combined-name "OrgMode"
  66. "Calendar name for the combined iCalendar representing all agenda files."
  67. :group 'org-export-icalendar
  68. :type 'string)
  69. (defcustom org-icalendar-combined-description ""
  70. "Calendar description for the combined iCalendar (all agenda files)."
  71. :group 'org-export-icalendar
  72. :type 'string)
  73. (defcustom org-icalendar-exclude-tags nil
  74. "Tags that exclude a tree from export.
  75. This variable allows specifying different exclude tags from other
  76. back-ends. It can also be set with the ICALENDAR_EXCLUDE_TAGS
  77. keyword."
  78. :group 'org-export-icalendar
  79. :type '(repeat (string :tag "Tag")))
  80. (defcustom org-icalendar-use-deadline '(event-if-not-todo todo-due)
  81. "Contexts where iCalendar export should use a deadline time stamp.
  82. This is a list with possibly several symbols in it. Valid symbols are:
  83. `event-if-todo'
  84. Deadlines in TODO entries become calendar events.
  85. `event-if-todo-not-done'
  86. Deadlines in TODO entries with not-DONE state become events.
  87. `event-if-not-todo'
  88. Deadlines in non-TODO entries become calendar events.
  89. `todo-due'
  90. Use deadlines in TODO entries as due-dates."
  91. :group 'org-export-icalendar
  92. :type
  93. '(set :greedy t
  94. (const :tag "DEADLINE in non-TODO entries become events"
  95. event-if-not-todo)
  96. (const :tag "DEADLINE in TODO entries become events"
  97. event-if-todo)
  98. (const :tag "DEADLINE in TODO entries with not-DONE state become events"
  99. event-if-todo-not-done)
  100. (const :tag "DEADLINE in TODO entries become due-dates"
  101. todo-due)))
  102. (defcustom org-icalendar-use-scheduled '(todo-start)
  103. "Contexts where iCalendar export should use a scheduling time stamp.
  104. This is a list with possibly several symbols in it. Valid symbols are:
  105. `event-if-todo'
  106. Scheduling time stamps in TODO entries become an event.
  107. `event-if-todo-not-done'
  108. Scheduling time stamps in TODO entries with not-DONE state
  109. become events.
  110. `event-if-not-todo'
  111. Scheduling time stamps in non-TODO entries become an event.
  112. `todo-start'
  113. Scheduling time stamps in TODO entries become start date. Some
  114. calendar applications show TODO entries only after that date."
  115. :group 'org-export-icalendar
  116. :type
  117. '(set :greedy t
  118. (const :tag "SCHEDULED timestamps in non-TODO entries become events"
  119. event-if-not-todo)
  120. (const :tag "SCHEDULED timestamps in TODO entries become events"
  121. event-if-todo)
  122. (const :tag "SCHEDULED in TODO entries with not-DONE state become events"
  123. event-if-todo-not-done)
  124. (const :tag "SCHEDULED in TODO entries become start date"
  125. todo-start)))
  126. (defcustom org-icalendar-categories '(local-tags category)
  127. "Items that should be entered into the \"categories\" field.
  128. This is a list of symbols, the following are valid:
  129. `category' The Org mode category of the current file or tree
  130. `todo-state' The todo state, if any
  131. `local-tags' The tags, defined in the current line
  132. `all-tags' All tags, including inherited ones."
  133. :group 'org-export-icalendar
  134. :type '(repeat
  135. (choice
  136. (const :tag "The file or tree category" category)
  137. (const :tag "The TODO state" todo-state)
  138. (const :tag "Tags defined in current line" local-tags)
  139. (const :tag "All tags, including inherited ones" all-tags))))
  140. (defcustom org-icalendar-with-timestamps 'active
  141. "Non-nil means make an event from plain time stamps.
  142. It can be set to `active', `inactive', t or nil, in order to make
  143. an event from, respectively, only active timestamps, only
  144. inactive ones, all of them or none.
  145. This variable has precedence over `org-export-with-timestamps'.
  146. It can also be set with the #+OPTIONS line, e.g. \"<:t\"."
  147. :group 'org-export-icalendar
  148. :type '(choice
  149. (const :tag "All timestamps" t)
  150. (const :tag "Only active timestamps" active)
  151. (const :tag "Only inactive timestamps" inactive)
  152. (const :tag "No timestamp" nil)))
  153. (defcustom org-icalendar-include-todo nil
  154. "Non-nil means create VTODO components from TODO items.
  155. Valid values are:
  156. nil don't include any task.
  157. t include tasks that are not in DONE state.
  158. `unblocked' include all TODO items that are not blocked.
  159. `all' include both done and not done items."
  160. :group 'org-export-icalendar
  161. :type '(choice
  162. (const :tag "None" nil)
  163. (const :tag "Unfinished" t)
  164. (const :tag "Unblocked" unblocked)
  165. (const :tag "All" all)
  166. (repeat :tag "Specific TODO keywords"
  167. (string :tag "Keyword"))))
  168. (defcustom org-icalendar-include-bbdb-anniversaries nil
  169. "Non-nil means a combined iCalendar file should include anniversaries.
  170. The anniversaries are defined in the BBDB database."
  171. :group 'org-export-icalendar
  172. :type 'boolean)
  173. (defcustom org-icalendar-include-sexps t
  174. "Non-nil means export to iCalendar files should also cover sexp entries.
  175. These are entries like in the diary, but directly in an Org file."
  176. :group 'org-export-icalendar
  177. :type 'boolean)
  178. (defcustom org-icalendar-include-body t
  179. "Amount of text below headline to be included in iCalendar export.
  180. This is a number of characters that should maximally be included.
  181. Properties, scheduling and clocking lines will always be removed.
  182. The text will be inserted into the DESCRIPTION field."
  183. :group 'org-export-icalendar
  184. :type '(choice
  185. (const :tag "Nothing" nil)
  186. (const :tag "Everything" t)
  187. (integer :tag "Max characters")))
  188. (defcustom org-icalendar-store-UID nil
  189. "Non-nil means store any created UIDs in properties.
  190. The iCalendar standard requires that all entries have a unique identifier.
  191. Org will create these identifiers as needed. When this variable is non-nil,
  192. the created UIDs will be stored in the ID property of the entry. Then the
  193. next time this entry is exported, it will be exported with the same UID,
  194. superseding the previous form of it. This is essential for
  195. synchronization services.
  196. This variable is not turned on by default because we want to avoid creating
  197. a property drawer in every entry if people are only playing with this feature,
  198. or if they are only using it locally."
  199. :group 'org-export-icalendar
  200. :type 'boolean)
  201. (defcustom org-icalendar-timezone (getenv "TZ")
  202. "The time zone string for iCalendar export.
  203. When nil or the empty string, use output
  204. from (current-time-zone)."
  205. :group 'org-export-icalendar
  206. :type '(choice
  207. (const :tag "Unspecified" nil)
  208. (string :tag "Time zone")))
  209. (defcustom org-icalendar-date-time-format ":%Y%m%dT%H%M%S"
  210. "Format-string for exporting icalendar DATE-TIME.
  211. See `format-time-string' for a full documentation. The only
  212. difference is that `org-icalendar-timezone' is used for %Z.
  213. Interesting value are:
  214. - \":%Y%m%dT%H%M%S\" for local time
  215. - \";TZID=%Z:%Y%m%dT%H%M%S\" for local time with explicit timezone
  216. - \":%Y%m%dT%H%M%SZ\" for time expressed in Universal Time"
  217. :group 'org-export-icalendar
  218. :version "24.1"
  219. :type '(choice
  220. (const :tag "Local time" ":%Y%m%dT%H%M%S")
  221. (const :tag "Explicit local time" ";TZID=%Z:%Y%m%dT%H%M%S")
  222. (const :tag "Universal time" ":%Y%m%dT%H%M%SZ")
  223. (string :tag "Explicit format")))
  224. (defvar org-icalendar-after-save-hook nil
  225. "Hook run after an iCalendar file has been saved.
  226. This hook is run with the name of the file as argument. A good
  227. way to use this is to tell a desktop calendar application to
  228. re-read the iCalendar file.")
  229. ;;; Define Back-End
  230. (org-export-define-derived-backend 'icalendar 'ascii
  231. :translate-alist '((clock . nil)
  232. (footnote-definition . nil)
  233. (footnote-reference . nil)
  234. (headline . org-icalendar-entry)
  235. (inner-template . org-icalendar-inner-template)
  236. (inlinetask . nil)
  237. (planning . nil)
  238. (section . nil)
  239. (template . org-icalendar-template))
  240. :options-alist
  241. '((:exclude-tags
  242. "ICALENDAR_EXCLUDE_TAGS" nil org-icalendar-exclude-tags split)
  243. (:with-timestamps nil "<" org-icalendar-with-timestamps)
  244. ;; Other variables.
  245. (:icalendar-alarm-time nil nil org-icalendar-alarm-time)
  246. (:icalendar-categories nil nil org-icalendar-categories)
  247. (:icalendar-date-time-format nil nil org-icalendar-date-time-format)
  248. (:icalendar-include-bbdb-anniversaries nil nil org-icalendar-include-bbdb-anniversaries)
  249. (:icalendar-include-body nil nil org-icalendar-include-body)
  250. (:icalendar-include-sexps nil nil org-icalendar-include-sexps)
  251. (:icalendar-include-todo nil nil org-icalendar-include-todo)
  252. (:icalendar-store-UID nil nil org-icalendar-store-UID)
  253. (:icalendar-timezone nil nil org-icalendar-timezone)
  254. (:icalendar-use-deadline nil nil org-icalendar-use-deadline)
  255. (:icalendar-use-scheduled nil nil org-icalendar-use-scheduled))
  256. :filters-alist
  257. '((:filter-headline . org-icalendar-clear-blank-lines))
  258. :menu-entry
  259. '(?c "Export to iCalendar"
  260. ((?f "Current file" org-icalendar-export-to-ics)
  261. (?a "All agenda files"
  262. (lambda (a s v b) (org-icalendar-export-agenda-files a)))
  263. (?c "Combine all agenda files"
  264. (lambda (a s v b) (org-icalendar-combine-agenda-files a))))))
  265. ;;; Internal Functions
  266. (defun org-icalendar-create-uid (file &optional bell)
  267. "Set ID property on headlines missing it in FILE.
  268. When optional argument BELL is non-nil, inform the user with
  269. a message if the file was modified."
  270. (let (modified-flag)
  271. (org-map-entries
  272. (lambda ()
  273. (let ((entry (org-element-at-point)))
  274. (unless (org-element-property :ID entry)
  275. (org-id-get-create)
  276. (setq modified-flag t)
  277. (forward-line))))
  278. nil nil 'comment)
  279. (when (and bell modified-flag)
  280. (message "ID properties created in file \"%s\"" file)
  281. (sit-for 2))))
  282. (defun org-icalendar-blocked-headline-p (headline info)
  283. "Non-nil when HEADLINE is considered to be blocked.
  284. INFO is a plist used as a communication channel.
  285. A headline is blocked when either
  286. - it has children which are not all in a completed state;
  287. - it has a parent with the property :ORDERED:, and there are
  288. siblings prior to it with incomplete status;
  289. - its parent is blocked because it has siblings that should be
  290. done first or is a child of a blocked grandparent entry."
  291. (or
  292. ;; Check if any child is not done.
  293. (org-element-map (org-element-contents headline) 'headline
  294. (lambda (hl) (eq (org-element-property :todo-type hl) 'todo))
  295. info 'first-match)
  296. ;; Check :ORDERED: node property.
  297. (catch 'blockedp
  298. (let ((current headline))
  299. (dolist (parent (org-element-lineage headline))
  300. (cond
  301. ((not (org-element-property :todo-keyword parent))
  302. (throw 'blockedp nil))
  303. ((org-not-nil (org-element-property :ORDERED parent))
  304. (let ((sibling current))
  305. (while (setq sibling (org-export-get-previous-element
  306. sibling info))
  307. (when (eq (org-element-property :todo-type sibling) 'todo)
  308. (throw 'blockedp t)))))
  309. (t (setq current parent))))))))
  310. (defun org-icalendar-use-UTC-date-time-p ()
  311. "Non-nil when `org-icalendar-date-time-format' requires UTC time."
  312. (char-equal (elt org-icalendar-date-time-format
  313. (1- (length org-icalendar-date-time-format)))
  314. ?Z))
  315. (defun org-icalendar-convert-timestamp (timestamp keyword &optional end tz)
  316. "Convert TIMESTAMP to iCalendar format.
  317. TIMESTAMP is a timestamp object. KEYWORD is added in front of
  318. it, in order to make a complete line (e.g. \"DTSTART\").
  319. When optional argument END is non-nil, use end of time range.
  320. Also increase the hour by two (if time string contains a time),
  321. or the day by one (if it does not contain a time) when no
  322. explicit ending time is specified.
  323. When optional argument TZ is non-nil, timezone data time will be
  324. added to the timestamp. It can be the string \"UTC\", to use UTC
  325. time, or a string in the IANA TZ database
  326. format (e.g. \"Europe/London\"). In either case, the value of
  327. `org-icalendar-date-time-format' will be ignored."
  328. (let* ((year-start (org-element-property :year-start timestamp))
  329. (year-end (org-element-property :year-end timestamp))
  330. (month-start (org-element-property :month-start timestamp))
  331. (month-end (org-element-property :month-end timestamp))
  332. (day-start (org-element-property :day-start timestamp))
  333. (day-end (org-element-property :day-end timestamp))
  334. (hour-start (org-element-property :hour-start timestamp))
  335. (hour-end (org-element-property :hour-end timestamp))
  336. (minute-start (org-element-property :minute-start timestamp))
  337. (minute-end (org-element-property :minute-end timestamp))
  338. (with-time-p minute-start)
  339. (equal-bounds-p
  340. (equal (list year-start month-start day-start hour-start minute-start)
  341. (list year-end month-end day-end hour-end minute-end)))
  342. (mi (cond ((not with-time-p) 0)
  343. ((not end) minute-start)
  344. ((and org-agenda-default-appointment-duration equal-bounds-p)
  345. (+ minute-end org-agenda-default-appointment-duration))
  346. (t minute-end)))
  347. (h (cond ((not with-time-p) 0)
  348. ((not end) hour-start)
  349. ((or (not equal-bounds-p)
  350. org-agenda-default-appointment-duration)
  351. hour-end)
  352. (t (+ hour-end 2))))
  353. (d (cond ((not end) day-start)
  354. ((not with-time-p) (1+ day-end))
  355. (t day-end)))
  356. (m (if end month-end month-start))
  357. (y (if end year-end year-start)))
  358. (concat
  359. keyword
  360. (format-time-string
  361. (cond ((string-equal tz "UTC") ":%Y%m%dT%H%M%SZ")
  362. ((not with-time-p) ";VALUE=DATE:%Y%m%d")
  363. ((stringp tz) (concat ";TZID=" tz ":%Y%m%dT%H%M%S"))
  364. (t (replace-regexp-in-string "%Z"
  365. org-icalendar-timezone
  366. org-icalendar-date-time-format
  367. t)))
  368. ;; Convert timestamp into internal time in order to use
  369. ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
  370. (org-encode-time 0 mi h d m y)
  371. (and (or (string-equal tz "UTC")
  372. (and (null tz)
  373. with-time-p
  374. (org-icalendar-use-UTC-date-time-p)))
  375. t)))))
  376. (defun org-icalendar-dtstamp ()
  377. "Return DTSTAMP property, as a string."
  378. (format-time-string "DTSTAMP:%Y%m%dT%H%M%SZ" nil t))
  379. (defun org-icalendar-get-categories (entry info)
  380. "Return categories according to `org-icalendar-categories'.
  381. ENTRY is a headline or an inlinetask element. INFO is a plist
  382. used as a communication channel."
  383. (mapconcat
  384. #'identity
  385. (org-uniquify
  386. (let (categories)
  387. (dolist (type org-icalendar-categories (nreverse categories))
  388. (cl-case type
  389. (category
  390. (push (org-export-get-category entry info) categories))
  391. (todo-state
  392. (let ((todo (org-element-property :todo-keyword entry)))
  393. (and todo (push todo categories))))
  394. (local-tags
  395. (setq categories
  396. (append (nreverse (org-export-get-tags entry info))
  397. categories)))
  398. (all-tags
  399. (setq categories
  400. (append (nreverse (org-export-get-tags entry info nil t))
  401. categories)))))))
  402. ","))
  403. (defun org-icalendar-transcode-diary-sexp (sexp uid summary)
  404. "Transcode a diary sexp into iCalendar format.
  405. SEXP is the diary sexp being transcoded, as a string. UID is the
  406. unique identifier for the entry. SUMMARY defines a short summary
  407. or subject for the event."
  408. (when (require 'icalendar nil t)
  409. (org-element-normalize-string
  410. (with-temp-buffer
  411. (let ((sexp (if (not (string-match "\\`<%%" sexp)) sexp
  412. (concat (substring sexp 1 -1) " " summary))))
  413. (put-text-property 0 1 'uid uid sexp)
  414. (insert sexp "\n"))
  415. (org-diary-to-ical-string (current-buffer))))))
  416. (defun org-icalendar-cleanup-string (s)
  417. "Cleanup string S according to RFC 5545."
  418. (when s
  419. ;; Protect "\", "," and ";" characters. and replace newline
  420. ;; characters with literal \n.
  421. (replace-regexp-in-string
  422. "[ \t]*\n" "\\n"
  423. (replace-regexp-in-string "[\\,;]" "\\\\\\&" s)
  424. nil t)))
  425. (defun org-icalendar-fold-string (s)
  426. "Fold string S according to RFC 5545."
  427. (org-element-normalize-string
  428. (mapconcat
  429. (lambda (line)
  430. ;; Limit each line to a maximum of 75 characters. If it is
  431. ;; longer, fold it by using "\r\n " as a continuation marker.
  432. (let ((len (length line)))
  433. (if (<= len 75) line
  434. (let ((folded-line (substring line 0 75))
  435. (chunk-start 75)
  436. chunk-end)
  437. ;; Since continuation marker takes up one character on the
  438. ;; line, real contents must be split at 74 chars.
  439. (while (< (setq chunk-end (+ chunk-start 74)) len)
  440. (setq folded-line
  441. (concat folded-line "\r\n "
  442. (substring line chunk-start chunk-end))
  443. chunk-start chunk-end))
  444. (concat folded-line "\r\n " (substring line chunk-start))))))
  445. (org-split-string s "\n") "\r\n")))
  446. ;;; Filters
  447. (defun org-icalendar-clear-blank-lines (headline _back-end _info)
  448. "Remove blank lines in HEADLINE export.
  449. HEADLINE is a string representing a transcoded headline.
  450. BACK-END and INFO are ignored."
  451. (replace-regexp-in-string "^\\(?:[ \t]*\n\\)+" "" headline))
  452. ;;; Transcode Functions
  453. ;;;; Headline and Inlinetasks
  454. ;; The main function is `org-icalendar-entry', which extracts
  455. ;; information from a headline or an inlinetask (summary,
  456. ;; description...) and then delegates code generation to
  457. ;; `org-icalendar--vtodo' and `org-icalendar--vevent', depending
  458. ;; on the component needed.
  459. ;; Obviously, `org-icalendar--valarm' handles alarms, which can
  460. ;; happen within a VTODO component.
  461. (defun org-icalendar-entry (entry contents info)
  462. "Transcode ENTRY element into iCalendar format.
  463. ENTRY is either a headline or an inlinetask. CONTENTS is
  464. ignored. INFO is a plist used as a communication channel.
  465. This function is called on every headline, the section below
  466. it (minus inlinetasks) being its contents. It tries to create
  467. VEVENT and VTODO components out of scheduled date, deadline date,
  468. plain timestamps, diary sexps. It also calls itself on every
  469. inlinetask within the section."
  470. (unless (org-element-property :footnote-section-p entry)
  471. (let* ((type (org-element-type entry))
  472. ;; Determine contents really associated to the entry. For
  473. ;; a headline, limit them to section, if any. For an
  474. ;; inlinetask, this is every element within the task.
  475. (inside
  476. (if (eq type 'inlinetask)
  477. (cons 'org-data (cons nil (org-element-contents entry)))
  478. (let ((first (car (org-element-contents entry))))
  479. (and (eq (org-element-type first) 'section)
  480. (cons 'org-data
  481. (cons nil (org-element-contents first))))))))
  482. (concat
  483. (let ((todo-type (org-element-property :todo-type entry))
  484. (uid (or (org-element-property :ID entry) (org-id-new)))
  485. (summary (org-icalendar-cleanup-string
  486. (or (org-element-property :SUMMARY entry)
  487. (org-export-data
  488. (org-element-property :title entry) info))))
  489. (loc (org-icalendar-cleanup-string
  490. (org-export-get-node-property
  491. :LOCATION entry
  492. (org-property-inherit-p "LOCATION"))))
  493. (class (org-icalendar-cleanup-string
  494. (org-export-get-node-property
  495. :CLASS entry
  496. (org-property-inherit-p "CLASS"))))
  497. ;; Build description of the entry from associated section
  498. ;; (headline) or contents (inlinetask).
  499. (desc
  500. (org-icalendar-cleanup-string
  501. (or (org-element-property :DESCRIPTION entry)
  502. (let ((contents (org-export-data inside info)))
  503. (cond
  504. ((not (org-string-nw-p contents)) nil)
  505. ((wholenump org-icalendar-include-body)
  506. (let ((contents (org-trim contents)))
  507. (substring
  508. contents 0 (min (length contents)
  509. org-icalendar-include-body))))
  510. (org-icalendar-include-body (org-trim contents)))))))
  511. (cat (org-icalendar-get-categories entry info))
  512. (tz (org-export-get-node-property
  513. :TIMEZONE entry
  514. (org-property-inherit-p "TIMEZONE"))))
  515. (concat
  516. ;; Events: Delegate to `org-icalendar--vevent' to generate
  517. ;; "VEVENT" component from scheduled, deadline, or any
  518. ;; timestamp in the entry.
  519. (let ((deadline (org-element-property :deadline entry))
  520. (use-deadline (plist-get info :icalendar-use-deadline)))
  521. (and deadline
  522. (pcase todo-type
  523. (`todo (or (memq 'event-if-todo-not-done use-deadline)
  524. (memq 'event-if-todo use-deadline)))
  525. (`done (memq 'event-if-todo use-deadline))
  526. (_ (memq 'event-if-not-todo use-deadline)))
  527. (org-icalendar--vevent
  528. entry deadline (concat "DL-" uid)
  529. (concat "DL: " summary) loc desc cat tz class)))
  530. (let ((scheduled (org-element-property :scheduled entry))
  531. (use-scheduled (plist-get info :icalendar-use-scheduled)))
  532. (and scheduled
  533. (pcase todo-type
  534. (`todo (or (memq 'event-if-todo-not-done use-scheduled)
  535. (memq 'event-if-todo use-scheduled)))
  536. (`done (memq 'event-if-todo use-scheduled))
  537. (_ (memq 'event-if-not-todo use-scheduled)))
  538. (org-icalendar--vevent
  539. entry scheduled (concat "SC-" uid)
  540. (concat "S: " summary) loc desc cat tz class)))
  541. ;; When collecting plain timestamps from a headline and its
  542. ;; title, skip inlinetasks since collection will happen once
  543. ;; ENTRY is one of them.
  544. (let ((counter 0))
  545. (mapconcat
  546. #'identity
  547. (org-element-map (cons (org-element-property :title entry)
  548. (org-element-contents inside))
  549. 'timestamp
  550. (lambda (ts)
  551. (when (let ((type (org-element-property :type ts)))
  552. (cl-case (plist-get info :with-timestamps)
  553. (active (memq type '(active active-range)))
  554. (inactive (memq type '(inactive inactive-range)))
  555. ((t) t)))
  556. (let ((uid (format "TS%d-%s" (cl-incf counter) uid)))
  557. (org-icalendar--vevent
  558. entry ts uid summary loc desc cat tz class))))
  559. info nil (and (eq type 'headline) 'inlinetask))
  560. ""))
  561. ;; Task: First check if it is appropriate to export it. If
  562. ;; so, call `org-icalendar--vtodo' to transcode it into
  563. ;; a "VTODO" component.
  564. (when (and todo-type
  565. (cl-case (plist-get info :icalendar-include-todo)
  566. (all t)
  567. (unblocked
  568. (and (eq type 'headline)
  569. (not (org-icalendar-blocked-headline-p
  570. entry info))))
  571. ((t) (eq todo-type 'todo))))
  572. (org-icalendar--vtodo entry uid summary loc desc cat tz class))
  573. ;; Diary-sexp: Collect every diary-sexp element within ENTRY
  574. ;; and its title, and transcode them. If ENTRY is
  575. ;; a headline, skip inlinetasks: they will be handled
  576. ;; separately.
  577. (when org-icalendar-include-sexps
  578. (let ((counter 0))
  579. (mapconcat #'identity
  580. (org-element-map
  581. (cons (org-element-property :title entry)
  582. (org-element-contents inside))
  583. 'diary-sexp
  584. (lambda (sexp)
  585. (org-icalendar-transcode-diary-sexp
  586. (org-element-property :value sexp)
  587. (format "DS%d-%s" (cl-incf counter) uid)
  588. summary))
  589. info nil (and (eq type 'headline) 'inlinetask))
  590. "")))))
  591. ;; If ENTRY is a headline, call current function on every
  592. ;; inlinetask within it. In agenda export, this is independent
  593. ;; from the mark (or lack thereof) on the entry.
  594. (when (eq type 'headline)
  595. (mapconcat #'identity
  596. (org-element-map inside 'inlinetask
  597. (lambda (task) (org-icalendar-entry task nil info))
  598. info) ""))
  599. ;; Don't forget components from inner entries.
  600. contents))))
  601. (defun org-icalendar--vevent
  602. (entry timestamp uid summary location description categories timezone class)
  603. "Create a VEVENT component.
  604. ENTRY is either a headline or an inlinetask element. TIMESTAMP
  605. is a timestamp object defining the date-time of the event. UID
  606. is the unique identifier for the event. SUMMARY defines a short
  607. summary or subject for the event. LOCATION defines the intended
  608. venue for the event. DESCRIPTION provides the complete
  609. description of the event. CATEGORIES defines the categories the
  610. event belongs to. TIMEZONE specifies a time zone for this event
  611. only. CLASS contains the visibility attribute. Three of them
  612. (\"PUBLIC\", \"CONFIDENTIAL\", and \"PRIVATE\") are predefined, others
  613. should be treated as \"PRIVATE\" if they are unknown to the iCalendar server.
  614. Return VEVENT component as a string."
  615. (org-icalendar-fold-string
  616. (if (eq (org-element-property :type timestamp) 'diary)
  617. (org-icalendar-transcode-diary-sexp
  618. (org-element-property :raw-value timestamp) uid summary)
  619. (concat "BEGIN:VEVENT\n"
  620. (org-icalendar-dtstamp) "\n"
  621. "UID:" uid "\n"
  622. (org-icalendar-convert-timestamp timestamp "DTSTART" nil timezone) "\n"
  623. (org-icalendar-convert-timestamp timestamp "DTEND" t timezone) "\n"
  624. ;; RRULE.
  625. (when (org-element-property :repeater-type timestamp)
  626. (format "RRULE:FREQ=%s;INTERVAL=%d\n"
  627. (cl-case (org-element-property :repeater-unit timestamp)
  628. (hour "HOURLY") (day "DAILY") (week "WEEKLY")
  629. (month "MONTHLY") (year "YEARLY"))
  630. (org-element-property :repeater-value timestamp)))
  631. "SUMMARY:" summary "\n"
  632. (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
  633. (and (org-string-nw-p class) (format "CLASS:%s\n" class))
  634. (and (org-string-nw-p description)
  635. (format "DESCRIPTION:%s\n" description))
  636. "CATEGORIES:" categories "\n"
  637. ;; VALARM.
  638. (org-icalendar--valarm entry timestamp summary)
  639. "END:VEVENT"))))
  640. (defun org-icalendar--vtodo
  641. (entry uid summary location description categories timezone class)
  642. "Create a VTODO component.
  643. ENTRY is either a headline or an inlinetask element. UID is the
  644. unique identifier for the task. SUMMARY defines a short summary
  645. or subject for the task. LOCATION defines the intended venue for
  646. the task. DESCRIPTION provides the complete description of the
  647. task. CATEGORIES defines the categories the task belongs to.
  648. TIMEZONE specifies a time zone for this TODO only.
  649. Return VTODO component as a string."
  650. (let ((start (or (and (memq 'todo-start org-icalendar-use-scheduled)
  651. (org-element-property :scheduled entry))
  652. ;; If we can't use a scheduled time for some
  653. ;; reason, start task now.
  654. (let ((now (decode-time)))
  655. (list 'timestamp
  656. (list :type 'active
  657. :minute-start (nth 1 now)
  658. :hour-start (nth 2 now)
  659. :day-start (nth 3 now)
  660. :month-start (nth 4 now)
  661. :year-start (nth 5 now)))))))
  662. (org-icalendar-fold-string
  663. (concat "BEGIN:VTODO\n"
  664. "UID:TODO-" uid "\n"
  665. (org-icalendar-dtstamp) "\n"
  666. (org-icalendar-convert-timestamp start "DTSTART" nil timezone) "\n"
  667. (and (memq 'todo-due org-icalendar-use-deadline)
  668. (org-element-property :deadline entry)
  669. (concat (org-icalendar-convert-timestamp
  670. (org-element-property :deadline entry) "DUE" nil timezone)
  671. "\n"))
  672. "SUMMARY:" summary "\n"
  673. (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
  674. (and (org-string-nw-p class) (format "CLASS:%s\n" class))
  675. (and (org-string-nw-p description)
  676. (format "DESCRIPTION:%s\n" description))
  677. "CATEGORIES:" categories "\n"
  678. "SEQUENCE:1\n"
  679. (format "PRIORITY:%d\n"
  680. (let ((pri (or (org-element-property :priority entry)
  681. org-priority-default)))
  682. (floor (- 9 (* 8. (/ (float (- org-priority-lowest pri))
  683. (- org-priority-lowest
  684. org-priority-highest)))))))
  685. (format "STATUS:%s\n"
  686. (if (eq (org-element-property :todo-type entry) 'todo)
  687. "NEEDS-ACTION"
  688. "COMPLETED"))
  689. "END:VTODO"))))
  690. (defun org-icalendar--valarm (entry timestamp summary)
  691. "Create a VALARM component.
  692. ENTRY is the calendar entry triggering the alarm. TIMESTAMP is
  693. the start date-time of the entry. SUMMARY defines a short
  694. summary or subject for the task.
  695. Return VALARM component as a string, or nil if it isn't allowed."
  696. ;; Create a VALARM entry if the entry is timed. This is not very
  697. ;; general in that:
  698. ;; (a) only one alarm per entry is defined,
  699. ;; (b) only minutes are allowed for the trigger period ahead of the
  700. ;; start time,
  701. ;; (c) only a DISPLAY action is defined. [ESF]
  702. (let ((alarm-time
  703. (let ((warntime
  704. (org-element-property :APPT_WARNTIME entry)))
  705. (if warntime (string-to-number warntime) nil))))
  706. (and (or (and alarm-time
  707. (> alarm-time 0))
  708. (> org-icalendar-alarm-time 0)
  709. org-icalendar-force-alarm)
  710. (org-element-property :hour-start timestamp)
  711. (format "BEGIN:VALARM
  712. ACTION:DISPLAY
  713. DESCRIPTION:%s
  714. TRIGGER:-P0DT0H%dM0S
  715. END:VALARM\n"
  716. summary
  717. (cond
  718. ((and alarm-time org-icalendar-force-alarm) alarm-time)
  719. ((and alarm-time (not (zerop alarm-time))) alarm-time)
  720. (t org-icalendar-alarm-time))))))
  721. ;;;; Template
  722. (defun org-icalendar-inner-template (contents _)
  723. "Return document body string after iCalendar conversion.
  724. CONTENTS is the transcoded contents string."
  725. contents)
  726. (defun org-icalendar-template (contents info)
  727. "Return complete document string after iCalendar conversion.
  728. CONTENTS is the transcoded contents string. INFO is a plist used
  729. as a communication channel."
  730. (org-icalendar--vcalendar
  731. ;; Name.
  732. (if (not (plist-get info :input-file)) (buffer-name (buffer-base-buffer))
  733. (file-name-nondirectory
  734. (file-name-sans-extension (plist-get info :input-file))))
  735. ;; Owner.
  736. (if (not (plist-get info :with-author)) ""
  737. (org-export-data (plist-get info :author) info))
  738. ;; Timezone.
  739. (if (org-string-nw-p org-icalendar-timezone) org-icalendar-timezone
  740. (cadr (current-time-zone)))
  741. ;; Description.
  742. (org-export-data (plist-get info :title) info)
  743. contents))
  744. (defun org-icalendar--vcalendar (name owner tz description contents)
  745. "Create a VCALENDAR component.
  746. NAME, OWNER, TZ, DESCRIPTION and CONTENTS are all strings giving,
  747. respectively, the name of the calendar, its owner, the timezone
  748. used, a short description and the other components included."
  749. (concat (format "BEGIN:VCALENDAR
  750. VERSION:2.0
  751. X-WR-CALNAME:%s
  752. PRODID:-//%s//Emacs with Org mode//EN
  753. X-WR-TIMEZONE:%s
  754. X-WR-CALDESC:%s
  755. CALSCALE:GREGORIAN\n"
  756. (org-icalendar-cleanup-string name)
  757. (org-icalendar-cleanup-string owner)
  758. (org-icalendar-cleanup-string tz)
  759. (org-icalendar-cleanup-string description))
  760. contents
  761. "END:VCALENDAR\n"))
  762. ;;; Interactive Functions
  763. ;;;###autoload
  764. (defun org-icalendar-export-to-ics
  765. (&optional async subtreep visible-only body-only)
  766. "Export current buffer to an iCalendar file.
  767. If narrowing is active in the current buffer, only export its
  768. narrowed part.
  769. If a region is active, export that region.
  770. A non-nil optional argument ASYNC means the process should happen
  771. asynchronously. The resulting file should be accessible through
  772. the `org-export-stack' interface.
  773. When optional argument SUBTREEP is non-nil, export the sub-tree
  774. at point, extracting information from the headline properties
  775. first.
  776. When optional argument VISIBLE-ONLY is non-nil, don't export
  777. contents of hidden elements.
  778. When optional argument BODY-ONLY is non-nil, only write code
  779. between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\".
  780. Return ICS file name."
  781. (interactive)
  782. (let ((file (buffer-file-name (buffer-base-buffer))))
  783. (when (and file org-icalendar-store-UID)
  784. (org-icalendar-create-uid file 'warn-user)))
  785. ;; Export part. Since this back-end is backed up by `ascii', ensure
  786. ;; links will not be collected at the end of sections.
  787. (let ((outfile (org-export-output-file-name ".ics" subtreep)))
  788. (org-export-to-file 'icalendar outfile
  789. async subtreep visible-only body-only
  790. '(:ascii-charset utf-8 :ascii-links-to-notes nil)
  791. '(lambda (file)
  792. (run-hook-with-args 'org-icalendar-after-save-hook file) nil))))
  793. ;;;###autoload
  794. (defun org-icalendar-export-agenda-files (&optional async)
  795. "Export all agenda files to iCalendar files.
  796. When optional argument ASYNC is non-nil, export happens in an
  797. external process."
  798. (interactive)
  799. (if async
  800. ;; Asynchronous export is not interactive, so we will not call
  801. ;; `org-check-agenda-file'. Instead we remove any non-existent
  802. ;; agenda file from the list.
  803. (let ((files (cl-remove-if-not #'file-exists-p (org-agenda-files t))))
  804. (org-export-async-start
  805. (lambda (results)
  806. (dolist (f results) (org-export-add-to-stack f 'icalendar)))
  807. `(let (output-files)
  808. (dolist (file ',files outputfiles)
  809. (with-current-buffer (org-get-agenda-file-buffer file)
  810. (push (expand-file-name (org-icalendar-export-to-ics))
  811. output-files))))))
  812. (let ((files (org-agenda-files t)))
  813. (org-agenda-prepare-buffers files)
  814. (unwind-protect
  815. (dolist (file files)
  816. (catch 'nextfile
  817. (org-check-agenda-file file)
  818. (with-current-buffer (org-get-agenda-file-buffer file)
  819. (org-icalendar-export-to-ics))))
  820. (org-release-buffers org-agenda-new-buffers)))))
  821. ;;;###autoload
  822. (defun org-icalendar-combine-agenda-files (&optional async)
  823. "Combine all agenda files into a single iCalendar file.
  824. A non-nil optional argument ASYNC means the process should happen
  825. asynchronously. The resulting file should be accessible through
  826. the `org-export-stack' interface.
  827. The file is stored under the name chosen in
  828. `org-icalendar-combined-agenda-file'."
  829. (interactive)
  830. (if async
  831. (let ((files (cl-remove-if-not #'file-exists-p (org-agenda-files t))))
  832. (org-export-async-start
  833. (lambda (_)
  834. (org-export-add-to-stack
  835. (expand-file-name org-icalendar-combined-agenda-file)
  836. 'icalendar))
  837. `(apply #'org-icalendar--combine-files ',files)))
  838. (apply #'org-icalendar--combine-files (org-agenda-files t))))
  839. (defun org-icalendar-export-current-agenda (file)
  840. "Export current agenda view to an iCalendar FILE.
  841. This function assumes major mode for current buffer is
  842. `org-agenda-mode'."
  843. (let* ((org-export-use-babel) ;don't evaluate Babel blocks
  844. (contents
  845. (org-export-string-as
  846. (with-output-to-string
  847. (save-excursion
  848. (let ((p (point-min))
  849. (seen nil)) ;prevent duplicates
  850. (while (setq p (next-single-property-change p 'org-hd-marker))
  851. (let ((m (get-text-property p 'org-hd-marker)))
  852. (when (and m (not (member m seen)))
  853. (push m seen)
  854. (with-current-buffer (marker-buffer m)
  855. (org-with-wide-buffer
  856. (goto-char (marker-position m))
  857. (princ
  858. (org-element-normalize-string
  859. (buffer-substring (point)
  860. (org-entry-end-position))))))))
  861. (forward-line)))))
  862. 'icalendar t
  863. '(:ascii-charset utf-8 :ascii-links-to-notes nil
  864. :icalendar-include-todo all))))
  865. (with-temp-file file
  866. (insert
  867. (org-icalendar--vcalendar
  868. org-icalendar-combined-name
  869. user-full-name
  870. (or (org-string-nw-p org-icalendar-timezone) (cadr (current-time-zone)))
  871. org-icalendar-combined-description
  872. contents)))
  873. (run-hook-with-args 'org-icalendar-after-save-hook file)))
  874. (defun org-icalendar--combine-files (&rest files)
  875. "Combine entries from multiple files into an iCalendar file.
  876. FILES is a list of files to build the calendar from."
  877. ;; At the end of the process, all buffers related to FILES are going
  878. ;; to be killed. Make sure to only kill the ones opened in the
  879. ;; process.
  880. (let ((org-agenda-new-buffers nil))
  881. (unwind-protect
  882. (progn
  883. (with-temp-file org-icalendar-combined-agenda-file
  884. (insert
  885. (org-icalendar--vcalendar
  886. ;; Name.
  887. org-icalendar-combined-name
  888. ;; Owner.
  889. user-full-name
  890. ;; Timezone.
  891. (or (org-string-nw-p org-icalendar-timezone)
  892. (cadr (current-time-zone)))
  893. ;; Description.
  894. org-icalendar-combined-description
  895. ;; Contents.
  896. (concat
  897. ;; Agenda contents.
  898. (mapconcat
  899. (lambda (file)
  900. (catch 'nextfile
  901. (org-check-agenda-file file)
  902. (with-current-buffer (org-get-agenda-file-buffer file)
  903. ;; Create ID if necessary.
  904. (when org-icalendar-store-UID
  905. (org-icalendar-create-uid file t))
  906. (org-export-as
  907. 'icalendar nil nil t
  908. '(:ascii-charset utf-8 :ascii-links-to-notes nil)))))
  909. files "")
  910. ;; BBDB anniversaries.
  911. (when (and org-icalendar-include-bbdb-anniversaries
  912. (require 'ol-bbdb nil t))
  913. (with-output-to-string (org-bbdb-anniv-export-ical)))))))
  914. (run-hook-with-args 'org-icalendar-after-save-hook
  915. org-icalendar-combined-agenda-file))
  916. (org-release-buffers org-agenda-new-buffers))))
  917. (provide 'ox-icalendar)
  918. ;; Local variables:
  919. ;; generated-autoload-file: "org-loaddefs.el"
  920. ;; End:
  921. ;;; ox-icalendar.el ends here