ox-icalendar.el 37 KB

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