ox-icalendar.el 36 KB

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