ox-icalendar.el 38 KB

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