org-e-icalendar.el 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. ;;; org-e-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. ;; This program 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. ;; This program 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 this program. 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-e-icalendar-export-to-ics' (current
  24. ;; file), `org-e-icalendar-export-agenda-files' (agenda files into
  25. ;; separate calendars) and `org-e-icalendar-combined-agenda-file'
  26. ;; (agenda files into one combined calendar).
  27. ;;
  28. ;; It also provides the `org-e-icalendar-export-current-agenda'
  29. ;; function, which will create a calendar file from current agenda
  30. ;; view. It is 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. (require 'org-e-ascii)
  39. (declare-function org-bbdb-anniv-export-ical "org-bbdb" nil)
  40. ;;; User-Configurable Variables
  41. (defgroup org-export-e-icalendar nil
  42. "Options specific for iCalendar export back-end."
  43. :tag "Org iCalendar"
  44. :group 'org-export)
  45. (defcustom org-e-icalendar-combined-agenda-file "~/org.ics"
  46. "The file name for the iCalendar file covering all agenda files.
  47. This file is created with the command \\[org-e-icalendar-combine-agenda-files].
  48. The file name should be absolute. It will be overwritten without warning."
  49. :group 'org-export-e-icalendar
  50. :type 'file)
  51. (defcustom org-e-icalendar-alarm-time 0
  52. "Number of minutes for triggering an alarm for exported timed events.
  53. A zero value (the default) turns off the definition of an alarm trigger
  54. for timed events. If non-zero, alarms are created.
  55. - a single alarm per entry is defined
  56. - The alarm will go off N minutes before the event
  57. - only a DISPLAY action is defined."
  58. :group 'org-export-e-icalendar
  59. :version "24.1"
  60. :type 'integer)
  61. (defcustom org-e-icalendar-combined-name "OrgMode"
  62. "Calendar name for the combined iCalendar representing all agenda files."
  63. :group 'org-export-e-icalendar
  64. :type 'string)
  65. (defcustom org-e-icalendar-combined-description ""
  66. "Calendar description for the combined iCalendar (all agenda files)."
  67. :group 'org-export-e-icalendar
  68. :type 'string)
  69. (defcustom org-e-icalendar-exclude-tags nil
  70. "Tags that exclude a tree from export.
  71. This variable allows to specify different exclude tags from other
  72. back-ends. It can also be set with the ICAL_EXCLUDE_TAGS
  73. keyword."
  74. :group 'org-export-e-icalendar
  75. :type '(repeat (string :tag "Tag")))
  76. (defcustom org-e-icalendar-use-deadline '(event-if-not-todo todo-due)
  77. "Contexts where iCalendar export should use a deadline time stamp.
  78. This is a list with several symbols in it. Valid symbol are:
  79. `event-if-todo' Deadlines in TODO entries become calendar events.
  80. `event-if-not-todo' Deadlines in non-TODO entries become calendar events.
  81. `todo-due' Use deadlines in TODO entries as due-dates"
  82. :group 'org-export-e-icalendar
  83. :type '(set :greedy t
  84. (const :tag "Deadlines in non-TODO entries become events"
  85. event-if-not-todo)
  86. (const :tag "Deadline in TODO entries become events"
  87. event-if-todo)
  88. (const :tag "Deadlines in TODO entries become due-dates"
  89. todo-due)))
  90. (defcustom org-e-icalendar-use-scheduled '(todo-start)
  91. "Contexts where iCalendar export should use a scheduling time stamp.
  92. This is a list with several symbols in it. Valid symbol are:
  93. `event-if-todo' Scheduling time stamps in TODO entries become an event.
  94. `event-if-not-todo' Scheduling time stamps in non-TODO entries become an event.
  95. `todo-start' Scheduling time stamps in TODO entries become start date.
  96. Some calendar applications show TODO entries only after
  97. that date."
  98. :group 'org-export-e-icalendar
  99. :type '(set :greedy t
  100. (const :tag
  101. "SCHEDULED timestamps in non-TODO entries become events"
  102. event-if-not-todo)
  103. (const :tag "SCHEDULED timestamps in TODO entries become events"
  104. event-if-todo)
  105. (const :tag "SCHEDULED in TODO entries become start date"
  106. todo-start)))
  107. (defcustom org-e-icalendar-categories '(local-tags category)
  108. "Items that should be entered into the \"categories\" field.
  109. This is a list of symbols, the following are valid:
  110. `category' The Org mode category of the current file or tree
  111. `todo-state' The todo state, if any
  112. `local-tags' The tags, defined in the current line
  113. `all-tags' All tags, including inherited ones."
  114. :group 'org-export-e-icalendar
  115. :type '(repeat
  116. (choice
  117. (const :tag "The file or tree category" category)
  118. (const :tag "The TODO state" todo-state)
  119. (const :tag "Tags defined in current line" local-tags)
  120. (const :tag "All tags, including inherited ones" all-tags))))
  121. (defcustom org-e-icalendar-with-timestamps 'active
  122. "Non-nil means make an event from plain time stamps.
  123. It can be set to `active', `inactive', t or nil, in order to make
  124. an event from, respectively, only active timestamps, only
  125. inactive ones, all of them or none.
  126. This variable has precedence over `org-export-with-timestamps'.
  127. It can also be set with the #+OPTIONS line, e.g. \"<:t\"."
  128. :group 'org-export-e-icalendar
  129. :type '(choice
  130. (const :tag "All timestamps" t)
  131. (const :tag "Only active timestamps" active)
  132. (const :tag "Only inactive timestamps" inactive)
  133. (const :tag "No timestamp" nil)))
  134. (defcustom org-e-icalendar-include-todo nil
  135. "Non-nil means create VTODO components from TODO items.
  136. Valid values are:
  137. nil don't include any task.
  138. t include tasks that are not in DONE state.
  139. `unblocked' include all TODO items that are not blocked.
  140. `all' include both done and not done items."
  141. :group 'org-export-e-icalendar
  142. :type '(choice
  143. (const :tag "None" nil)
  144. (const :tag "Unfinished" t)
  145. (const :tag "Unblocked" unblocked)
  146. (const :tag "All" all)
  147. (repeat :tag "Specific TODO keywords"
  148. (string :tag "Keyword"))))
  149. (defcustom org-e-icalendar-include-bbdb-anniversaries nil
  150. "Non-nil means a combined iCalendar file should include anniversaries.
  151. The anniversaries are defined in the BBDB database."
  152. :group 'org-export-e-icalendar
  153. :type 'boolean)
  154. (defcustom org-e-icalendar-include-sexps t
  155. "Non-nil means export to iCalendar files should also cover sexp entries.
  156. These are entries like in the diary, but directly in an Org mode
  157. file."
  158. :group 'org-export-e-icalendar
  159. :type 'boolean)
  160. (defcustom org-e-icalendar-include-body t
  161. "Amount of text below headline to be included in iCalendar export.
  162. This is a number of characters that should maximally be included.
  163. Properties, scheduling and clocking lines will always be removed.
  164. The text will be inserted into the DESCRIPTION field."
  165. :group 'org-export-e-icalendar
  166. :type '(choice
  167. (const :tag "Nothing" nil)
  168. (const :tag "Everything" t)
  169. (integer :tag "Max characters")))
  170. (defcustom org-e-icalendar-store-UID nil
  171. "Non-nil means store any created UIDs in properties.
  172. The iCalendar standard requires that all entries have a unique identifier.
  173. Org will create these identifiers as needed. When this variable is non-nil,
  174. the created UIDs will be stored in the ID property of the entry. Then the
  175. next time this entry is exported, it will be exported with the same UID,
  176. superseding the previous form of it. This is essential for
  177. synchronization services.
  178. This variable is not turned on by default because we want to avoid creating
  179. a property drawer in every entry if people are only playing with this feature,
  180. or if they are only using it locally."
  181. :group 'org-export-e-icalendar
  182. :type 'boolean)
  183. (defcustom org-e-icalendar-timezone (getenv "TZ")
  184. "The time zone string for iCalendar export.
  185. When nil or the empty string, use output
  186. from (current-time-zone)."
  187. :group 'org-export-e-icalendar
  188. :type '(choice
  189. (const :tag "Unspecified" nil)
  190. (string :tag "Time zone")))
  191. (defcustom org-e-icalendar-date-time-format ":%Y%m%dT%H%M%S"
  192. "Format-string for exporting icalendar DATE-TIME.
  193. See `format-time-string' for a full documentation. The only
  194. difference is that `org-e-icalendar-timezone' is used for %Z.
  195. Interesting value are:
  196. - \":%Y%m%dT%H%M%S\" for local time
  197. - \";TZID=%Z:%Y%m%dT%H%M%S\" for local time with explicit timezone
  198. - \":%Y%m%dT%H%M%SZ\" for time expressed in Universal Time"
  199. :group 'org-export-e-icalendar
  200. :version "24.1"
  201. :type '(choice
  202. (const :tag "Local time" ":%Y%m%dT%H%M%S")
  203. (const :tag "Explicit local time" ";TZID=%Z:%Y%m%dT%H%M%S")
  204. (const :tag "Universal time" ":%Y%m%dT%H%M%SZ")
  205. (string :tag "Explicit format")))
  206. (defvar org-e-icalendar-after-save-hook nil
  207. "Hook run after an iCalendar file has been saved.
  208. This hook is run with the name of the file as argument. A good
  209. way to use this is to tell a desktop calendar application to
  210. re-read the iCalendar file.")
  211. ;;; Define Back-End
  212. (org-export-define-derived-backend e-icalendar e-ascii
  213. :translate-alist ((clock . ignore)
  214. (headline . org-e-icalendar-entry)
  215. (inlinetask . ignore)
  216. (planning . ignore)
  217. (section . ignore)
  218. (template . org-e-icalendar-template))
  219. :options-alist
  220. ((:exclude-tags
  221. "ICALENDAR_EXCLUDE_TAGS" nil org-e-icalendar-exclude-tags split)
  222. (:with-timestamps nil "<" org-e-icalendar-with-timestamps)
  223. (:with-vtodo nil nil org-e-icalendar-include-todo)
  224. ;; The following property will be non-nil when export has been
  225. ;; started from org-agenda-mode. In this case, any entry without
  226. ;; a non-nil "ICALENDAR_MARK" property will be ignored.
  227. (:icalendar-agenda-view nil nil nil))
  228. :filters-alist
  229. ((:filter-headline . org-e-icalendar-clear-blank-lines))
  230. :menu-entry
  231. (?c "Export to iCalendar"
  232. ((?f "Current file" org-e-icalendar-export-to-ics)
  233. (?a "All agenda files"
  234. (lambda (a s v b) (org-e-icalendar-export-agenda-files a)))
  235. (?c "Combine all agenda files"
  236. (lambda (a s v b) (org-e-icalendar-combine-agenda-files a))))))
  237. ;;; Internal Functions
  238. (defun org-e-icalendar-create-uid (file &optional bell)
  239. "Set ID property on headlines missing it in FILE.
  240. When optional argument BELL is non-nil, inform the user with
  241. a message if the file was modified."
  242. (let (modified-flag)
  243. (org-map-entries
  244. (lambda ()
  245. (let ((entry (org-element-at-point)))
  246. (unless (org-element-property :id entry)
  247. (org-id-get-create)
  248. (setq modified-flag t)
  249. (forward-line))
  250. (when (eq (org-element-type entry) 'inlinetask)
  251. (setq org-map-continue-from (org-element-property :end entry)))))
  252. nil nil 'comment)
  253. (when (and bell modified-flag)
  254. (message "ID properties created in file \"%s\"" file)
  255. (sit-for 2))))
  256. (defun org-e-icalendar-blocked-headline-p (headline info)
  257. "Non-nil when HEADLINE is considered to be blocked.
  258. INFO is a plist used as a communication channel.
  259. An headline is blocked when either:
  260. - It has children which are not all in a completed state.
  261. - It has a parent with the property :ORDERED:, and there are
  262. siblings prior to it with incomplete status.
  263. - Its parent is blocked because it has siblings that should be
  264. done first or is a child of a blocked grandparent entry."
  265. (or
  266. ;; Check if any child is not done.
  267. (org-element-map
  268. headline 'headline
  269. (lambda (hl) (eq (org-element-property :todo-type hl) 'todo))
  270. info 'first-match)
  271. ;; Check :ORDERED: node property.
  272. (catch 'blockedp
  273. (let ((current headline))
  274. (mapc (lambda (parent)
  275. (cond
  276. ((not (org-element-property :todo-keyword parent))
  277. (throw 'blockedp nil))
  278. ((org-not-nil (org-element-property :ordered parent))
  279. (let ((sibling current))
  280. (while (setq sibling (org-export-get-previous-element
  281. sibling info))
  282. (when (eq (org-element-property :todo-type sibling) 'todo)
  283. (throw 'blockedp t)))))
  284. (t (setq current parent))))
  285. (org-export-get-genealogy headline))
  286. nil))))
  287. (defun org-e-icalendar-use-UTC-date-time-p ()
  288. "Non-nil when `org-e-icalendar-date-time-format' requires UTC time."
  289. (char-equal (elt org-e-icalendar-date-time-format
  290. (1- (length org-e-icalendar-date-time-format))) ?Z))
  291. (defvar org-agenda-default-appointment-duration) ; From org-agenda.el.
  292. (defun org-e-icalendar-convert-timestamp (timestamp keyword &optional end utc)
  293. "Convert TIMESTAMP to iCalendar format.
  294. TIMESTAMP is a timestamp object. KEYWORD is added in front of
  295. it, in order to make a complete line (e.g. \"DTSTART\").
  296. When optional argument END is non-nil, use end of time range.
  297. Also increase the hour by two (if time string contains a time),
  298. or the day by one (if it does not contain a time) when no
  299. explicit ending time is specified.
  300. When optional argument UTC is non-nil, time will be expressed in
  301. Universal Time, ignoring `org-e-icalendar-date-time-format'.
  302. This is mandatory for \"DTSTAMP\" property."
  303. (let* ((year-start (org-element-property :year-start timestamp))
  304. (year-end (org-element-property :year-end timestamp))
  305. (month-start (org-element-property :month-start timestamp))
  306. (month-end (org-element-property :month-end timestamp))
  307. (day-start (org-element-property :day-start timestamp))
  308. (day-end (org-element-property :day-end timestamp))
  309. (hour-start (org-element-property :hour-start timestamp))
  310. (hour-end (org-element-property :hour-end timestamp))
  311. (minute-start (org-element-property :minute-start timestamp))
  312. (minute-end (org-element-property :minute-end timestamp))
  313. (with-time-p minute-start)
  314. (equal-bounds-p
  315. (equal (list year-start month-start day-start hour-start minute-start)
  316. (list year-end month-end day-end hour-end minute-end)))
  317. (mi (cond ((not with-time-p) 0)
  318. ((not end) minute-start)
  319. ((and org-agenda-default-appointment-duration equal-bounds-p)
  320. (+ minute-end org-agenda-default-appointment-duration))
  321. (t minute-end)))
  322. (h (cond ((not with-time-p) 0)
  323. ((not end) hour-start)
  324. ((or (not equal-bounds-p)
  325. org-agenda-default-appointment-duration)
  326. hour-end)
  327. (t (+ hour-end 2))))
  328. (d (cond ((not end) day-start)
  329. ((not with-time-p) (1+ day-end))
  330. (t day-end)))
  331. (m (if end month-end month-start))
  332. (y (if end year-end year-start)))
  333. (concat
  334. keyword
  335. (format-time-string
  336. (cond (utc ":%Y%m%dT%H%M%SZ")
  337. ((not with-time-p) ";VALUE=DATE:%Y%m%d")
  338. (t (replace-regexp-in-string "%Z"
  339. org-e-icalendar-timezone
  340. org-e-icalendar-date-time-format
  341. t)))
  342. ;; Convert timestamp into internal time in order to use
  343. ;; `format-time-string' and fix any mistake (i.e. MI >= 60).
  344. (encode-time 0 mi h d m y)
  345. (or utc (and with-time-p (org-e-icalendar-use-UTC-date-time-p)))))))
  346. (defun org-e-icalendar-get-categories (entry info)
  347. "Return categories according to `org-e-icalendar-categories'.
  348. ENTRY is an headline or an inlinetask element. INFO is a plist
  349. used as a communication channel."
  350. (mapconcat
  351. 'identity
  352. (org-uniquify
  353. (let (categories)
  354. (mapc (lambda (type)
  355. (case type
  356. (category
  357. (push (org-export-get-category entry info) categories))
  358. (todo-state
  359. (let ((todo (org-element-property :todo-keyword entry)))
  360. (and todo (push todo categories))))
  361. (local-tags
  362. (setq categories
  363. (append (nreverse (org-export-get-tags entry info))
  364. categories)))
  365. (all-tags
  366. (setq categories
  367. (append (nreverse (org-export-get-tags entry info nil t))
  368. categories)))))
  369. org-e-icalendar-categories)
  370. ;; Return list of categories, following specified order.
  371. (nreverse categories))) ","))
  372. (defun org-e-icalendar-transcode-diary-sexp (sexp uid summary)
  373. "Transcode a diary sexp into iCalendar format.
  374. SEXP is the diary sexp being transcoded, as a string. UID is the
  375. unique identifier for the entry. SUMMARY defines a short summary
  376. or subject for the event."
  377. (when (require 'icalendar nil t)
  378. (org-element-normalize-string
  379. (with-temp-buffer
  380. (let ((sexp (if (not (string-match "\\`<%%" sexp)) sexp
  381. (concat (substring sexp 1 -1) " " summary))))
  382. (put-text-property 0 1 'uid uid sexp)
  383. (insert sexp "\n"))
  384. (org-diary-to-ical-string (current-buffer))))))
  385. (defun org-e-icalendar-cleanup-string (s)
  386. "Cleanup string S according to RFC 5545."
  387. (when s
  388. ;; Protect "\", "," and ";" characters. and replace newline
  389. ;; characters with literal \n.
  390. (replace-regexp-in-string
  391. "[ \t]*\n" "\\n"
  392. (replace-regexp-in-string "[\\,;]" "\\\&" s)
  393. nil t)))
  394. (defun org-e-icalendar-fold-string (s)
  395. "Fold string S according to RFC 5545."
  396. (org-element-normalize-string
  397. (mapconcat
  398. (lambda (line)
  399. ;; Limit each line to a maximum of 75 characters. If it is
  400. ;; longer, fold it by using "\n " as a continuation marker.
  401. (let ((len (length line)))
  402. (if (<= len 75) line
  403. (let ((folded-line (substring line 0 75))
  404. (chunk-start 75)
  405. chunk-end)
  406. ;; Since continuation marker takes up one character on the
  407. ;; line, real contents must be split at 74 chars.
  408. (while (< (setq chunk-end (+ chunk-start 74)) len)
  409. (setq folded-line
  410. (concat folded-line "\n "
  411. (substring line chunk-start chunk-end))
  412. chunk-start chunk-end))
  413. (concat folded-line "\n " (substring line chunk-start))))))
  414. (org-split-string s "\n") "\n")))
  415. ;;; Filters
  416. (defun org-e-icalendar-clear-blank-lines (headline back-end info)
  417. "Remove trailing blank lines in HEADLINE export.
  418. HEADLINE is a string representing a transcoded headline.
  419. BACK-END and INFO are ignored."
  420. (replace-regexp-in-string "^\\(?:[ \t]*\n\\)*" "" headline))
  421. ;;; Transcode Functions
  422. ;;;; Headline and Inlinetasks
  423. ;; The main function is `org-e-icalendar-entry', which extracts
  424. ;; information from an headline or an inlinetask (summary,
  425. ;; description...) and then delegates code generation to
  426. ;; `org-e-icalendar--vtodo' and `org-e-icalendar--vevent', depending
  427. ;; on the component needed.
  428. ;; Obviously, `org-e-icalendar--valarm' handles alarms, which can
  429. ;; happen within a VTODO component.
  430. (defun org-e-icalendar-entry (entry contents info)
  431. "Transcode ENTRY element into iCalendar format.
  432. ENTRY is either an headline or an inlinetask. CONTENTS is
  433. ignored. INFO is a plist used as a communication channel.
  434. This function is called on every headline, the section below
  435. it (minus inlinetasks) being its contents. It tries to create
  436. VEVENT and VTODO components out of scheduled date, deadline date,
  437. plain timestamps, diary sexps. It also calls itself on every
  438. inlinetask within the section."
  439. (unless (org-element-property :footnote-section-p entry)
  440. (let* ((type (org-element-type entry))
  441. ;; Determine contents really associated to the entry. For
  442. ;; an headline, limit them to section, if any. For an
  443. ;; inlinetask, this is every element within the task.
  444. (inside
  445. (if (eq type 'inlinetask)
  446. (cons 'org-data (cons nil (org-element-contents entry)))
  447. (let ((first (car (org-element-contents entry))))
  448. (and (eq (org-element-type first) 'section)
  449. (cons 'org-data
  450. (cons nil (org-element-contents first))))))))
  451. (concat
  452. (unless (and (plist-get info :icalendar-agenda-view)
  453. (not (org-element-property :icalendar-mark entry)))
  454. (let ((todo-type (org-element-property :todo-type entry))
  455. (uid (or (org-element-property :id entry) (org-id-new)))
  456. (summary (org-e-icalendar-cleanup-string
  457. (or (org-element-property :summary entry)
  458. (org-export-data
  459. (org-element-property :title entry) info))))
  460. (loc (org-e-icalendar-cleanup-string
  461. (org-element-property :location entry)))
  462. ;; Build description of the entry from associated
  463. ;; section (headline) or contents (inlinetask).
  464. (desc
  465. (org-e-icalendar-cleanup-string
  466. (or (org-element-property :description entry)
  467. (let ((contents (org-export-data inside info)))
  468. (cond
  469. ((not (org-string-nw-p contents)) nil)
  470. ((wholenump org-e-icalendar-include-body)
  471. (let ((contents (org-trim contents)))
  472. (substring
  473. contents 0 (min (length contents)
  474. org-e-icalendar-include-body))))
  475. (org-e-icalendar-include-body (org-trim contents)))))))
  476. (cat (org-e-icalendar-get-categories entry info)))
  477. (concat
  478. ;; Events: Delegate to `org-e-icalendar--vevent' to
  479. ;; generate "VEVENT" component from scheduled, deadline,
  480. ;; or any timestamp in the entry.
  481. (let ((deadline (org-element-property :deadline entry)))
  482. (and deadline
  483. (memq (if todo-type 'event-if-todo 'event-if-not-todo)
  484. org-e-icalendar-use-deadline)
  485. (org-e-icalendar--vevent
  486. entry deadline (concat "DL-" uid)
  487. (concat "DL: " summary) loc desc cat)))
  488. (let ((scheduled (org-element-property :scheduled entry)))
  489. (and scheduled
  490. (memq (if todo-type 'event-if-todo 'event-if-not-todo)
  491. org-e-icalendar-use-scheduled)
  492. (org-e-icalendar--vevent
  493. entry scheduled (concat "SC-" uid)
  494. (concat "S: " summary) loc desc cat)))
  495. ;; When collecting plain timestamps from an headline and
  496. ;; its title, skip inlinetasks since collection will
  497. ;; happen once ENTRY is one of them.
  498. (let ((counter 0))
  499. (mapconcat
  500. 'identity
  501. (org-element-map
  502. (cons (org-element-property :title entry)
  503. (org-element-contents inside))
  504. 'timestamp
  505. (lambda (ts)
  506. (let ((uid (format "TS%d-%s" (incf counter) uid)))
  507. (org-e-icalendar--vevent entry ts uid summary loc desc cat)))
  508. info nil (and (eq type 'headline) 'inlinetask))
  509. ""))
  510. ;; Task: First check if it is appropriate to export it.
  511. ;; If so, call `org-e-icalendar--vtodo' to transcode it
  512. ;; into a "VTODO" component.
  513. (when (and todo-type
  514. (case (plist-get info :with-vtodo)
  515. (all t)
  516. (unblocked
  517. (and (eq type 'headline)
  518. (not (org-e-icalendar-blocked-headline-p
  519. entry info))))
  520. ('t (eq todo-type 'todo))))
  521. (org-e-icalendar--vtodo entry uid summary loc desc cat))
  522. ;; Diary-sexp: Collect every diary-sexp element within
  523. ;; ENTRY and its title, and transcode them. If ENTRY is
  524. ;; an headline, skip inlinetasks: they will be handled
  525. ;; separately.
  526. (when org-e-icalendar-include-sexps
  527. (let ((counter 0))
  528. (mapconcat 'identity
  529. (org-element-map
  530. (cons (org-element-property :title entry)
  531. (org-element-contents inside))
  532. 'diary-sexp
  533. (lambda (sexp)
  534. (org-e-icalendar-transcode-diary-sexp
  535. (org-element-property :value sexp)
  536. (format "DS%d-%s" (incf counter) uid)
  537. summary))
  538. info nil (and (eq type 'headline) 'inlinetask))
  539. ""))))))
  540. ;; If ENTRY is an headline, call current function on every
  541. ;; inlinetask within it. In agenda export, this is independent
  542. ;; from the mark (or lack thereof) on the entry.
  543. (when (eq type 'headline)
  544. (mapconcat 'identity
  545. (org-element-map
  546. inside 'inlinetask
  547. (lambda (task) (org-e-icalendar-entry task nil info))
  548. info) ""))
  549. ;; Don't forget components from inner entries.
  550. contents))))
  551. (defun org-e-icalendar--vevent
  552. (entry timestamp uid summary location description categories)
  553. "Create a VEVENT component.
  554. ENTRY is either an 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-e-icalendar-fold-string
  563. (if (eq (org-element-property :type timestamp) 'diary)
  564. (org-e-icalendar-transcode-diary-sexp
  565. (org-element-property :raw-value timestamp) uid summary)
  566. (concat "BEGIN:VEVENT\n"
  567. (org-e-icalendar-convert-timestamp timestamp "DTSTAMP" nil t) "\n"
  568. "UID:" uid "\n"
  569. (org-e-icalendar-convert-timestamp timestamp "DTSTART") "\n"
  570. (org-e-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-e-icalendar--valarm entry timestamp summary)
  585. "END:VEVENT"))))
  586. (defun org-e-icalendar--vtodo
  587. (entry uid summary location description categories)
  588. "Create a VTODO component.
  589. ENTRY is either an 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-e-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-e-icalendar-fold-string
  608. (concat "BEGIN:VTODO\n"
  609. "UID:TODO-" uid "\n"
  610. (org-e-icalendar-convert-timestamp start "DTSTAMP" nil t) "\n"
  611. (org-e-icalendar-convert-timestamp start "DTSTART") "\n"
  612. (and (memq 'todo-due org-e-icalendar-use-deadline)
  613. (org-element-property :deadline entry)
  614. (concat (org-e-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-e-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-e-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-e-icalendar-alarm-time alarm-time)))))
  659. ;;;; Template
  660. (defun org-e-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-e-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-e-icalendar-timezone) org-e-icalendar-timezone
  674. (cadr (current-time-zone)))
  675. ;; Description.
  676. (org-export-data (plist-get info :title) info)
  677. contents))
  678. (defun org-e-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-e-icalendar-cleanup-string name)
  691. (org-e-icalendar-cleanup-string owner)
  692. (org-e-icalendar-cleanup-string tz)
  693. (org-e-icalendar-cleanup-string description))
  694. contents
  695. "END:VCALENDAR\n"))
  696. ;;; Interactive Functions
  697. ;;;###autoload
  698. (defun org-e-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-e-icalendar-store-UID)
  718. (org-e-icalendar-create-uid file 'warn-user)))
  719. ;; Export part. Since this back-end is backed up by `e-ascii',
  720. ;; ensure 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 'e-icalendar)
  726. (run-hook-with-args 'org-e-icalendar-after-save-hook f))
  727. `(let ((org-e-ascii-links-to-notes nil))
  728. (expand-file-name
  729. (org-export-to-file
  730. 'e-icalendar ,outfile ,subtreep ,visible-only ,body-only
  731. '(:ascii-charset utf-8)))))
  732. (let ((org-e-ascii-links-to-notes nil))
  733. (org-export-to-file 'e-icalendar outfile subtreep visible-only body-only
  734. '(:ascii-charset utf-8)))
  735. (run-hook-with-args 'org-e-icalendar-after-save-hook outfile)
  736. outfile)))
  737. ;;;###autoload
  738. (defun org-e-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-e-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-e-icalendar-export-to-ics))))
  767. files)
  768. (org-release-buffers org-agenda-new-buffers)))))
  769. ;;;###autoload
  770. (defun org-e-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-e-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-e-icalendar-combined-agenda-file)
  784. 'e-icalendar))
  785. `(apply 'org-e-icalendar--combine-files nil ',files)))
  786. (apply 'org-e-icalendar--combine-files nil (org-agenda-files t))))
  787. (defun org-e-icalendar-export-current-agenda ()
  788. "Export current agenda view to an iCalendar file.
  789. The file is stored under the name
  790. `org-e-icalendar-combined-agenda-file'. This function assumes
  791. major mode for current buffer is `org-agenda-mode'."
  792. (apply 'org-e-icalendar--combine-files
  793. (org-create-marker-find-array (org-agenda-collect-markers))
  794. (org-agenda-files nil 'ifmode)))
  795. (defun org-e-icalendar--combine-files (restriction &rest files)
  796. "Combine entries from multiple files into an iCalendar file.
  797. RESTRICTION, when non-nil, is an alist where key is a file name
  798. and value a list of buffer positions pointing to entries that
  799. should appear in the calendar. It only makes sense if the
  800. function was called from an agenda buffer. FILES is a list of
  801. files to build the calendar from."
  802. (org-agenda-prepare-buffers files)
  803. (unwind-protect
  804. (progn
  805. (with-temp-file org-e-icalendar-combined-agenda-file
  806. (insert
  807. (org-e-icalendar--vcalendar
  808. ;; Name.
  809. org-e-icalendar-combined-name
  810. ;; Owner.
  811. user-full-name
  812. ;; Timezone.
  813. (if (org-string-nw-p org-e-icalendar-timezone)
  814. org-e-icalendar-timezone
  815. (cadr (current-time-zone)))
  816. ;; Description.
  817. org-e-icalendar-combined-description
  818. ;; Contents.
  819. (concat
  820. ;; Agenda contents.
  821. (mapconcat
  822. (lambda (file)
  823. (catch 'nextfile
  824. (org-check-agenda-file file)
  825. (with-current-buffer (org-get-agenda-file-buffer file)
  826. ;; Create ID if necessary.
  827. (when org-e-icalendar-store-UID
  828. (org-e-icalendar-create-uid file))
  829. (let ((marks (cdr (assoc (expand-file-name file)
  830. restriction))))
  831. (unless (and restriction (not marks))
  832. ;; Add a hook adding :ICALENDAR_MARK: property
  833. ;; to each entry appearing in agenda view.
  834. ;; Use `apply-partially' because the function
  835. ;; still has to accept one argument.
  836. (let ((org-export-before-processing-hook
  837. (cons (apply-partially
  838. (lambda (m-list dummy)
  839. (mapc (lambda (m)
  840. (org-entry-put
  841. m "ICALENDAR_MARK" "t"))
  842. m-list))
  843. (sort marks '>))
  844. org-export-before-processing-hook)))
  845. (org-export-as
  846. 'e-icalendar nil nil t
  847. (list :ascii-charset 'utf-8
  848. :icalendar-agenda-view restriction))))))))
  849. files "")
  850. ;; BBDB anniversaries.
  851. (when (and org-e-icalendar-include-bbdb-anniversaries
  852. (require 'org-bbdb nil t))
  853. (with-temp-buffer
  854. (org-bbdb-anniv-export-ical)
  855. (buffer-string)))))))
  856. (run-hook-with-args 'org-e-icalendar-after-save-hook
  857. org-e-icalendar-combined-agenda-file))
  858. (org-release-buffers org-agenda-new-buffers)))
  859. (provide 'org-e-icalendar)
  860. ;;; org-e-icalendar.el ends here