ox-icalendar.el 37 KB

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