Fix typos
[org-mode.git] / lisp / org-feed.el
blobdbda714def85969e0173fa919939af4b551e3892
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.24trans
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 needs to have its own heading.
50 ;; Besides these standard elements that need to be specified for each
51 ;; feed,, keyword-value pairs can set additional options. For example,
52 ;; to de-select transitional entries with a title containing
54 ;; "reQall is typing what you said",
56 ;; you could use the `:filter' argument:
58 ;; (setq org-feed-alist
59 ;; '(("ReQall"
60 ;; "http://www.reqall.com/user/feeds/rss/a1b2c3....."
61 ;; "~/org/feeds.org" "ReQall Entries"
62 ;; :filter my-reqall-filter)))
64 ;; (defun my-reqall-filter (e)
65 ;; (if (string-match "reQall is typing what you said"
66 ;; (plist-get e :title))
67 ;; nil
68 ;; e))
70 ;; See the docstring for `org-feed-alist' for more details.
73 ;; Keeping track of previously added entries
74 ;; -----------------------------------------
76 ;; Since Org allows you to delete, archive, or move outline nodes,
77 ;; org-feed.el needs to keep track of which feed items have been handled
78 ;; before, so that they will not be handled again. For this, org-feed.el
79 ;; stores information in a special drawer, FEEDSTATUS, under the heading
80 ;; that received the input of the feed. You should add FEEDSTATUS
81 ;; to your list of drawers in the files that receive feed input:
83 ;; #+DRAWERS: PROPERTIES LOGBOOK FEEDSTATUS
85 ;; Acknowledgments
86 ;; ----------------
88 ;; org-feed.el is based on ideas by Brad Bozarth who implemented a
89 ;; similar mechanism using shell and awk scripts.
91 ;;; Code:
93 (require 'org)
95 (declare-function url-retrieve-synchronously "url" (url))
97 (defgroup org-feed nil
98 "Options concerning RSS feeds as inputs for Org files."
99 :tag "Org ID"
100 :group 'org)
102 ;;;###autoload
103 (defcustom org-feed-alist nil
104 "Alist specifying RSS feeds that should create inputs for Org.
105 Each entry in this list specified an RSS feed tat should be queried
106 to create inbox items in Org. Each entry is a list with the following items:
108 name a custom name for this feed
109 URL the Feed URL
110 file the target Org file where entries should be listed
111 headline the headline under which entries should be listed
113 Additional arguments can be given using keyword-value pairs. Many of these
114 specify functions that receive one or a list of \"entries\" as their single
115 argument. An entry is a property list that describes a feed item. The
116 property list has properties for each field in the item, for example `:title'
117 for the `<title>' field and `:pubDate' for the publication date. In addition,
118 it contains the following properties:
120 `:item-full-text' the full text in the <item> tag
121 `:guid-permalink' t when the guid property is a permalink
123 :filter filter-function
124 A function to select interesting entries in the feed. It gets a single
125 entry as parameter. It should return the entry if it is relevant, or
126 nil if it is not.
128 :template template-string
129 The default action on new items in the feed is to add them as children
130 under the headline for the feed. The template describes how the entry
131 should be formatted. If not given, it defaults to
132 `org-feed-default-template'.
134 :formatter formatter-function
135 Instead of relying on a template, you may specify a function to format
136 the outline node to be inserted as a child. This function gets passed
137 a property list describing a single feed item, and it should return a
138 string that is a properly formatted Org outline node of level 1.
140 :new-handler function
141 If adding new items as children to the outline is not what you want
142 to do with new items, define a handler function that is called with
143 a list of all new items in the feed, each one represented as a property
144 list. The handler should do what needs to be done, and org-feed will
145 mark all items given to this handler as \"handled\", i.e. they will not
146 be passed to this handler again in future readings of the feed.
147 When the handler is called, point will be at the feed headline.
149 :changed-handler function
150 This function gets passed a list of all entries that have been
151 handled before, but are now still in the feed and have *changed*
152 since last handled (as evidenced by a different sha1 hash).
153 When the handler is called, point will be at the feed headline.
155 :group 'org-feed
156 :type '(repeat
157 (list :value ("" "http://" "" "")
158 (string :tag "Name")
159 (string :tag "Feed URL")
160 (file :tag "File for inbox")
161 (string :tag "Headline for inbox")
162 (repeat :inline t
163 (choice
164 (list :inline t :tag "Filter"
165 (const :filter)
166 (symbol :tag "Filter Function"))
167 (list :inline t :tag "Template"
168 (const :template)
169 (string :tag "Template"))
170 (list :inline t :tag "Formatter"
171 (const :formatter)
172 (symbol :tag "Formatter Function"))
173 (list :inline t :tag "New items handler"
174 (const :new-handler)
175 (symbol :tag "Handler Function"))
176 (list :inline t :tag "Changed items"
177 (const :changed-handler)
178 (symbol :tag "Handler Function"))
179 )))))
181 (defcustom org-feed-default-template "\n* %h\n %U\n %description\n %a\n"
182 "Template for the Org node created from RSS feed items.
183 This is just the default, each feed can specify its own.
184 Any fields from the feed item can be interpolated into the template with
185 %name, for example %title, %description, %pubDate etc. In addition, the
186 following special escapes are valid as well:
188 %h the title, or the first line of the description
189 %t the date as a stamp, either from <pubDate> (if present), or
190 the current date.
191 %T date and time
192 %u,%U like %t,%T, but inactive time stamps
193 %a A link, from <guid> if that is a permalink, else from <link>"
194 :group 'org-feed
195 :type '(string :tag "Template"))
197 (defcustom org-feed-save-after-adding t
198 "Non-nil means, save buffer after adding new feed items."
199 :group 'org-feed
200 :type 'boolean)
202 (defcustom org-feed-retrieve-method 'url-retrieve-synchronously
203 "The method to be used to retrieve a feed URL.
204 This can be `curl' or `wget' to call these external programs, or it can be
205 an Emacs Lisp function that will return a buffer containing the content
206 of the file pointed to by the URL."
207 :group 'org-feed
208 :type '(choice
209 (const :tag "Internally with url.el" url-retrieve-synchronously)
210 (const :tag "Externally with curl" curl)
211 (const :tag "Externally with wget" wget)
212 (function :tag "Function")))
214 (defcustom org-feed-before-adding-hook nil
215 "Hook that is run before adding new feed items to a file.
216 You might want to commit the file in its current state to version control,
217 for example."
218 :group 'org-feed
219 :type 'hook)
221 (defcustom org-feed-after-adding-hook nil
222 "Hook that is run after new items have been added to a file.
223 Depending on `org-feed-save-after-adding', the buffer will already
224 have been saved."
225 :group 'org-feed
226 :type 'hook)
228 (defvar org-feed-buffer "*Org feed*"
229 "The buffer used to retrieve a feed.")
231 ;;;###autoload
232 (defun org-feed-update-all ()
233 "Get inbox items from all feeds in `org-feed-alist'."
234 (interactive)
235 (let ((nfeeds (length org-feed-alist))
236 (nnew (apply '+ (mapcar 'org-feed-update org-feed-alist))))
237 (message "%s from %d %s"
238 (cond ((= nnew 0) "No new entries")
239 ((= nnew 1) "1 new entry")
240 (t (format "%d new entries" nnew)))
241 nfeeds
242 (if (= nfeeds 1) "feed" "feeds"))))
244 ;;;###autoload
245 (defun org-feed-update (feed &optional retrieve-only)
246 "Get inbox items from FEED.
247 FEED can be a string with an association in `org-feed-alist', or
248 it can be a list structured like an entry in `org-feed-alist'."
249 (interactive (list (org-completing-read "Feed name: " org-feed-alist)))
250 (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
251 (unless feed
252 (error "No such feed in `org-feed-alist"))
253 (catch 'exit
254 (let ((name (car feed))
255 (url (nth 1 feed))
256 (file (nth 2 feed))
257 (headline (nth 3 feed))
258 (filter (nth 1 (memq :filter feed)))
259 (formatter (nth 1 (memq :formatter feed)))
260 (new-handler (nth 1 (memq :new-handler feed)))
261 (changed-handler (nth 1 (memq :changed-handler feed)))
262 (template (or (nth 1 (memq :template feed))
263 org-feed-default-template))
264 feed-buffer inbox-pos
265 entries old-status status new changed guid-alist e guid olds)
266 (setq feed-buffer (org-feed-get-feed url))
267 (unless (and feed-buffer (bufferp feed-buffer))
268 (error "Cannot get feed %s" name))
269 (when retrieve-only
270 (throw 'exit feed-buffer))
271 (setq entries (org-feed-parse-feed feed-buffer))
272 (ignore-errors (kill-buffer feed-buffer))
273 (save-excursion
274 (save-window-excursion
275 (setq inbox-pos (org-feed-goto-inbox-internal file headline))
276 (setq old-status (org-feed-read-previous-status inbox-pos))
277 ;; Add the "handled" status to the appropriate entries
278 (setq entries (mapcar (lambda (e)
279 (setq e (plist-put e :handled
280 (nth 1 (assoc
281 (plist-get e :guid)
282 old-status)))))
283 entries))
284 ;; Find out which entries are new and which are changed
285 (dolist (e entries)
286 (if (not (plist-get e :handled))
287 (push e new)
288 (setq olds (nth 2 (assoc (plist-get e :guid) old-status)))
289 (if (and olds
290 (not (string= (sha1-string (plist-get e :item-full-text))
291 olds)))
292 (push e changed))))
294 ;; Parse the relevant entries fully
295 (setq new (mapcar 'org-feed-parse-entry new)
296 changed (mapcar 'org-feed-parse-entry changed))
298 ;; Run the filter
299 (when filter
300 (setq new (delq nil (mapcar filter new))
301 changed (delq nil (mapcar filter new))))
303 (when (not (or new changed))
304 (message "No new items in feed %s" name)
305 (throw 'exit 0))
307 ;; Get alist based on guid, to look up entries
308 (setq guid-alist
309 (append
310 (mapcar (lambda (e) (list (plist-get e :guid) e)) new)
311 (mapcar (lambda (e) (list (plist-get e :guid) e)) changed)))
313 ;; Construct the new status
314 (setq status
315 (mapcar
316 (lambda (e)
317 (setq guid (plist-get e :guid))
318 (list guid
319 ;; things count as handled if we handle them now,
320 ;; or if they were handled previously
321 (if (assoc guid guid-alist) t (plist-get e :handled))
322 ;; A hash, to detect changes
323 (sha1-string (plist-get e :item-full-text))))
324 entries))
326 ;; Handle new items in the feed
327 (when new
328 (if new-handler
329 (progn
330 (goto-char inbox-pos)
331 (funcall new-handler new))
332 ;; No custom handler, do the default adding
333 ;; Format the new entries into an alist with GUIDs in the car
334 (setq new-formatted
335 (mapcar
336 (lambda (e) (org-feed-format-entry e template formatter))
337 new)))
339 ;; Insert the new items
340 (org-feed-add-items inbox-pos new-formatted))
342 ;; Handle changed items in the feed
343 (when (and changed-handler changed)
344 (goto-char inbox-pos)
345 (funcall changed-handler changed))
347 ;; Write the new status
348 ;; We do this only now, in case something goes wrong above, so
349 ;; that would would end up with a status that does not reflect
350 ;; which items truely have been handled
351 (org-feed-write-status inbox-pos status)
353 ;; Normalize the visibility of the inbox tree
354 (goto-char inbox-pos)
355 (hide-subtree)
356 (show-children)
357 (org-cycle-hide-drawers 'children)
359 ;; Hooks and messages
360 (when org-feed-save-after-adding (save-buffer))
361 (message "Added %d new item%s from feed %s to file %s, heading %s"
362 (length new) (if (> (length new) 1) "s" "")
363 name
364 (file-name-nondirectory file) headline)
365 (run-hooks 'org-feed-after-adding-hook)
366 (length new))))))
368 ;;;###autoload
369 (defun org-feed-goto-inbox (feed)
370 "Go to the inbox that captures the feed named FEED."
371 (interactive
372 (list (if (= (length org-feed-alist) 1)
373 (car org-feed-alist)
374 (org-completing-read "Feed name: " org-feed-alist))))
375 (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
376 (unless feed
377 (error "No such feed in `org-feed-alist"))
378 (org-feed-goto-inbox-internal (nth 2 feed) (nth 3 feed)))
380 ;;;###autoload
381 (defun org-feed-show-raw-feed (feed)
382 "Show the raw feed buffer of a feed."
383 (interactive
384 (list (if (= (length org-feed-alist) 1)
385 (car org-feed-alist)
386 (org-completing-read "Feed name: " org-feed-alist))))
387 (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
388 (unless feed
389 (error "No such feed in `org-feed-alist"))
390 (switch-to-buffer
391 (org-feed-update feed 'retrieve-only))
392 (goto-char (point-min)))
394 (defun org-feed-goto-inbox-internal (file heading)
395 "Find or create HEADING in FILE.
396 Switch to that buffer, and return the position of that headline."
397 (find-file file)
398 (widen)
399 (goto-char (point-min))
400 (if (re-search-forward
401 (concat "^\\*+[ \t]+" heading "[ \t]*\\(:.*?:[ \t]*\\)?$")
402 nil t)
403 (goto-char (match-beginning 0))
404 (goto-char (point-max))
405 (insert "\n\n* " heading "\n\n")
406 (org-back-to-heading t))
407 (point))
409 (defun org-feed-read-previous-status (pos)
410 "Get the alist of old GUIDs from the entry at POS.
411 This will find the FEEDSTATUS drawer and extract the alist."
412 (save-excursion
413 (goto-char pos)
414 (let ((end (save-excursion (org-end-of-subtree t t))))
415 (if (re-search-forward
416 "^[ \t]*:FEEDSTATUS:[ \t]*\n\\([^\000]*?\\)\n[ \t]*:END:"
417 end t)
418 (read (match-string 1))
419 nil))))
421 (defun org-feed-write-status (pos status)
422 "Write the feed status to the FEEDSTATUS drawer."
423 (save-excursion
424 (goto-char pos)
425 (let ((end (save-excursion (org-end-of-subtree t t)))
426 guid)
427 (if (re-search-forward "^[ \t]*:FEEDSTATUS:[ \t]*\n" end t)
428 (progn
429 (goto-char (match-end 0))
430 (delete-region (point)
431 (save-excursion
432 (and (re-search-forward "^[ \t]*:END:" nil t)
433 (match-beginning 0)))))
434 (outline-next-heading)
435 (insert " :FEEDSTATUS:\n :END:\n")
436 (beginning-of-line 0))
437 (insert (pp-to-string status)))))
439 (defun org-feed-add-items (pos entries)
440 "Add the formatted items to the headline as POS."
441 (let (entry level)
442 (save-excursion
443 (goto-char pos)
444 (unless (looking-at org-complex-heading-regexp)
445 (error "Wrong position"))
446 (setq level (org-get-valid-level (length (match-string 1)) 1))
447 (org-end-of-subtree t t)
448 (skip-chars-backward " \t\n")
449 (beginning-of-line 2)
450 (setq pos (point))
451 (while (setq entry (pop entries))
452 (org-paste-subtree level entry 'yank))
453 (org-mark-ring-push pos))))
455 (defun org-feed-format-entry (entry template formatter)
456 "Format ENTRY so that it can be inserted into an Org file.
457 ENTRY is a property list. This function adds a `:formatted-for-org' property
458 and returns the full property list.
459 If that property is already present, nothing changes."
460 (if formatter
461 (funcall formatter entry)
462 (let (dlines fmt tmp indent time
463 v-h v-t v-T v-u v-U v-a)
464 (setq dlines (org-split-string (or (plist-get entry :description) "???")
465 "\n")
466 v-h (or (plist-get entry :title) (car dlines) "???")
467 time (or (if (plist-get entry :pubDate)
468 (org-read-date t t (plist-get entry :pubDate)))
469 (current-time))
470 v-t (format-time-string (org-time-stamp-format nil nil) time)
471 v-T (format-time-string (org-time-stamp-format t nil) time)
472 v-u (format-time-string (org-time-stamp-format nil t) time)
473 v-U (format-time-string (org-time-stamp-format t t) time)
474 v-a (if (setq tmp (or (and (plist-get entry :guid-permalink)
475 (plist-get entry :guid))
476 (plist-get entry :link)))
477 (concat "[[" tmp "]]\n")
478 ""))
479 (with-temp-buffer
480 (insert template)
481 (goto-char (point-min))
482 (while (re-search-forward "%\\([a-zA-Z]+\\)" nil t)
483 (setq name (match-string 1))
484 (cond
485 ((member name '("h" "t" "T" "u" "U" "a"))
486 (replace-match (symbol-value (intern (concat "v-" name))) t t))
487 ((setq tmp (plist-get entry (intern (concat ":" name))))
488 (save-excursion
489 (save-match-data
490 (beginning-of-line 1)
491 (when (looking-at (concat "^\\([ \t]*\\)%" name "[ \t]*$"))
492 (setq tmp (org-feed-make-indented-block
493 tmp (org-get-indentation))))))
494 (replace-match tmp t t))))
495 (buffer-string)))))
497 (defun org-feed-make-indented-block (s n)
498 "Add indentaton of N spaces to a multiline string S."
499 (if (not (string-match "\n" s))
501 (mapconcat 'identity
502 (org-split-string s "\n")
503 (concat "\n" (make-string n ?\ )))))
505 (defun org-feed-get-feed (url)
506 "Get the RSS feed file at URL and return the buffer."
507 (cond
508 ((eq org-feed-retrieve-method 'url-retrieve-synchronously)
509 (url-retrieve-synchronously url))
510 ((eq org-feed-retrieve-method 'curl)
511 (ignore-errors (kill-buffer org-feed-buffer))
512 (call-process "curl" nil org-feed-buffer nil url)
513 org-feed-buffer)
514 ((eq org-feed-retrieve-method 'wget)
515 (ignore-errors (kill-buffer org-feed-buffer))
516 (call-process "curl" nil org-feed-buffer nil "-q" "-O" "-" url)
517 org-feed-buffer)
518 ((functionp org-feed-retrieve-method)
519 (funcall org-feed-retrieve-method url))))
521 (defun org-feed-parse-feed (buffer)
522 "Parse BUFFER for RS feed entries.
523 Returns a list of entries, with each entry a property list,
524 containing the properties `:guid' and `:item-full-text'."
525 (let (entries beg end item guid entry)
526 (with-current-buffer buffer
527 (widen)
528 (goto-char (point-min))
529 (while (re-search-forward "<item>" nil t)
530 (setq beg (point)
531 end (and (re-search-forward "</item>" nil t)
532 (match-beginning 0)))
533 (setq item (buffer-substring beg end)
534 guid (if (string-match "<guid\\>.*?>\\(.*?\\)</guid>" item)
535 (org-match-string-no-properties 1 item)))
536 (setq entry (list :guid guid :item-full-text item))
537 (push entry entries)
538 (widen)
539 (goto-char end))
540 (nreverse entries))))
542 (defun org-feed-parse-entry (entry)
543 "Parse the `:item-full-text' field for xml tags and create new properties."
544 (with-temp-buffer
545 (insert (plist-get entry :item-full-text))
546 (goto-char (point-min))
547 (while (re-search-forward "<\\([a-zA-Z]+\\>\\).*?>\\([^\000]*?\\)</\\1>"
548 nil t)
549 (setq entry (plist-put entry
550 (intern (concat ":" (match-string 1)))
551 (match-string 2))))
552 (goto-char (point-min))
553 (unless (re-search-forward "isPermaLink[ \t]*=[ \t]*\"false\"" nil t)
554 (setq entry (plist-put entry :guid-permalink t))))
555 entry)
557 (provide 'org-feed)
559 ;; arch-tag: 0929b557-9bc4-47f4-9633-30a12dbb5ae2
561 ;;; org-feed.el ends here