ox-icalendar.el 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. ;;; ox-icalendar.el --- iCalendar Back-End for Org Export Engine
  2. ;; Copyright (C) 2004-2014 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 'ox-ascii)
  27. (declare-function org-bbdb-anniv-export-ical "org-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 to specify different exclude tags from other
  60. back-ends. It can also be set with the ICAL_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. ;; The following property will be non-nil when export has been
  226. ;; started from org-agenda-mode. In this case, any entry without
  227. ;; a non-nil "ICALENDAR_MARK" property will be ignored.
  228. (:icalendar-agenda-view nil nil nil))
  229. :filters-alist
  230. '((:filter-headline . org-icalendar-clear-blank-lines))
  231. :menu-entry
  232. '(?c "Export to iCalendar"
  233. ((?f "Current file" org-icalendar-export-to-ics)
  234. (?a "All agenda files"
  235. (lambda (a s v b) (org-icalendar-export-agenda-files a)))
  236. (?c "Combine all agenda files"
  237. (lambda (a s v b) (org-icalendar-combine-agenda-files a))))))
  238. ;;; Internal Functions
  239. (defun org-icalendar-create-uid (file &optional bell h-markers)
  240. "Set ID property on headlines missing it in FILE.
  241. When optional argument BELL is non-nil, inform the user with
  242. a message if the file was modified. With optional argument
  243. H-MARKERS non-nil, it is a list of markers for the headlines
  244. which will be updated."
  245. (let ((pt (if h-markers (goto-char (car h-markers)) (point-min)))
  246. modified-flag)
  247. (org-map-entries
  248. (lambda ()
  249. (let ((entry (org-element-at-point)))
  250. (unless (or (< (point) pt) (org-element-property :ID entry))
  251. (org-id-get-create)
  252. (setq modified-flag t)
  253. (forward-line))
  254. (when h-markers (setq org-map-continue-from (pop h-markers)))))
  255. nil nil 'comment)
  256. (when (and bell modified-flag)
  257. (message "ID properties created in file \"%s\"" file)
  258. (sit-for 2))))
  259. (defun org-icalendar-blocked-headline-p (headline info)
  260. "Non-nil when HEADLINE is considered to be blocked.
  261. INFO is a plist used as a communication channel.
  262. A headline is blocked when either
  263. - it has children which are not all in a completed state;
  264. - it has a parent with the property :ORDERED:, and there are
  265. siblings prior to it with incomplete status;
  266. - its parent is blocked because it has siblings that should be
  267. done first or is a child of a blocked grandparent entry."
  268. (or
  269. ;; Check if any child is not done.
  270. (org-element-map headline 'headline
  271. (lambda (hl) (eq (org-element-property :todo-type hl) 'todo))
  272. info 'first-match)
  273. ;; Check :ORDERED: node property.
  274. (catch 'blockedp
  275. (let ((current headline))
  276. (mapc (lambda (parent)
  277. (cond
  278. ((not (org-element-property :todo-keyword parent))
  279. (throw 'blockedp nil))
  280. ((org-not-nil (org-element-property :ORDERED parent))
  281. (let ((sibling current))
  282. (while (setq sibling (org-export-get-previous-element
  283. sibling info))
  284. (when (eq (org-element-property :todo-type sibling) 'todo)
  285. (throw 'blockedp t)))))
  286. (t (setq current parent))))
  287. (org-export-get-genealogy headline))
  288. nil))))
  289. (defun org-icalendar-use-UTC-date-time-p ()
  290. "Non-nil when `org-icalendar-date-time-format' requires UTC time."
  291. (char-equal (elt org-icalendar-date-time-format
  292. (1- (length org-icalendar-date-time-format))) ?Z))
  293. (defvar org-agenda-default-appointment-duration) ; From org-agenda.el.
  294. (defun org-icalendar-convert-timestamp (timestamp keyword &optional end utc)
  295. "Convert TIMESTAMP to iCalendar format.
  296. TIMESTAMP is a timestamp object. KEYWORD is added in front of
  297. it, in order to make a complete line (e.g. \"DTSTART\").
  298. When optional argument END is non-nil, use end of time range.
  299. Also increase the hour by two (if time string contains a time),
  300. or the day by one (if it does not contain a time) when no
  301. explicit ending time is specified.
  302. When optional argument UTC is non-nil, time will be expressed in
  303. Universal Time, ignoring `org-icalendar-date-time-format'."
  304. (let* ((year-start (org-element-property :year-start timestamp))
  305. (year-end (org-element-property :year-end timestamp))
  306. (month-start (org-element-property :month-start timestamp))
  307. (month-end (org-element-property :month-end timestamp))
  308. (day-start (org-element-property :day-start timestamp))
  309. (day-end (org-element-property :day-end timestamp))
  310. (hour-start (org-element-property :hour-start timestamp))
  311. (hour-end (org-element-property :hour-end timestamp))
  312. (minute-start (org-element-property :minute-start timestamp))
  313. (minute-end (org-element-property :minute-end timestamp))
  314. (with-time-p minute-start)
  315. (equal-bounds-p
  316. (equal (list year-start month-start day-start hour-start minute-start)
  317. (list year-end month-end day-end hour-end minute-end)))
  318. (mi (cond ((not with-time-p) 0)
  319. ((not end) minute-start)
  320. ((and org-agenda-default-appointment-duration equal-bounds-p)
  321. (+ minute-end org-agenda-default-appointment-duration))
  322. (t minute-end)))
  323. (h (cond ((not with-time-p) 0)
  324. ((not end) hour-start)
  325. ((or (not equal-bounds-p)
  326. org-agenda-default-appointment-duration)
  327. hour-end)
  328. (t (+ hour-end 2))))
  329. (d (cond ((not end) day-start)
  330. ((not with-time-p) (1+ day-end))
  331. (t day-end)))
  332. (m (if end month-end month-start))
  333. (y (if end year-end year-start)))
  334. (concat
  335. keyword
  336. (format-time-string
  337. (cond (utc ":%Y%m%dT%H%M%SZ")
  338. ((not with-time-p) ";VALUE=DATE:%Y%m%d")
  339. (t (replace-regexp-in-string "%Z"
  340. org-icalendar-timezone
  341. org-icalendar-date-time-format
  342. t)))
  343. ;; Convert timestamp into internal time in order to use
  344. ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
  345. (encode-time 0 mi h d m y)
  346. (or utc (and with-time-p (org-icalendar-use-UTC-date-time-p)))))))
  347. (defun org-icalendar-dtstamp ()
  348. "Return DTSTAMP property, as a string."
  349. (format-time-string "DTSTAMP:%Y%m%dT%H%M%SZ" nil t))
  350. (defun org-icalendar-get-categories (entry info)
  351. "Return categories according to `org-icalendar-categories'.
  352. ENTRY is a headline or an inlinetask element. INFO is a plist
  353. used as a communication channel."
  354. (mapconcat
  355. 'identity
  356. (org-uniquify
  357. (let (categories)
  358. (mapc (lambda (type)
  359. (case type
  360. (category
  361. (push (org-export-get-category entry info) categories))
  362. (todo-state
  363. (let ((todo (org-element-property :todo-keyword entry)))
  364. (and todo (push todo categories))))
  365. (local-tags
  366. (setq categories
  367. (append (nreverse (org-export-get-tags entry info))
  368. categories)))
  369. (all-tags
  370. (setq categories
  371. (append (nreverse (org-export-get-tags entry info nil t))
  372. categories)))))
  373. org-icalendar-categories)
  374. ;; Return list of categories, following specified order.
  375. (nreverse categories))) ","))
  376. (defun org-icalendar-transcode-diary-sexp (sexp uid summary)
  377. "Transcode a diary sexp into iCalendar format.
  378. SEXP is the diary sexp being transcoded, as a string. UID is the
  379. unique identifier for the entry. SUMMARY defines a short summary
  380. or subject for the event."
  381. (when (require 'icalendar nil t)
  382. (org-element-normalize-string
  383. (with-temp-buffer
  384. (let ((sexp (if (not (string-match "\\`<%%" sexp)) sexp
  385. (concat (substring sexp 1 -1) " " summary))))
  386. (put-text-property 0 1 'uid uid sexp)
  387. (insert sexp "\n"))
  388. (org-diary-to-ical-string (current-buffer))))))
  389. (defun org-icalendar-cleanup-string (s)
  390. "Cleanup string S according to RFC 5545."
  391. (when s
  392. ;; Protect "\", "," and ";" characters. and replace newline
  393. ;; characters with literal \n.
  394. (replace-regexp-in-string
  395. "[ \t]*\n" "\\n"
  396. (replace-regexp-in-string "[\\,;]" "\\\&" s)
  397. nil t)))
  398. (defun org-icalendar-fold-string (s)
  399. "Fold string S according to RFC 5545."
  400. (org-element-normalize-string
  401. (mapconcat
  402. (lambda (line)
  403. ;; Limit each line to a maximum of 75 characters. If it is
  404. ;; longer, fold it by using "\n " as a continuation marker.
  405. (let ((len (length line)))
  406. (if (<= len 75) line
  407. (let ((folded-line (substring line 0 75))
  408. (chunk-start 75)
  409. chunk-end)
  410. ;; Since continuation marker takes up one character on the
  411. ;; line, real contents must be split at 74 chars.
  412. (while (< (setq chunk-end (+ chunk-start 74)) len)
  413. (setq folded-line
  414. (concat folded-line "\n "
  415. (substring line chunk-start chunk-end))
  416. chunk-start chunk-end))
  417. (concat folded-line "\n " (substring line chunk-start))))))
  418. (org-split-string s "\n") "\n")))
  419. ;;; Filters
  420. (defun org-icalendar-clear-blank-lines (headline back-end info)
  421. "Remove blank lines in HEADLINE export.
  422. HEADLINE is a string representing a transcoded headline.
  423. BACK-END and INFO are ignored."
  424. (replace-regexp-in-string "^\\(?:[ \t]*\n\\)+" "" headline))
  425. ;;; Transcode Functions
  426. ;;;; Headline and Inlinetasks
  427. ;; The main function is `org-icalendar-entry', which extracts
  428. ;; information from a headline or an inlinetask (summary,
  429. ;; description...) and then delegates code generation to
  430. ;; `org-icalendar--vtodo' and `org-icalendar--vevent', depending
  431. ;; on the component needed.
  432. ;; Obviously, `org-icalendar--valarm' handles alarms, which can
  433. ;; happen within a VTODO component.
  434. (defun org-icalendar-entry (entry contents info)
  435. "Transcode ENTRY element into iCalendar format.
  436. ENTRY is either a headline or an inlinetask. CONTENTS is
  437. ignored. INFO is a plist used as a communication channel.
  438. This function is called on every headline, the section below
  439. it (minus inlinetasks) being its contents. It tries to create
  440. VEVENT and VTODO components out of scheduled date, deadline date,
  441. plain timestamps, diary sexps. It also calls itself on every
  442. inlinetask within the section."
  443. (unless (org-element-property :footnote-section-p entry)
  444. (let* ((type (org-element-type entry))
  445. ;; Determine contents really associated to the entry. For
  446. ;; a headline, limit them to section, if any. For an
  447. ;; inlinetask, this is every element within the task.
  448. (inside
  449. (if (eq type 'inlinetask)
  450. (cons 'org-data (cons nil (org-element-contents entry)))
  451. (let ((first (car (org-element-contents entry))))
  452. (and (eq (org-element-type first) 'section)
  453. (cons 'org-data
  454. (cons nil (org-element-contents first))))))))
  455. (concat
  456. (unless (and (plist-get info :icalendar-agenda-view)
  457. (not (org-element-property :ICALENDAR-MARK entry)))
  458. (let ((todo-type (org-element-property :todo-type entry))
  459. (uid (or (org-element-property :ID entry) (org-id-new)))
  460. (summary (org-icalendar-cleanup-string
  461. (or (org-element-property :SUMMARY entry)
  462. (org-export-data
  463. (org-element-property :title entry) info))))
  464. (loc (org-icalendar-cleanup-string
  465. (org-element-property :LOCATION entry)))
  466. ;; Build description of the entry from associated
  467. ;; section (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. (concat
  482. ;; Events: Delegate to `org-icalendar--vevent' to
  483. ;; generate "VEVENT" component from scheduled, deadline,
  484. ;; or any timestamp in the entry.
  485. (let ((deadline (org-element-property :deadline entry)))
  486. (and deadline
  487. (memq (if todo-type 'event-if-todo 'event-if-not-todo)
  488. org-icalendar-use-deadline)
  489. (org-icalendar--vevent
  490. entry deadline (concat "DL-" uid)
  491. (concat "DL: " summary) loc desc cat)))
  492. (let ((scheduled (org-element-property :scheduled entry)))
  493. (and scheduled
  494. (memq (if todo-type 'event-if-todo 'event-if-not-todo)
  495. org-icalendar-use-scheduled)
  496. (org-icalendar--vevent
  497. entry scheduled (concat "SC-" uid)
  498. (concat "S: " summary) loc desc cat)))
  499. ;; When collecting plain timestamps from a headline and
  500. ;; its title, skip inlinetasks since collection will
  501. ;; happen once ENTRY is one of them.
  502. (let ((counter 0))
  503. (mapconcat
  504. #'identity
  505. (org-element-map (cons (org-element-property :title entry)
  506. (org-element-contents inside))
  507. 'timestamp
  508. (lambda (ts)
  509. (when (let ((type (org-element-property :type ts)))
  510. (case (plist-get info :with-timestamps)
  511. (active (memq type '(active active-range)))
  512. (inactive (memq type '(inactive inactive-range)))
  513. ((t) t)))
  514. (let ((uid (format "TS%d-%s" (incf counter) uid)))
  515. (org-icalendar--vevent
  516. entry ts uid summary loc desc cat))))
  517. info nil (and (eq type 'headline) 'inlinetask))
  518. ""))
  519. ;; Task: First check if it is appropriate to export it.
  520. ;; If so, call `org-icalendar--vtodo' to transcode it
  521. ;; into a "VTODO" component.
  522. (when (and todo-type
  523. (case (plist-get info :icalendar-include-todo)
  524. (all t)
  525. (unblocked
  526. (and (eq type 'headline)
  527. (not (org-icalendar-blocked-headline-p
  528. entry info))))
  529. ((t) (eq todo-type 'todo))))
  530. (org-icalendar--vtodo entry uid summary loc desc cat))
  531. ;; Diary-sexp: Collect every diary-sexp element within
  532. ;; ENTRY and its title, and transcode them. If ENTRY is
  533. ;; a headline, skip inlinetasks: they will be handled
  534. ;; separately.
  535. (when org-icalendar-include-sexps
  536. (let ((counter 0))
  537. (mapconcat #'identity
  538. (org-element-map
  539. (cons (org-element-property :title entry)
  540. (org-element-contents inside))
  541. 'diary-sexp
  542. (lambda (sexp)
  543. (org-icalendar-transcode-diary-sexp
  544. (org-element-property :value sexp)
  545. (format "DS%d-%s" (incf counter) uid)
  546. summary))
  547. info nil (and (eq type 'headline) 'inlinetask))
  548. ""))))))
  549. ;; If ENTRY is a headline, call current function on every
  550. ;; inlinetask within it. In agenda export, this is independent
  551. ;; from the mark (or lack thereof) on the entry.
  552. (when (eq type 'headline)
  553. (mapconcat #'identity
  554. (org-element-map inside 'inlinetask
  555. (lambda (task) (org-icalendar-entry task nil info))
  556. info) ""))
  557. ;; Don't forget components from inner entries.
  558. contents))))
  559. (defun org-icalendar--vevent
  560. (entry timestamp uid summary location description categories)
  561. "Create a VEVENT component.
  562. ENTRY is either a headline or an inlinetask element. TIMESTAMP
  563. is a timestamp object defining the date-time of the event. UID
  564. is the unique identifier for the event. SUMMARY defines a short
  565. summary or subject for the event. LOCATION defines the intended
  566. venue for the event. DESCRIPTION provides the complete
  567. description of the event. CATEGORIES defines the categories the
  568. event belongs to.
  569. Return VEVENT component as a string."
  570. (org-icalendar-fold-string
  571. (if (eq (org-element-property :type timestamp) 'diary)
  572. (org-icalendar-transcode-diary-sexp
  573. (org-element-property :raw-value timestamp) uid summary)
  574. (concat "BEGIN:VEVENT\n"
  575. (org-icalendar-dtstamp) "\n"
  576. "UID:" uid "\n"
  577. (org-icalendar-convert-timestamp timestamp "DTSTART") "\n"
  578. (org-icalendar-convert-timestamp timestamp "DTEND" t) "\n"
  579. ;; RRULE.
  580. (when (org-element-property :repeater-type timestamp)
  581. (format "RRULE:FREQ=%s;INTERVAL=%d\n"
  582. (case (org-element-property :repeater-unit timestamp)
  583. (hour "HOURLY") (day "DAILY") (week "WEEKLY")
  584. (month "MONTHLY") (year "YEARLY"))
  585. (org-element-property :repeater-value timestamp)))
  586. "SUMMARY:" summary "\n"
  587. (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
  588. (and (org-string-nw-p description)
  589. (format "DESCRIPTION:%s\n" description))
  590. "CATEGORIES:" categories "\n"
  591. ;; VALARM.
  592. (org-icalendar--valarm entry timestamp summary)
  593. "END:VEVENT"))))
  594. (defun org-icalendar--vtodo
  595. (entry uid summary location description categories)
  596. "Create a VTODO component.
  597. ENTRY is either a headline or an inlinetask element. UID is the
  598. unique identifier for the task. SUMMARY defines a short summary
  599. or subject for the task. LOCATION defines the intended venue for
  600. the task. DESCRIPTION provides the complete description of the
  601. task. CATEGORIES defines the categories the task belongs to.
  602. Return VTODO component as a string."
  603. (let ((start (or (and (memq 'todo-start org-icalendar-use-scheduled)
  604. (org-element-property :scheduled entry))
  605. ;; If we can't use a scheduled time for some
  606. ;; reason, start task now.
  607. (let ((now (decode-time (current-time))))
  608. (list 'timestamp
  609. (list :type 'active
  610. :minute-start (nth 1 now)
  611. :hour-start (nth 2 now)
  612. :day-start (nth 3 now)
  613. :month-start (nth 4 now)
  614. :year-start (nth 5 now)))))))
  615. (org-icalendar-fold-string
  616. (concat "BEGIN:VTODO\n"
  617. "UID:TODO-" uid "\n"
  618. (org-icalendar-dtstamp) "\n"
  619. (org-icalendar-convert-timestamp start "DTSTART") "\n"
  620. (and (memq 'todo-due org-icalendar-use-deadline)
  621. (org-element-property :deadline entry)
  622. (concat (org-icalendar-convert-timestamp
  623. (org-element-property :deadline entry) "DUE")
  624. "\n"))
  625. "SUMMARY:" summary "\n"
  626. (and (org-string-nw-p location) (format "LOCATION:%s\n" location))
  627. (and (org-string-nw-p description)
  628. (format "DESCRIPTION:%s\n" description))
  629. "CATEGORIES:" categories "\n"
  630. "SEQUENCE:1\n"
  631. (format "PRIORITY:%d\n"
  632. (let ((pri (or (org-element-property :priority entry)
  633. org-default-priority)))
  634. (floor (- 9 (* 8. (/ (float (- org-lowest-priority pri))
  635. (- org-lowest-priority
  636. org-highest-priority)))))))
  637. (format "STATUS:%s\n"
  638. (if (eq (org-element-property :todo-type entry) 'todo)
  639. "NEEDS-ACTION"
  640. "COMPLETED"))
  641. "END:VTODO"))))
  642. (defun org-icalendar--valarm (entry timestamp summary)
  643. "Create a VALARM component.
  644. ENTRY is the calendar entry triggering the alarm. TIMESTAMP is
  645. the start date-time of the entry. SUMMARY defines a short
  646. summary or subject for the task.
  647. Return VALARM component as a string, or nil if it isn't allowed."
  648. ;; Create a VALARM entry if the entry is timed. This is not very
  649. ;; general in that:
  650. ;; (a) only one alarm per entry is defined,
  651. ;; (b) only minutes are allowed for the trigger period ahead of the
  652. ;; start time,
  653. ;; (c) only a DISPLAY action is defined. [ESF]
  654. (let ((alarm-time
  655. (let ((warntime
  656. (org-element-property :APPT_WARNTIME entry)))
  657. (if warntime (string-to-number warntime) 0))))
  658. (and (or (> alarm-time 0) (> org-icalendar-alarm-time 0))
  659. (org-element-property :hour-start timestamp)
  660. (format "BEGIN:VALARM
  661. ACTION:DISPLAY
  662. DESCRIPTION:%s
  663. TRIGGER:-P0DT0H%dM0S
  664. END:VALARM\n"
  665. summary
  666. (if (zerop alarm-time) org-icalendar-alarm-time alarm-time)))))
  667. ;;;; Template
  668. (defun org-icalendar-template (contents info)
  669. "Return complete document string after iCalendar conversion.
  670. CONTENTS is the transcoded contents string. INFO is a plist used
  671. as a communication channel."
  672. (org-icalendar--vcalendar
  673. ;; Name.
  674. (if (not (plist-get info :input-file)) (buffer-name (buffer-base-buffer))
  675. (file-name-nondirectory
  676. (file-name-sans-extension (plist-get info :input-file))))
  677. ;; Owner.
  678. (if (not (plist-get info :with-author)) ""
  679. (org-export-data (plist-get info :author) info))
  680. ;; Timezone.
  681. (if (org-string-nw-p org-icalendar-timezone) org-icalendar-timezone
  682. (cadr (current-time-zone)))
  683. ;; Description.
  684. (org-export-data (plist-get info :title) info)
  685. contents))
  686. (defun org-icalendar--vcalendar (name owner tz description contents)
  687. "Create a VCALENDAR component.
  688. NAME, OWNER, TZ, DESCRIPTION and CONTENTS are all strings giving,
  689. respectively, the name of the calendar, its owner, the timezone
  690. used, a short description and the other components included."
  691. (concat (format "BEGIN:VCALENDAR
  692. VERSION:2.0
  693. X-WR-CALNAME:%s
  694. PRODID:-//%s//Emacs with Org mode//EN
  695. X-WR-TIMEZONE:%s
  696. X-WR-CALDESC:%s
  697. CALSCALE:GREGORIAN\n"
  698. (org-icalendar-cleanup-string name)
  699. (org-icalendar-cleanup-string owner)
  700. (org-icalendar-cleanup-string tz)
  701. (org-icalendar-cleanup-string description))
  702. contents
  703. "END:VCALENDAR\n"))
  704. ;;; Interactive Functions
  705. ;;;###autoload
  706. (defun org-icalendar-export-to-ics
  707. (&optional async subtreep visible-only body-only)
  708. "Export current buffer to an iCalendar file.
  709. If narrowing is active in the current buffer, only export its
  710. narrowed part.
  711. If a region is active, export that region.
  712. A non-nil optional argument ASYNC means the process should happen
  713. asynchronously. The resulting file should be accessible through
  714. the `org-export-stack' interface.
  715. When optional argument SUBTREEP is non-nil, export the sub-tree
  716. at point, extracting information from the headline properties
  717. first.
  718. When optional argument VISIBLE-ONLY is non-nil, don't export
  719. contents of hidden elements.
  720. When optional argument BODY-ONLY is non-nil, only write code
  721. between \"BEGIN:VCALENDAR\" and \"END:VCALENDAR\".
  722. Return ICS file name."
  723. (interactive)
  724. (let ((file (buffer-file-name (buffer-base-buffer))))
  725. (when (and file org-icalendar-store-UID)
  726. (org-icalendar-create-uid file 'warn-user)))
  727. ;; Export part. Since this back-end is backed up by `ascii', ensure
  728. ;; links will not be collected at the end of sections.
  729. (let ((outfile (org-export-output-file-name ".ics" subtreep)))
  730. (org-export-to-file 'icalendar outfile
  731. async subtreep visible-only body-only '(:ascii-charset utf-8)
  732. (lambda (file)
  733. (run-hook-with-args 'org-icalendar-after-save-hook file) nil))))
  734. ;;;###autoload
  735. (defun org-icalendar-export-agenda-files (&optional async)
  736. "Export all agenda files to iCalendar files.
  737. When optional argument ASYNC is non-nil, export happens in an
  738. external process."
  739. (interactive)
  740. (if async
  741. ;; Asynchronous export is not interactive, so we will not call
  742. ;; `org-check-agenda-file'. Instead we remove any non-existent
  743. ;; agenda file from the list.
  744. (let ((files (org-remove-if-not 'file-exists-p (org-agenda-files t))))
  745. (org-export-async-start
  746. (lambda (results)
  747. (mapc (lambda (f) (org-export-add-to-stack f 'icalendar))
  748. results))
  749. `(let (output-files)
  750. (mapc (lambda (file)
  751. (with-current-buffer (org-get-agenda-file-buffer file)
  752. (push (expand-file-name (org-icalendar-export-to-ics))
  753. output-files)))
  754. ',files)
  755. output-files)))
  756. (let ((files (org-agenda-files t)))
  757. (org-agenda-prepare-buffers files)
  758. (unwind-protect
  759. (mapc (lambda (file)
  760. (catch 'nextfile
  761. (org-check-agenda-file file)
  762. (with-current-buffer (org-get-agenda-file-buffer file)
  763. (org-icalendar-export-to-ics))))
  764. files)
  765. (org-release-buffers org-agenda-new-buffers)))))
  766. ;;;###autoload
  767. (defun org-icalendar-combine-agenda-files (&optional async)
  768. "Combine all agenda files into a single iCalendar file.
  769. A non-nil optional argument ASYNC means the process should happen
  770. asynchronously. The resulting file should be accessible through
  771. the `org-export-stack' interface.
  772. The file is stored under the name chosen in
  773. `org-icalendar-combined-agenda-file'."
  774. (interactive)
  775. (if async
  776. (let ((files (org-remove-if-not 'file-exists-p (org-agenda-files t))))
  777. (org-export-async-start
  778. (lambda (dummy)
  779. (org-export-add-to-stack
  780. (expand-file-name org-icalendar-combined-agenda-file)
  781. 'icalendar))
  782. `(apply 'org-icalendar--combine-files nil ',files)))
  783. (apply 'org-icalendar--combine-files nil (org-agenda-files t))))
  784. (defun org-icalendar-export-current-agenda (file)
  785. "Export current agenda view to an iCalendar FILE.
  786. This function assumes major mode for current buffer is
  787. `org-agenda-mode'."
  788. (let (org-export-babel-evaluate ; Don't evaluate Babel block
  789. (org-icalendar-combined-agenda-file file)
  790. (marker-list
  791. ;; Collect the markers pointing to entries in the current
  792. ;; agenda buffer.
  793. (let (markers)
  794. (save-excursion
  795. (goto-char (point-min))
  796. (while (not (eobp))
  797. (let ((m (or (org-get-at-bol 'org-hd-marker)
  798. (org-get-at-bol 'org-marker))))
  799. (and m (push m markers)))
  800. (beginning-of-line 2)))
  801. (nreverse markers))))
  802. (apply 'org-icalendar--combine-files
  803. ;; Build restriction alist.
  804. (let (restriction)
  805. ;; Sort markers in each association within RESTRICTION.
  806. (mapcar (lambda (x) (setcdr x (sort (copy-sequence (cdr x)) '<)) x)
  807. (dolist (m marker-list restriction)
  808. (let* ((pos (marker-position m))
  809. (file (buffer-file-name
  810. (org-base-buffer (marker-buffer m))))
  811. (file-markers (assoc file restriction)))
  812. ;; Add POS in FILE association if one exists
  813. ;; or create a new association for FILE.
  814. (if file-markers (push pos (cdr file-markers))
  815. (push (list file pos) restriction))))))
  816. (org-agenda-files nil 'ifmode))))
  817. (defun org-icalendar--combine-files (restriction &rest files)
  818. "Combine entries from multiple files into an iCalendar file.
  819. RESTRICTION, when non-nil, is an alist where key is a file name
  820. and value a list of buffer positions pointing to entries that
  821. should appear in the calendar. It only makes sense if the
  822. function was called from an agenda buffer. FILES is a list of
  823. files to build the calendar from."
  824. (org-agenda-prepare-buffers files)
  825. (unwind-protect
  826. (progn
  827. (with-temp-file org-icalendar-combined-agenda-file
  828. (insert
  829. (org-icalendar--vcalendar
  830. ;; Name.
  831. org-icalendar-combined-name
  832. ;; Owner.
  833. user-full-name
  834. ;; Timezone.
  835. (or (org-string-nw-p org-icalendar-timezone)
  836. (cadr (current-time-zone)))
  837. ;; Description.
  838. org-icalendar-combined-description
  839. ;; Contents.
  840. (concat
  841. ;; Agenda contents.
  842. (mapconcat
  843. (lambda (file)
  844. (catch 'nextfile
  845. (org-check-agenda-file file)
  846. (with-current-buffer (org-get-agenda-file-buffer file)
  847. (let ((marks (cdr (assoc (expand-file-name file)
  848. restriction))))
  849. ;; Create ID if necessary.
  850. (when org-icalendar-store-UID
  851. (org-icalendar-create-uid file t marks))
  852. (unless (and restriction (not marks))
  853. ;; Add a hook adding :ICALENDAR_MARK: property
  854. ;; to each entry appearing in agenda view.
  855. ;; Use `apply-partially' because the function
  856. ;; still has to accept one argument.
  857. (let ((org-export-before-processing-hook
  858. (cons (apply-partially
  859. (lambda (m-list dummy)
  860. (mapc (lambda (m)
  861. (org-entry-put
  862. m "ICALENDAR-MARK" "t"))
  863. m-list))
  864. (sort marks '>))
  865. org-export-before-processing-hook)))
  866. (org-export-as
  867. 'icalendar nil nil t
  868. (list :ascii-charset 'utf-8
  869. :icalendar-agenda-view restriction))))))))
  870. files "")
  871. ;; BBDB anniversaries.
  872. (when (and org-icalendar-include-bbdb-anniversaries
  873. (require 'org-bbdb nil t))
  874. (with-output-to-string (org-bbdb-anniv-export-ical)))))))
  875. (run-hook-with-args 'org-icalendar-after-save-hook
  876. org-icalendar-combined-agenda-file))
  877. (org-release-buffers org-agenda-new-buffers)))
  878. (provide 'ox-icalendar)
  879. ;; Local variables:
  880. ;; generated-autoload-file: "org-loaddefs.el"
  881. ;; End:
  882. ;;; ox-icalendar.el ends here