ox-icalendar.el 37 KB

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