ox-icalendar.el 35 KB

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