ox-icalendar.el 37 KB

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