ox-icalendar.el 36 KB

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