ox-icalendar.el 37 KB

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