Bugfix: Swapping the last two subtrees in a file.
[org-mode.git] / lisp / org-feed.el
blob4544e85f5575148bfc6f66dc5eb0d46b721857b4
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 :drawer drawer-name
124 The name of the drawer for storing feed information. The default is
125 \"FEEDSTATUS\". Using different drawers for different feeds allows
126 several feeds to target the same inbox heading.
128 :filter filter-function
129 A function to select interesting entries in the feed. It gets a single
130 entry as parameter. It should return the entry if it is relevant, or
131 nil if it is not.
133 :template template-string
134 The default action on new items in the feed is to add them as children
135 under the headline for the feed. The template describes how the entry
136 should be formatted. If not given, it defaults to
137 `org-feed-default-template'.
139 :formatter formatter-function
140 Instead of relying on a template, you may specify a function to format
141 the outline node to be inserted as a child. This function gets passed
142 a property list describing a single feed item, and it should return a
143 string that is a properly formatted Org outline node of level 1.
145 :new-handler function
146 If adding new items as children to the outline is not what you want
147 to do with new items, define a handler function that is called with
148 a list of all new items in the feed, each one represented as a property
149 list. The handler should do what needs to be done, and org-feed will
150 mark all items given to this handler as \"handled\", i.e. they will not
151 be passed to this handler again in future readings of the feed.
152 When the handler is called, point will be at the feed headline.
154 :changed-handler function
155 This function gets passed a list of all entries that have been
156 handled before, but are now still in the feed and have *changed*
157 since last handled (as evidenced by a different sha1 hash).
158 When the handler is called, point will be at the feed headline."
159 :group 'org-feed
160 :type '(repeat
161 (list :value ("" "http://" "" "")
162 (string :tag "Name")
163 (string :tag "Feed URL")
164 (file :tag "File for inbox")
165 (string :tag "Headline for inbox")
166 (repeat :inline t
167 (choice
168 (list :inline t :tag "Filter"
169 (const :filter)
170 (symbol :tag "Filter Function"))
171 (list :inline t :tag "Template"
172 (const :template)
173 (string :tag "Template"))
174 (list :inline t :tag "Formatter"
175 (const :formatter)
176 (symbol :tag "Formatter Function"))
177 (list :inline t :tag "New items handler"
178 (const :new-handler)
179 (symbol :tag "Handler Function"))
180 (list :inline t :tag "Changed items"
181 (const :changed-handler)
182 (symbol :tag "Handler Function"))
183 )))))
185 (defcustom org-feed-drawer "FEEDSTATUS"
186 "The name of the drawer for feed status information.
187 Each feed may also specify its own drawer name using the `:drawer'
188 parameter in `org-feed-alist'.
189 Note that in order to make these drawers behave like drawers, they must
190 be added to the variable `org-drawers' or configured with a #+DRAWERS
191 line."
192 :group 'org-feed
193 :type '(string :tag "Drawer Name"))
195 (defcustom org-feed-default-template "\n* %h\n %U\n %description\n %a\n"
196 "Template for the Org node created from RSS feed items.
197 This is just the default, each feed can specify its own.
198 Any fields from the feed item can be interpolated into the template with
199 %name, for example %title, %description, %pubDate etc. In addition, the
200 following special escapes are valid as well:
202 %h the title, or the first line of the description
203 %t the date as a stamp, either from <pubDate> (if present), or
204 the current date.
205 %T date and time
206 %u,%U like %t,%T, but inactive time stamps
207 %a A link, from <guid> if that is a permalink, else from <link>"
208 :group 'org-feed
209 :type '(string :tag "Template"))
211 (defcustom org-feed-save-after-adding t
212 "Non-nil means, save buffer after adding new feed items."
213 :group 'org-feed
214 :type 'boolean)
216 (defcustom org-feed-retrieve-method 'url-retrieve-synchronously
217 "The method to be used to retrieve a feed URL.
218 This can be `curl' or `wget' to call these external programs, or it can be
219 an Emacs Lisp function that will return a buffer containing the content
220 of the file pointed to by the URL."
221 :group 'org-feed
222 :type '(choice
223 (const :tag "Internally with url.el" url-retrieve-synchronously)
224 (const :tag "Externally with curl" curl)
225 (const :tag "Externally with wget" wget)
226 (function :tag "Function")))
228 (defcustom org-feed-before-adding-hook nil
229 "Hook that is run before adding new feed items to a file.
230 You might want to commit the file in its current state to version control,
231 for example."
232 :group 'org-feed
233 :type 'hook)
235 (defcustom org-feed-after-adding-hook nil
236 "Hook that is run after new items have been added to a file.
237 Depending on `org-feed-save-after-adding', the buffer will already
238 have been saved."
239 :group 'org-feed
240 :type 'hook)
242 (defvar org-feed-buffer "*Org feed*"
243 "The buffer used to retrieve a feed.")
245 ;;;###autoload
246 (defun org-feed-update-all ()
247 "Get inbox items from all feeds in `org-feed-alist'."
248 (interactive)
249 (let ((nfeeds (length org-feed-alist))
250 (nnew (apply '+ (mapcar 'org-feed-update org-feed-alist))))
251 (message "%s from %d %s"
252 (cond ((= nnew 0) "No new entries")
253 ((= nnew 1) "1 new entry")
254 (t (format "%d new entries" nnew)))
255 nfeeds
256 (if (= nfeeds 1) "feed" "feeds"))))
258 ;;;###autoload
259 (defun org-feed-update (feed &optional retrieve-only)
260 "Get inbox items from FEED.
261 FEED can be a string with an association in `org-feed-alist', or
262 it can be a list structured like an entry in `org-feed-alist'."
263 (interactive (list (org-completing-read "Feed name: " org-feed-alist)))
264 (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
265 (unless feed
266 (error "No such feed in `org-feed-alist"))
267 (catch 'exit
268 (let ((name (car feed))
269 (url (nth 1 feed))
270 (file (nth 2 feed))
271 (headline (nth 3 feed))
272 (filter (nth 1 (memq :filter feed)))
273 (formatter (nth 1 (memq :formatter feed)))
274 (new-handler (nth 1 (memq :new-handler feed)))
275 (changed-handler (nth 1 (memq :changed-handler feed)))
276 (template (or (nth 1 (memq :template feed))
277 org-feed-default-template))
278 (drawer (or (nth 1 (memq :drawer feed))
279 org-feed-drawer))
280 feed-buffer inbox-pos
281 entries old-status status new changed guid-alist e guid olds)
282 (setq feed-buffer (org-feed-get-feed url))
283 (unless (and feed-buffer (bufferp feed-buffer))
284 (error "Cannot get feed %s" name))
285 (when retrieve-only
286 (throw 'exit feed-buffer))
287 (setq entries (org-feed-parse-feed feed-buffer))
288 (ignore-errors (kill-buffer feed-buffer))
289 (save-excursion
290 (save-window-excursion
291 (setq inbox-pos (org-feed-goto-inbox-internal file headline))
292 (setq old-status (org-feed-read-previous-status inbox-pos drawer))
293 ;; Add the "handled" status to the appropriate entries
294 (setq entries (mapcar (lambda (e)
295 (setq e (plist-put e :handled
296 (nth 1 (assoc
297 (plist-get e :guid)
298 old-status)))))
299 entries))
300 ;; Find out which entries are new and which are changed
301 (dolist (e entries)
302 (if (not (plist-get e :handled))
303 (push e new)
304 (setq olds (nth 2 (assoc (plist-get e :guid) old-status)))
305 (if (and olds
306 (not (string= (sha1-string (plist-get e :item-full-text))
307 olds)))
308 (push e changed))))
310 ;; Parse the relevant entries fully
311 (setq new (mapcar 'org-feed-parse-entry new)
312 changed (mapcar 'org-feed-parse-entry changed))
314 ;; Run the filter
315 (when filter
316 (setq new (delq nil (mapcar filter new))
317 changed (delq nil (mapcar filter new))))
319 (when (not (or new changed))
320 (message "No new items in feed %s" name)
321 (throw 'exit 0))
323 ;; Get alist based on guid, to look up entries
324 (setq guid-alist
325 (append
326 (mapcar (lambda (e) (list (plist-get e :guid) e)) new)
327 (mapcar (lambda (e) (list (plist-get e :guid) e)) changed)))
329 ;; Construct the new status
330 (setq status
331 (mapcar
332 (lambda (e)
333 (setq guid (plist-get e :guid))
334 (list guid
335 ;; things count as handled if we handle them now,
336 ;; or if they were handled previously
337 (if (assoc guid guid-alist) t (plist-get e :handled))
338 ;; A hash, to detect changes
339 (sha1-string (plist-get e :item-full-text))))
340 entries))
342 ;; Handle new items in the feed
343 (when new
344 (if new-handler
345 (progn
346 (goto-char inbox-pos)
347 (funcall new-handler new))
348 ;; No custom handler, do the default adding
349 ;; Format the new entries into an alist with GUIDs in the car
350 (setq new-formatted
351 (mapcar
352 (lambda (e) (org-feed-format-entry e template formatter))
353 new)))
355 ;; Insert the new items
356 (org-feed-add-items inbox-pos new-formatted))
358 ;; Handle changed items in the feed
359 (when (and changed-handler changed)
360 (goto-char inbox-pos)
361 (funcall changed-handler changed))
363 ;; Write the new status
364 ;; We do this only now, in case something goes wrong above, so
365 ;; that would would end up with a status that does not reflect
366 ;; which items truely have been handled
367 (org-feed-write-status inbox-pos drawer status)
369 ;; Normalize the visibility of the inbox tree
370 (goto-char inbox-pos)
371 (hide-subtree)
372 (show-children)
373 (org-cycle-hide-drawers 'children)
375 ;; Hooks and messages
376 (when org-feed-save-after-adding (save-buffer))
377 (message "Added %d new item%s from feed %s to file %s, heading %s"
378 (length new) (if (> (length new) 1) "s" "")
379 name
380 (file-name-nondirectory file) headline)
381 (run-hooks 'org-feed-after-adding-hook)
382 (length new))))))
384 ;;;###autoload
385 (defun org-feed-goto-inbox (feed)
386 "Go to the inbox that captures the feed named FEED."
387 (interactive
388 (list (if (= (length org-feed-alist) 1)
389 (car org-feed-alist)
390 (org-completing-read "Feed name: " org-feed-alist))))
391 (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
392 (unless feed
393 (error "No such feed in `org-feed-alist"))
394 (org-feed-goto-inbox-internal (nth 2 feed) (nth 3 feed)))
396 ;;;###autoload
397 (defun org-feed-show-raw-feed (feed)
398 "Show the raw feed buffer of a feed."
399 (interactive
400 (list (if (= (length org-feed-alist) 1)
401 (car org-feed-alist)
402 (org-completing-read "Feed name: " org-feed-alist))))
403 (if (stringp feed) (setq feed (assoc feed org-feed-alist)))
404 (unless feed
405 (error "No such feed in `org-feed-alist"))
406 (switch-to-buffer
407 (org-feed-update feed 'retrieve-only))
408 (goto-char (point-min)))
410 (defun org-feed-goto-inbox-internal (file heading)
411 "Find or create HEADING in FILE.
412 Switch to that buffer, and return the position of that headline."
413 (find-file file)
414 (widen)
415 (goto-char (point-min))
416 (if (re-search-forward
417 (concat "^\\*+[ \t]+" heading "[ \t]*\\(:.*?:[ \t]*\\)?$")
418 nil t)
419 (goto-char (match-beginning 0))
420 (goto-char (point-max))
421 (insert "\n\n* " heading "\n\n")
422 (org-back-to-heading t))
423 (point))
425 (defun org-feed-read-previous-status (pos drawer)
426 "Get the alist of old GUIDs from the entry at POS.
427 This will find DRAWER and extract the alist."
428 (save-excursion
429 (goto-char pos)
430 (let ((end (save-excursion (org-end-of-subtree t t))))
431 (if (re-search-forward
432 (concat "^[ \t]*:" drawer ":[ \t]*\n\\([^\000]*?\\)\n[ \t]*:END:")
433 end t)
434 (read (match-string 1))
435 nil))))
437 (defun org-feed-write-status (pos drawer status)
438 "Write the feed STATUS to DRAWER in entry at POS."
439 (save-excursion
440 (goto-char pos)
441 (let ((end (save-excursion (org-end-of-subtree t t)))
442 guid)
443 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*\n")
444 end t)
445 (progn
446 (goto-char (match-end 0))
447 (delete-region (point)
448 (save-excursion
449 (and (re-search-forward "^[ \t]*:END:" nil t)
450 (match-beginning 0)))))
451 (outline-next-heading)
452 (insert " :" drawer ":\n :END:\n")
453 (beginning-of-line 0))
454 (insert (pp-to-string status)))))
456 (defun org-feed-add-items (pos entries)
457 "Add the formatted items to the headline as POS."
458 (let (entry level)
459 (save-excursion
460 (goto-char pos)
461 (unless (looking-at org-complex-heading-regexp)
462 (error "Wrong position"))
463 (setq level (org-get-valid-level (length (match-string 1)) 1))
464 (org-end-of-subtree t t)
465 (skip-chars-backward " \t\n")
466 (beginning-of-line 2)
467 (setq pos (point))
468 (while (setq entry (pop entries))
469 (org-paste-subtree level entry 'yank))
470 (org-mark-ring-push pos))))
472 (defun org-feed-format-entry (entry template formatter)
473 "Format ENTRY so that it can be inserted into an Org file.
474 ENTRY is a property list. This function adds a `:formatted-for-org' property
475 and returns the full property list.
476 If that property is already present, nothing changes."
477 (if formatter
478 (funcall formatter entry)
479 (let (dlines fmt tmp indent time
480 v-h v-t v-T v-u v-U v-a)
481 (setq dlines (org-split-string (or (plist-get entry :description) "???")
482 "\n")
483 v-h (or (plist-get entry :title) (car dlines) "???")
484 time (or (if (plist-get entry :pubDate)
485 (org-read-date t t (plist-get entry :pubDate)))
486 (current-time))
487 v-t (format-time-string (org-time-stamp-format nil nil) time)
488 v-T (format-time-string (org-time-stamp-format t nil) time)
489 v-u (format-time-string (org-time-stamp-format nil t) time)
490 v-U (format-time-string (org-time-stamp-format t t) time)
491 v-a (if (setq tmp (or (and (plist-get entry :guid-permalink)
492 (plist-get entry :guid))
493 (plist-get entry :link)))
494 (concat "[[" tmp "]]\n")
495 ""))
496 (with-temp-buffer
497 (insert template)
498 (goto-char (point-min))
499 (while (re-search-forward "%\\([a-zA-Z]+\\)" nil t)
500 (setq name (match-string 1))
501 (cond
502 ((member name '("h" "t" "T" "u" "U" "a"))
503 (replace-match (symbol-value (intern (concat "v-" name))) t t))
504 ((setq tmp (plist-get entry (intern (concat ":" name))))
505 (save-excursion
506 (save-match-data
507 (beginning-of-line 1)
508 (when (looking-at (concat "^\\([ \t]*\\)%" name "[ \t]*$"))
509 (setq tmp (org-feed-make-indented-block
510 tmp (org-get-indentation))))))
511 (replace-match tmp t t))))
512 (buffer-string)))))
514 (defun org-feed-make-indented-block (s n)
515 "Add indentaton of N spaces to a multiline string S."
516 (if (not (string-match "\n" s))
518 (mapconcat 'identity
519 (org-split-string s "\n")
520 (concat "\n" (make-string n ?\ )))))
522 (defun org-feed-get-feed (url)
523 "Get the RSS feed file at URL and return the buffer."
524 (cond
525 ((eq org-feed-retrieve-method 'url-retrieve-synchronously)
526 (url-retrieve-synchronously url))
527 ((eq org-feed-retrieve-method 'curl)
528 (ignore-errors (kill-buffer org-feed-buffer))
529 (call-process "curl" nil org-feed-buffer nil url)
530 org-feed-buffer)
531 ((eq org-feed-retrieve-method 'wget)
532 (ignore-errors (kill-buffer org-feed-buffer))
533 (call-process "curl" nil org-feed-buffer nil "-q" "-O" "-" url)
534 org-feed-buffer)
535 ((functionp org-feed-retrieve-method)
536 (funcall org-feed-retrieve-method url))))
538 (defun org-feed-parse-feed (buffer)
539 "Parse BUFFER for RS feed entries.
540 Returns a list of entries, with each entry a property list,
541 containing the properties `:guid' and `:item-full-text'."
542 (let (entries beg end item guid entry)
543 (with-current-buffer buffer
544 (widen)
545 (goto-char (point-min))
546 (while (re-search-forward "<item>" nil t)
547 (setq beg (point)
548 end (and (re-search-forward "</item>" nil t)
549 (match-beginning 0)))
550 (setq item (buffer-substring beg end)
551 guid (if (string-match "<guid\\>.*?>\\(.*?\\)</guid>" item)
552 (org-match-string-no-properties 1 item)))
553 (setq entry (list :guid guid :item-full-text item))
554 (push entry entries)
555 (widen)
556 (goto-char end))
557 (nreverse entries))))
559 (defun org-feed-parse-entry (entry)
560 "Parse the `:item-full-text' field for xml tags and create new properties."
561 (with-temp-buffer
562 (insert (plist-get entry :item-full-text))
563 (goto-char (point-min))
564 (while (re-search-forward "<\\([a-zA-Z]+\\>\\).*?>\\([^\000]*?\\)</\\1>"
565 nil t)
566 (setq entry (plist-put entry
567 (intern (concat ":" (match-string 1)))
568 (match-string 2))))
569 (goto-char (point-min))
570 (unless (re-search-forward "isPermaLink[ \t]*=[ \t]*\"false\"" nil t)
571 (setq entry (plist-put entry :guid-permalink t))))
572 entry)
574 (provide 'org-feed)
576 ;; arch-tag: 0929b557-9bc4-47f4-9633-30a12dbb5ae2
578 ;;; org-feed.el ends here