ox-icalendar.el 38 KB

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