ox-icalendar.el 37 KB

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