ox-icalendar.el 39 KB

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