ox-icalendar.el 37 KB

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