ox-icalendar.el 37 KB

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