Release 6.25b
[org-mode/org-tableheadings.git] / lisp / org-feed.el
blobcedeb8938d3f8b25f9bae79d8a0766072cf4a46e
1 ;;; org-feed.el --- Add RSS feed items to Org files
2 ;;
3 ;; Copyright (C) 2009 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.25b
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; This module allows to create and change entries in an Org-mode
29 ;; file triggered by items in an RSS feed. The basic functionality is
30 ;; geared toward simply adding new items found in a feed as outline nodes
31 ;; to an Org file. Using hooks, arbitrary actions can be triggered for
32 ;; new or changed items.
34 ;; Selecting feeds and target locations
35 ;; ------------------------------------
37 ;; This module is configured through a single variable, `org-feed-alist'.
38 ;; Here is an example, using a notes/tasks feed from reQall.com.
40 ;; (setq org-feed-alist
41 ;; '(("ReQall"
42 ;; "http://www.reqall.com/user/feeds/rss/a1b2c3....."
43 ;; "~/org/feeds.org" "ReQall Entries")
45 ;; With this setup, the command `M-x org-feed-update-all' will
46 ;; collect new entries in the feed at the given URL and create
47 ;; entries as subheadings under the "ReQall Entries" heading in the
48 ;; file "~/org-feeds.org". Each feed should normally have its own
49 ;; heading - however see the `:drawer' parameter.
51 ;; Besides these standard elements that need to be specified for each
52 ;; feed, keyword-value pairs can set additional options. For example,
53 ;; to de-select transitional entries with a title containing
55 ;; "reQall is typing what you said",
57 ;; you could use the `:filter' argument:
59 ;; (setq org-feed-alist
60 ;; '(("ReQall"
61 ;; "http://www.reqall.com/user/feeds/rss/a1b2c3....."
62 ;; "~/org/feeds.org" "ReQall Entries"
63 ;; :filter my-reqall-filter)))
65 ;; (defun my-reqall-filter (e)
66 ;; (if (string-match "reQall is typing what you said"
67 ;; (plist-get e :title))
68 ;; nil
69 ;; e))
71 ;; See the docstring for `org-feed-alist' for more details.
74 ;; Keeping track of previously added entries
75 ;; -----------------------------------------
77 ;; Since Org allows you to delete, archive, or move outline nodes,
78 ;; org-feed.el needs to keep track of which feed items have been handled
79 ;; before, so that they will not be handled again. For this, org-feed.el
80 ;; stores information in a special drawer, FEEDSTATUS, under the heading
81 ;; that received the input of the feed. You should add FEEDSTATUS
82 ;; to your list of drawers in the files that receive feed input:
84 ;; #+DRAWERS: PROPERTIES LOGBOOK FEEDSTATUS
86 ;; Acknowledgments
87 ;; ----------------
89 ;; org-feed.el is based on ideas by Brad Bozarth who implemented a
90 ;; similar mechanism using shell and awk scripts.
92 ;;; Code:
94 (require 'org)
96 (declare-function url-retrieve-synchronously "url" (url))
98 (defgroup org-feed nil
99 "Options concerning RSS feeds as inputs for Org files."
100 :tag "Org ID"
101 :group 'org)
103 ;;;###autoload
104 (defcustom org-feed-alist nil
105 "Alist specifying RSS feeds that should create inputs for Org.
106 Each entry in this list specified an RSS feed tat should be queried
107 to create inbox items in Org. Each entry is a list with the following items:
109 name a custom name for this feed
110 URL the Feed URL
111 file the target Org file where entries should be listed
112 headline the headline under which entries should be listed
114 Additional arguments can be given using keyword-value pairs. Many of these
115 specify functions that receive one or a list of \"entries\" as their single
116 argument. An entry is a property list that describes a feed item. The
117 property list has properties for each field in the item, for example `:title'
118 for the `<title>' field and `:pubDate' for the publication date. In addition,
119 it contains the following properties:
121 `:item-full-text' the full text in the <item> tag
122 `:guid-permalink' t when the guid property is a permalink
124 Here are the keyword-value pair allows in `org-feed-alist'.
126 :drawer drawer-name
127 The name of the drawer for storing feed information. The default is
128 \"FEEDSTATUS\". Using different drawers for different feeds allows
129 several feeds to target the same inbox heading.
131 :filter filter-function
132 A function to select interesting entries in the feed. It gets a single
133 entry as parameter. It should return the entry if it is relevant, or
134 nil if it is not.
136 :template template-string
137 The default action on new items in the feed is to add them as children
138 under the headline for the feed. The template describes how the entry
139 should be formatted. If not given, it defaults to
140 `org-feed-default-template'.
142 :formatter formatter-function
143 Instead of relying on a template, you may specify a function to format
144 the outline node to be inserted as a child. This function gets passed
145 a property list describing a single feed item, and it should return a
146 string that is a properly formatted Org outline node of level 1.
148 :new-handler function
149 If adding new items as children to the outline is not what you want
150 to do with new items, define a handler function that is called with
151 a list of all new items in the feed, each one represented as a property
152 list. The handler should do what needs to be done, and org-feed will
153 mark all items given to this handler as \"handled\", i.e. they will not
154 be passed to this handler again in future readings of the feed.
155 When the handler is called, point will be at the feed headline.
157 :changed-handler function
158 This function gets passed a list of all entries that have been
159 handled before, but are now still in the feed and have *changed*
160 since last handled (as evidenced by a different sha1 hash).
161 When the handler is called, point will be at the feed headline."
162 :group 'org-feed
163 :type '(repeat
164 (list :value ("" "http://" "" "")
165 (string :tag "Name")
166 (string :tag "Feed URL")
167 (file :tag "File for inbox")
168 (string :tag "Headline for inbox")
169 (repeat :inline t
170 (choice
171 (list :inline t :tag "Filter"
172 (const :filter)
173 (symbol :tag "Filter Function"))
174 (list :inline t :tag "Template"
175 (const :template)
176 (string :tag "Template"))
177 (list :inline t :tag "Formatter"
178 (const :formatter)
179 (symbol :tag "Formatter Function"))
180 (list :inline t :tag "New items handler"
181 (const :new-handler)
182 (symbol :tag "Handler Function"))
183 (list :inline t :tag "Changed items"
184 (const :changed-handler)
185 (symbol :tag "Handler Function"))
186 )))))
188 (defcustom org-feed-drawer "FEEDSTATUS"
189 "The name of the drawer for feed status information.
190 Each feed may also specify its own drawer name using the `:drawer'
191 parameter in `org-feed-alist'.
192 Note that in order to make these drawers behave like drawers, they must
193 be added to the variable `org-drawers' or configured with a #+DRAWERS
194 line."
195 :group 'org-feed
196 :type '(string :tag "Drawer Name"))
198 (defcustom org-feed-default-template "\n* %h\n %U\n %description\n %a\n"
199 "Template for the Org node created from RSS feed items.
200 This is just the default, each feed can specify its own.
201 Any fields from the feed item can be interpolated into the template with
202 %name, for example %title, %description, %pubDate etc. In addition, the
203 following special escapes are valid as well:
205 %h the title, or the first line of the description
206 %t the date as a stamp, either from <pubDate> (if present), or
207 the current date.
208 %T date and time
209 %u,%U like %t,%T, but inactive time stamps
210 %a A link, from <guid> if that is a permalink, else from <link>"
211 :group 'org-feed
212 :type '(string :tag "Template"))
214 (defcustom org-feed-save-after-adding t
215 "Non-nil means, save buffer after adding new feed items."
216 :group 'org-feed
217 :type 'boolean)
219 (defcustom org-feed-retrieve-method 'url-retrieve-synchronously
220 "The method to be used to retrieve a feed URL.
221 This can be `curl' or `wget' to call these external programs, or it can be
222 an Emacs Lisp function that will return a buffer containing the content
223 of the file pointed to by the URL."
224 :group 'org-feed
225 :type '(choice
226 (const :tag "Internally with url.el" url-retrieve-synchronously)
227 (const :tag "Externally with curl" curl)
228 (const :tag "Externally with wget" wget)
229 (function :tag "Function")))
231 (defcustom org-feed-before-adding-hook nil
232 "Hook that is run before adding new feed items to a file.
233 You might want to commit the file in its current state to version control,
234 for example."
235 :group 'org-feed
236 :type 'hook)
238 (defcustom org-feed-after-adding-hook nil
239 "Hook that is run after new items have been added to a file.
240 Depending on `org-feed-save-after-adding', the buffer will already
241 have been saved."
242 :group 'org-feed
243 :type 'hook)
245 (defvar org-feed-buffer "*Org feed*"
246 "The buffer used to retrieve a feed.")
248 ;;;###autoload
249 (defun org-feed-update-all ()
250 "Get inbox items from all feeds in `org-feed-alist'."
251 (interactive)
252 (let ((nfeeds (length org-feed-alist))
253 (nnew (apply '+ (mapcar 'org-feed-update org-feed-alist))))
254 (message "%s from %d %s"
255 (cond ((= nnew 0) "No new entries")
256 ((= nnew 1) "1 new entry")
257 (t (format "%d new entries" nnew)))
258 nfeeds
259 (if (= nfeeds 1) "feed" "feeds"))))
261 ;;;###autoload
262 (defun org-feed-update (feed &optional retrieve-only)
263 "Get inbox items from FEED.
264 FEED can be a string with an association in `org-feed-alist', or
265 it can be a list structured like an entry in `org-feed-alist'."
266 (interactive (list (org-completing-read "Feed name: " org-feed-alist)))
267 (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
268 (unless feed
269 (error "No such feed in `org-feed-alist"))
270 (catch 'exit
271 (let ((name (car feed))
272 (url (nth 1 feed))
273 (file (nth 2 feed))
274 (headline (nth 3 feed))
275 (filter (nth 1 (memq :filter feed)))
276 (formatter (nth 1 (memq :formatter feed)))
277 (new-handler (nth 1 (memq :new-handler feed)))
278 (changed-handler (nth 1 (memq :changed-handler feed)))
279 (template (or (nth 1 (memq :template feed))
280 org-feed-default-template))
281 (drawer (or (nth 1 (memq :drawer feed))
282 org-feed-drawer))
283 feed-buffer inbox-pos
284 entries old-status status new changed guid-alist e guid olds)
285 (setq feed-buffer (org-feed-get-feed url))
286 (unless (and feed-buffer (bufferp feed-buffer))
287 (error "Cannot get feed %s" name))
288 (when retrieve-only
289 (throw 'exit feed-buffer))
290 (setq entries (org-feed-parse-feed feed-buffer))
291 (ignore-errors (kill-buffer feed-buffer))
292 (save-excursion
293 (save-window-excursion
294 (setq inbox-pos (org-feed-goto-inbox-internal file headline))
295 (setq old-status (org-feed-read-previous-status inbox-pos drawer))
296 ;; Add the "handled" status to the appropriate entries
297 (setq entries (mapcar (lambda (e)
298 (setq e (plist-put e :handled
299 (nth 1 (assoc
300 (plist-get e :guid)
301 old-status)))))
302 entries))
303 ;; Find out which entries are new and which are changed
304 (dolist (e entries)
305 (if (not (plist-get e :handled))
306 (push e new)
307 (setq olds (nth 2 (assoc (plist-get e :guid) old-status)))
308 (if (and olds
309 (not (string= (sha1-string (plist-get e :item-full-text))
310 olds)))
311 (push e changed))))
313 ;; Parse the relevant entries fully
314 (setq new (mapcar 'org-feed-parse-entry new)
315 changed (mapcar 'org-feed-parse-entry changed))
317 ;; Run the filter
318 (when filter
319 (setq new (delq nil (mapcar filter new))
320 changed (delq nil (mapcar filter new))))
322 (when (not (or new changed))
323 (message "No new items in feed %s" name)
324 (throw 'exit 0))
326 ;; Get alist based on guid, to look up entries
327 (setq guid-alist
328 (append
329 (mapcar (lambda (e) (list (plist-get e :guid) e)) new)
330 (mapcar (lambda (e) (list (plist-get e :guid) e)) changed)))
332 ;; Construct the new status
333 (setq status
334 (mapcar
335 (lambda (e)
336 (setq guid (plist-get e :guid))
337 (list guid
338 ;; things count as handled if we handle them now,
339 ;; or if they were handled previously
340 (if (assoc guid guid-alist) t (plist-get e :handled))
341 ;; A hash, to detect changes
342 (sha1-string (plist-get e :item-full-text))))
343 entries))
345 ;; Handle new items in the feed
346 (when new
347 (if new-handler
348 (progn
349 (goto-char inbox-pos)
350 (funcall new-handler new))
351 ;; No custom handler, do the default adding
352 ;; Format the new entries into an alist with GUIDs in the car
353 (setq new-formatted
354 (mapcar
355 (lambda (e) (org-feed-format-entry e template formatter))
356 new)))
358 ;; Insert the new items
359 (org-feed-add-items inbox-pos new-formatted))
361 ;; Handle changed items in the feed
362 (when (and changed-handler changed)
363 (goto-char inbox-pos)
364 (funcall changed-handler changed))
366 ;; Write the new status
367 ;; We do this only now, in case something goes wrong above, so
368 ;; that would would end up with a status that does not reflect
369 ;; which items truely have been handled
370 (org-feed-write-status inbox-pos drawer status)
372 ;; Normalize the visibility of the inbox tree
373 (goto-char inbox-pos)
374 (hide-subtree)
375 (show-children)
376 (org-cycle-hide-drawers 'children)
378 ;; Hooks and messages
379 (when org-feed-save-after-adding (save-buffer))
380 (message "Added %d new item%s from feed %s to file %s, heading %s"
381 (length new) (if (> (length new) 1) "s" "")
382 name
383 (file-name-nondirectory file) headline)
384 (run-hooks 'org-feed-after-adding-hook)
385 (length new))))))
387 ;;;###autoload
388 (defun org-feed-goto-inbox (feed)
389 "Go to the inbox that captures the feed named FEED."
390 (interactive
391 (list (if (= (length org-feed-alist) 1)
392 (car org-feed-alist)
393 (org-completing-read "Feed name: " org-feed-alist))))
394 (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
395 (unless feed
396 (error "No such feed in `org-feed-alist"))
397 (org-feed-goto-inbox-internal (nth 2 feed) (nth 3 feed)))
399 ;;;###autoload
400 (defun org-feed-show-raw-feed (feed)
401 "Show the raw feed buffer of a feed."
402 (interactive
403 (list (if (= (length org-feed-alist) 1)
404 (car org-feed-alist)
405 (org-completing-read "Feed name: " org-feed-alist))))
406 (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
407 (unless feed
408 (error "No such feed in `org-feed-alist"))
409 (switch-to-buffer
410 (org-feed-update feed 'retrieve-only))
411 (goto-char (point-min)))
413 (defun org-feed-goto-inbox-internal (file heading)
414 "Find or create HEADING in FILE.
415 Switch to that buffer, and return the position of that headline."
416 (find-file file)
417 (widen)
418 (goto-char (point-min))
419 (if (re-search-forward
420 (concat "^\\*+[ \t]+" heading "[ \t]*\\(:.*?:[ \t]*\\)?$")
421 nil t)
422 (goto-char (match-beginning 0))
423 (goto-char (point-max))
424 (insert "\n\n* " heading "\n\n")
425 (org-back-to-heading t))
426 (point))
428 (defun org-feed-read-previous-status (pos drawer)
429 "Get the alist of old GUIDs from the entry at POS.
430 This will find DRAWER and extract the alist."
431 (save-excursion
432 (goto-char pos)
433 (let ((end (save-excursion (org-end-of-subtree t t))))
434 (if (re-search-forward
435 (concat "^[ \t]*:" drawer ":[ \t]*\n\\([^\000]*?\\)\n[ \t]*:END:")
436 end t)
437 (read (match-string 1))
438 nil))))
440 (defun org-feed-write-status (pos drawer status)
441 "Write the feed STATUS to DRAWER in entry at POS."
442 (save-excursion
443 (goto-char pos)
444 (let ((end (save-excursion (org-end-of-subtree t t)))
445 guid)
446 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*\n")
447 end t)
448 (progn
449 (goto-char (match-end 0))
450 (delete-region (point)
451 (save-excursion
452 (and (re-search-forward "^[ \t]*:END:" nil t)
453 (match-beginning 0)))))
454 (outline-next-heading)
455 (insert " :" drawer ":\n :END:\n")
456 (beginning-of-line 0))
457 (insert (pp-to-string status)))))
459 (defun org-feed-add-items (pos entries)
460 "Add the formatted items to the headline as POS."
461 (let (entry level)
462 (save-excursion
463 (goto-char pos)
464 (unless (looking-at org-complex-heading-regexp)
465 (error "Wrong position"))
466 (setq level (org-get-valid-level (length (match-string 1)) 1))
467 (org-end-of-subtree t t)
468 (skip-chars-backward " \t\n")
469 (beginning-of-line 2)
470 (setq pos (point))
471 (while (setq entry (pop entries))
472 (org-paste-subtree level entry 'yank))
473 (org-mark-ring-push pos))))
475 (defun org-feed-format-entry (entry template formatter)
476 "Format ENTRY so that it can be inserted into an Org file.
477 ENTRY is a property list. This function adds a `:formatted-for-org' property
478 and returns the full property list.
479 If that property is already present, nothing changes."
480 (if formatter
481 (funcall formatter entry)
482 (let (dlines fmt tmp indent time
483 v-h v-t v-T v-u v-U v-a)
484 (setq dlines (org-split-string (or (plist-get entry :description) "???")
485 "\n")
486 v-h (or (plist-get entry :title) (car dlines) "???")
487 time (or (if (plist-get entry :pubDate)
488 (org-read-date t t (plist-get entry :pubDate)))
489 (current-time))
490 v-t (format-time-string (org-time-stamp-format nil nil) time)
491 v-T (format-time-string (org-time-stamp-format t nil) time)
492 v-u (format-time-string (org-time-stamp-format nil t) time)
493 v-U (format-time-string (org-time-stamp-format t t) time)
494 v-a (if (setq tmp (or (and (plist-get entry :guid-permalink)
495 (plist-get entry :guid))
496 (plist-get entry :link)))
497 (concat "[[" tmp "]]\n")
498 ""))
499 (with-temp-buffer
500 (insert template)
501 (goto-char (point-min))
502 (while (re-search-forward "%\\([a-zA-Z]+\\)" nil t)
503 (setq name (match-string 1))
504 (cond
505 ((member name '("h" "t" "T" "u" "U" "a"))
506 (replace-match (symbol-value (intern (concat "v-" name))) t t))
507 ((setq tmp (plist-get entry (intern (concat ":" name))))
508 (save-excursion
509 (save-match-data
510 (beginning-of-line 1)
511 (when (looking-at (concat "^\\([ \t]*\\)%" name "[ \t]*$"))
512 (setq tmp (org-feed-make-indented-block
513 tmp (org-get-indentation))))))
514 (replace-match tmp t t))))
515 (buffer-string)))))
517 (defun org-feed-make-indented-block (s n)
518 "Add indentaton of N spaces to a multiline string S."
519 (if (not (string-match "\n" s))
521 (mapconcat 'identity
522 (org-split-string s "\n")
523 (concat "\n" (make-string n ?\ )))))
525 (defun org-feed-get-feed (url)
526 "Get the RSS feed file at URL and return the buffer."
527 (cond
528 ((eq org-feed-retrieve-method 'url-retrieve-synchronously)
529 (url-retrieve-synchronously url))
530 ((eq org-feed-retrieve-method 'curl)
531 (ignore-errors (kill-buffer org-feed-buffer))
532 (call-process "curl" nil org-feed-buffer nil url)
533 org-feed-buffer)
534 ((eq org-feed-retrieve-method 'wget)
535 (ignore-errors (kill-buffer org-feed-buffer))
536 (call-process "curl" nil org-feed-buffer nil "-q" "-O" "-" url)
537 org-feed-buffer)
538 ((functionp org-feed-retrieve-method)
539 (funcall org-feed-retrieve-method url))))
541 (defun org-feed-parse-feed (buffer)
542 "Parse BUFFER for RS feed entries.
543 Returns a list of entries, with each entry a property list,
544 containing the properties `:guid' and `:item-full-text'."
545 (let (entries beg end item guid entry)
546 (with-current-buffer buffer
547 (widen)
548 (goto-char (point-min))
549 (while (re-search-forward "<item>" nil t)
550 (setq beg (point)
551 end (and (re-search-forward "</item>" nil t)
552 (match-beginning 0)))
553 (setq item (buffer-substring beg end)
554 guid (if (string-match "<guid\\>.*?>\\(.*?\\)</guid>" item)
555 (org-match-string-no-properties 1 item)))
556 (setq entry (list :guid guid :item-full-text item))
557 (push entry entries)
558 (widen)
559 (goto-char end))
560 (nreverse entries))))
562 (defun org-feed-parse-entry (entry)
563 "Parse the `:item-full-text' field for xml tags and create new properties."
564 (with-temp-buffer
565 (insert (plist-get entry :item-full-text))
566 (goto-char (point-min))
567 (while (re-search-forward "<\\([a-zA-Z]+\\>\\).*?>\\([^\000]*?\\)</\\1>"
568 nil t)
569 (setq entry (plist-put entry
570 (intern (concat ":" (match-string 1)))
571 (match-string 2))))
572 (goto-char (point-min))
573 (unless (re-search-forward "isPermaLink[ \t]*=[ \t]*\"false\"" nil t)
574 (setq entry (plist-put entry :guid-permalink t))))
575 entry)
577 (provide 'org-feed)
579 ;; arch-tag: 0929b557-9bc4-47f4-9633-30a12dbb5ae2
581 ;;; org-feed.el ends here