t-gnus-6_15-quimby: New branch for developing and synchronizing with Oort Gnus.
[elisp/gnus.git-] / lisp / nnweb.el
1 ;;; nnweb.el --- retrieving articles via web search engines
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Note: You need to have `url' and `w3' installed for this
28 ;; backend to work.
29
30 ;;; Code:
31
32 (eval-when-compile (require 'cl))
33 (eval-when-compile (require 'gnus-clfns))
34
35 (require 'nnoo)
36 (require 'message)
37 (require 'gnus-util)
38 (require 'gnus)
39 (require 'nnmail)
40 (eval-when-compile
41   (ignore-errors
42     (require 'w3)
43     (require 'url)
44     (require 'w3-forms)))
45
46 ;; Report failure to find w3 at load time if appropriate.
47 (unless noninteractive
48   (eval '(progn
49            (require 'w3)
50            (require 'url)
51            (require 'w3-forms))))
52
53 (nnoo-declare nnweb)
54
55 (defvoo nnweb-directory (nnheader-concat gnus-directory "nnweb/")
56   "Where nnweb will save its files.")
57
58 (defvoo nnweb-type 'dejanews
59   "What search engine type is being used.
60 Valid types include `dejanews', `dejanewsold', `reference',
61 and `altavista'.")
62
63 (defvar nnweb-type-definition
64   '((dejanews
65      (article . ignore)
66      (id . "http://search.dejanews.com/msgid.xp?MID=%s&fmt=text")
67      (map . nnweb-dejanews-create-mapping)
68      (search . nnweb-dejanews-search)
69      (address . "http://www.deja.com/=dnc/qs.xp")
70      (identifier . nnweb-dejanews-identity))
71     (dejanewsold
72      (article . ignore)
73      (map . nnweb-dejanews-create-mapping)
74      (search . nnweb-dejanewsold-search)
75      (address . "http://www.deja.com/dnquery.xp")
76      (identifier . nnweb-dejanews-identity))
77     (reference
78      (article . nnweb-reference-wash-article)
79      (map . nnweb-reference-create-mapping)
80      (search . nnweb-reference-search)
81      (address . "http://www.reference.com/cgi-bin/pn/go")
82      (identifier . identity))
83     (altavista
84      (article . nnweb-altavista-wash-article)
85      (map . nnweb-altavista-create-mapping)
86      (search . nnweb-altavista-search)
87      (address . "http://www.altavista.digital.com/cgi-bin/query")
88      (id . "/cgi-bin/news?id@%s")
89      (identifier . identity)))
90   "Type-definition alist.")
91
92 (defvoo nnweb-search nil
93   "Search string to feed to DejaNews.")
94
95 (defvoo nnweb-max-hits 999
96   "Maximum number of hits to display.")
97
98 (defvoo nnweb-ephemeral-p nil
99   "Whether this nnweb server is ephemeral.")
100
101 ;;; Internal variables
102
103 (defvoo nnweb-articles nil)
104 (defvoo nnweb-buffer nil)
105 (defvoo nnweb-group-alist nil)
106 (defvoo nnweb-group nil)
107 (defvoo nnweb-hashtb nil)
108
109 ;;; Interface functions
110
111 (nnoo-define-basics nnweb)
112
113 (deffoo nnweb-retrieve-headers (articles &optional group server fetch-old)
114   (nnweb-possibly-change-server group server)
115   (save-excursion
116     (set-buffer nntp-server-buffer)
117     (erase-buffer)
118     (let (article header)
119       (mm-with-unibyte-current-buffer
120         (while (setq article (pop articles))
121           (when (setq header (cadr (assq article nnweb-articles)))
122             (nnheader-insert-nov header))))
123       'nov)))
124
125 (deffoo nnweb-request-scan (&optional group server)
126   (nnweb-possibly-change-server group server)
127   (funcall (nnweb-definition 'map))
128   (unless nnweb-ephemeral-p
129     (nnweb-write-active)
130     (nnweb-write-overview group)))
131
132 (deffoo nnweb-request-group (group &optional server dont-check)
133   (nnweb-possibly-change-server nil server)
134   (when (and group
135              (not (equal group nnweb-group))
136              (not nnweb-ephemeral-p))
137     (let ((info (assoc group nnweb-group-alist)))
138       (when info
139         (setq nnweb-group group)
140         (setq nnweb-type (nth 2 info))
141         (setq nnweb-search (nth 3 info))
142         (unless dont-check
143           (nnweb-read-overview group)))))
144   (cond
145    ((not nnweb-articles)
146     (nnheader-report 'nnweb "No matching articles"))
147    (t
148     (let ((active (if nnweb-ephemeral-p
149                       (cons (caar nnweb-articles)
150                             (caar (last nnweb-articles)))
151                     (cadr (assoc group nnweb-group-alist)))))
152       (nnheader-report 'nnweb "Opened group %s" group)
153       (nnheader-insert
154        "211 %d %d %d %s\n" (length nnweb-articles)
155        (car active) (cdr active) group)))))
156
157 (deffoo nnweb-close-group (group &optional server)
158   (nnweb-possibly-change-server group server)
159   (when (gnus-buffer-live-p nnweb-buffer)
160     (save-excursion
161       (set-buffer nnweb-buffer)
162       (set-buffer-modified-p nil)
163       (kill-buffer nnweb-buffer)))
164   t)
165
166 (deffoo nnweb-request-article (article &optional group server buffer)
167   (nnweb-possibly-change-server group server)
168   (save-excursion
169     (set-buffer (or buffer nntp-server-buffer))
170     (let* ((header (cadr (assq article nnweb-articles)))
171            (url (and header (mail-header-xref header))))
172       (when (or (and url
173                      (mm-with-unibyte-current-buffer
174                        (nnweb-fetch-url url)))
175                 (and (stringp article)
176                      (nnweb-definition 'id t)
177                      (let ((fetch (nnweb-definition 'id))
178                            art)
179                        (when (string-match "^<\\(.*\\)>$" article)
180                          (setq art (match-string 1 article)))
181                        (and fetch
182                             art
183                             (mm-with-unibyte-current-buffer
184                               (nnweb-fetch-url
185                                (format fetch article)))))))
186         (unless nnheader-callback-function
187           (funcall (nnweb-definition 'article))
188           (nnweb-decode-entities))
189         (nnheader-report 'nnweb "Fetched article %s" article)
190         (cons group (and (numberp article) article))))))
191
192 (deffoo nnweb-close-server (&optional server)
193   (when (and (nnweb-server-opened server)
194              (gnus-buffer-live-p nnweb-buffer))
195     (save-excursion
196       (set-buffer nnweb-buffer)
197       (set-buffer-modified-p nil)
198       (kill-buffer nnweb-buffer)))
199   (nnoo-close-server 'nnweb server))
200
201 (deffoo nnweb-request-list (&optional server)
202   (nnweb-possibly-change-server nil server)
203   (save-excursion
204     (set-buffer nntp-server-buffer)
205     (nnmail-generate-active nnweb-group-alist)
206     t))
207
208 (deffoo nnweb-request-update-info (group info &optional server)
209   (nnweb-possibly-change-server group server))
210
211 (deffoo nnweb-asynchronous-p ()
212   t)
213
214 (deffoo nnweb-request-create-group (group &optional server args)
215   (nnweb-possibly-change-server nil server)
216   (nnweb-request-delete-group group)
217   (push `(,group ,(cons 1 0) ,@args) nnweb-group-alist)
218   (nnweb-write-active)
219   t)
220
221 (deffoo nnweb-request-delete-group (group &optional force server)
222   (nnweb-possibly-change-server group server)
223   (gnus-pull group nnweb-group-alist t)
224   (nnweb-write-active)
225   (gnus-delete-file (nnweb-overview-file group))
226   t)
227
228 (nnoo-define-skeleton nnweb)
229
230 ;;; Internal functions
231
232 (defun nnweb-read-overview (group)
233   "Read the overview of GROUP and build the map."
234   (when (file-exists-p (nnweb-overview-file group))
235     (mm-with-unibyte-buffer
236       (nnheader-insert-file-contents (nnweb-overview-file group))
237       (goto-char (point-min))
238       (let (header)
239         (while (not (eobp))
240           (setq header (nnheader-parse-nov))
241           (forward-line 1)
242           (push (list (mail-header-number header)
243                       header (mail-header-xref header))
244                 nnweb-articles)
245           (nnweb-set-hashtb header (car nnweb-articles)))))))
246
247 (defun nnweb-write-overview (group)
248   "Write the overview file for GROUP."
249   (with-temp-file (nnweb-overview-file group)
250     (let ((articles nnweb-articles))
251       (while articles
252         (nnheader-insert-nov (cadr (pop articles)))))))
253
254 (defun nnweb-set-hashtb (header data)
255   (gnus-sethash (nnweb-identifier (mail-header-xref header))
256                 data nnweb-hashtb))
257
258 (defun nnweb-get-hashtb (url)
259   (gnus-gethash (nnweb-identifier url) nnweb-hashtb))
260
261 (defun nnweb-identifier (ident)
262   (funcall (nnweb-definition 'identifier) ident))
263
264 (defun nnweb-overview-file (group)
265   "Return the name of the overview file of GROUP."
266   (nnheader-concat nnweb-directory group ".overview"))
267
268 (defun nnweb-write-active ()
269   "Save the active file."
270   (gnus-make-directory nnweb-directory)
271   (with-temp-file (nnheader-concat nnweb-directory "active")
272     (prin1 `(setq nnweb-group-alist ',nnweb-group-alist) (current-buffer))))
273
274 (defun nnweb-read-active ()
275   "Read the active file."
276   (load (nnheader-concat nnweb-directory "active") t t t))
277
278 (defun nnweb-definition (type &optional noerror)
279   "Return the definition of TYPE."
280   (let ((def (cdr (assq type (assq nnweb-type nnweb-type-definition)))))
281     (when (and (not def)
282                (not noerror))
283       (error "Undefined definition %s" type))
284     def))
285
286 (defun nnweb-possibly-change-server (&optional group server)
287   (nnweb-init server)
288   (when server
289     (unless (nnweb-server-opened server)
290       (nnweb-open-server server)))
291   (unless nnweb-group-alist
292     (nnweb-read-active))
293   (when group
294     (when (and (not nnweb-ephemeral-p)
295                (not (equal group nnweb-group)))
296       (setq nnweb-hashtb (gnus-make-hashtable 4095))
297       (nnweb-request-group group nil t))))
298
299 (defun nnweb-init (server)
300   "Initialize buffers and such."
301   (unless (gnus-buffer-live-p nnweb-buffer)
302     (setq nnweb-buffer
303           (save-excursion
304             (mm-with-unibyte
305               (nnheader-set-temp-buffer
306                (format " *nnweb %s %s %s*"
307                        nnweb-type nnweb-search server))
308               (current-buffer))))))
309
310 (defun nnweb-fetch-url (url)
311   (let (buf)
312     (save-excursion
313       (if (not nnheader-callback-function)
314           (progn
315             (with-temp-buffer
316               (mm-enable-multibyte)
317               (let ((coding-system-for-read 'binary)
318                     (coding-system-for-write 'binary)
319                     (input-coding-system 'binary)
320                     (output-coding-system 'binary)
321                     (default-process-coding-system 'binary))
322                 (nnweb-insert url))
323               (setq buf (buffer-string)))
324             (erase-buffer)
325             (insert buf)
326             t)
327         (nnweb-url-retrieve-asynch
328          url 'nnweb-callback (current-buffer) nnheader-callback-function)
329         t))))
330
331 (defun nnweb-callback (buffer callback)
332   (when (gnus-buffer-live-p url-working-buffer)
333     (save-excursion
334       (set-buffer url-working-buffer)
335       (funcall (nnweb-definition 'article))
336       (nnweb-decode-entities)
337       (set-buffer buffer)
338       (goto-char (point-max))
339       (insert-buffer-substring url-working-buffer))
340     (funcall callback t)
341     (gnus-kill-buffer url-working-buffer)))
342
343 (defun nnweb-url-retrieve-asynch (url callback &rest data)
344   (let ((url-request-method "GET")
345         (old-asynch url-be-asynchronous)
346         (url-request-data nil)
347         (url-request-extra-headers nil)
348         (url-working-buffer (generate-new-buffer-name " *nnweb*")))
349     (setq-default url-be-asynchronous t)
350     (save-excursion
351       (set-buffer (get-buffer-create url-working-buffer))
352       (setq url-current-callback-data data
353             url-be-asynchronous t
354             url-current-callback-func callback)
355       (url-retrieve url nil))
356     (setq-default url-be-asynchronous old-asynch)))
357
358 (if (fboundp 'url-retrieve-synchronously)
359     (defun nnweb-url-retrieve-asynch (url callback &rest data)
360       (url-retrieve url callback data)))
361
362 ;;;
363 ;;; DejaNews functions.
364 ;;;
365
366 (defun nnweb-dejanews-create-mapping ()
367   "Perform the search and create an number-to-url alist."
368   (save-excursion
369     (set-buffer nnweb-buffer)
370     (erase-buffer)
371     (when (funcall (nnweb-definition 'search) nnweb-search)
372       (let ((i 0)
373             (more t)
374             (case-fold-search t)
375             (active (or (cadr (assoc nnweb-group nnweb-group-alist))
376                         (cons 1 0)))
377             subject date from
378             map url parse a table group text)
379         (while more
380           ;; Go through all the article hits on this page.
381           (goto-char (point-min))
382           (setq parse (w3-parse-buffer (current-buffer))
383                 table (nth 1 (nnweb-parse-find-all 'table parse)))
384           (dolist (row (nth 2 (car (nth 2 table))))
385             (setq a (nnweb-parse-find 'a row)
386                   url (cdr (assq 'href (nth 1 a)))
387                   text (nreverse (nnweb-text row)))
388             (when a
389               (setq subject (nth 4 text)
390                     group (nth 2 text)
391                     date (nth 1 text)
392                     from (nth 0 text))
393               (if (string-match "\\([0-9]+\\)/\\([0-9]+\\)/\\([0-9]+\\)" date)
394                   (setq date (format "%s %s 00:00:00 %s"
395                                      (car (rassq (string-to-number
396                                                   (match-string 2 date))
397                                                  parse-time-months))
398                                      (match-string 3 date) 
399                                      (match-string 1 date)))
400                 (setq date "Jan 1 00:00:00 0000"))
401               (incf i)
402               (setq url (concat url "&fmt=text"))
403               (when (string-match "&context=[^&]+" url)
404                 (setq url (replace-match "" t t url)))
405               (unless (nnweb-get-hashtb url)
406                 (push
407                  (list
408                   (incf (cdr active))
409                   (make-full-mail-header
410                    (cdr active) (concat subject " (" group ")") from date
411                    (concat "<" (nnweb-identifier url) "@dejanews>")
412                    nil 0 0 url))
413                  map)
414                 (nnweb-set-hashtb (cadar map) (car map)))))
415           ;; See whether there is a "Get next 20 hits" button here.
416           (goto-char (point-min))
417           (if (or (not (re-search-forward
418                         "HREF=\"\\([^\"]+\\)\"[<>b]+Next result" nil t))
419                   (>= i nnweb-max-hits))
420               (setq more nil)
421             ;; Yup -- fetch it.
422             (setq more (match-string 1))
423             (erase-buffer)
424             (url-insert-file-contents more)))
425         ;; Return the articles in the right order.
426         (setq nnweb-articles
427               (sort (nconc nnweb-articles map) 'car-less-than-car))))))
428
429 (defun nnweb-dejanews-search (search)
430   (nnweb-insert
431    (concat
432     (nnweb-definition 'address)
433     "?"
434     (nnweb-encode-www-form-urlencoded
435      `(("ST" . "PS")
436        ("svcclass" . "dnyr")
437        ("QRY" . ,search)
438        ("defaultOp" . "AND")
439        ("DBS" . "1")
440        ("OP" . "dnquery.xp")
441        ("LNG" . "ALL")
442        ("maxhits" . "100")
443        ("threaded" . "0")
444        ("format" . "verbose2")
445        ("showsort" . "date")
446        ("agesign" . "1")
447        ("ageweight" . "1")))))
448   t)
449
450 (defun nnweb-dejanewsold-search (search)
451   (nnweb-fetch-form
452    (nnweb-definition 'address)
453    `(("query" . ,search)
454      ("defaultOp" . "AND")
455      ("svcclass" . "dnold")
456      ("maxhits" . "100")
457      ("format" . "verbose2")
458      ("threaded" . "0")
459      ("showsort" . "date")
460      ("agesign" . "1")
461      ("ageweight" . "1")))
462   t)
463
464 (defun nnweb-dejanews-identity (url)
465   "Return an unique identifier based on URL."
466   (if (string-match "AN=\\([0-9]+\\)" url)
467       (match-string 1 url)
468     url))
469
470 ;;;
471 ;;; InReference
472 ;;;
473
474 (defun nnweb-reference-create-mapping ()
475   "Perform the search and create an number-to-url alist."
476   (save-excursion
477     (set-buffer nnweb-buffer)
478     (erase-buffer)
479     (when (funcall (nnweb-definition 'search) nnweb-search)
480       (let ((i 0)
481             (more t)
482             (case-fold-search t)
483             (active (or (cadr (assoc nnweb-group nnweb-group-alist))
484                         (cons 1 0)))
485             Subject Score Date Newsgroups From Message-ID
486             map url)
487         (while more
488           ;; Go through all the article hits on this page.
489           (goto-char (point-min))
490           (search-forward "</pre><hr>" nil t)
491           (delete-region (point-min) (point))
492           (goto-char (point-min))
493           (while (re-search-forward "^ +[0-9]+\\." nil t)
494             (narrow-to-region
495              (point)
496              (if (re-search-forward "^$" nil t)
497                  (match-beginning 0)
498                (point-max)))
499             (goto-char (point-min))
500             (when (looking-at ".*href=\"\\([^\"]+\\)\"")
501               (setq url (match-string 1)))
502             (nnweb-remove-markup)
503             (goto-char (point-min))
504             (while (search-forward "\t" nil t)
505               (replace-match " "))
506             (goto-char (point-min))
507             (while (re-search-forward "^\\([^:]+\\): \\(.*\\)$" nil t)
508               (set (intern (match-string 1)) (match-string 2)))
509             (widen)
510             (search-forward "</pre>" nil t)
511             (incf i)
512             (unless (nnweb-get-hashtb url)
513               (push
514                (list
515                 (incf (cdr active))
516                 (make-full-mail-header
517                  (cdr active) (concat  "(" Newsgroups ") " Subject) From Date
518                  Message-ID
519                  nil 0 (string-to-int Score) url))
520                map)
521               (nnweb-set-hashtb (cadar map) (car map))))
522           (setq more nil))
523         ;; Return the articles in the right order.
524         (setq nnweb-articles
525               (sort (nconc nnweb-articles map) 'car-less-than-car))))))
526
527 (defun nnweb-reference-wash-article ()
528   (let ((case-fold-search t))
529     (goto-char (point-min))
530     (re-search-forward "^</center><hr>" nil t)
531     (delete-region (point-min) (point))
532     (search-forward "<pre>" nil t)
533     (forward-line -1)
534     (let ((body (point-marker)))
535       (search-forward "</pre>" nil t)
536       (delete-region (point) (point-max))
537       (nnweb-remove-markup)
538       (goto-char (point-min))
539       (while (looking-at " *$")
540         (gnus-delete-line))
541       (narrow-to-region (point-min) body)
542       (while (and (re-search-forward "^$" nil t)
543                   (not (eobp)))
544         (gnus-delete-line))
545       (goto-char (point-min))
546       (while (looking-at "\\(^[^ ]+:\\) *")
547         (replace-match "\\1 " t)
548         (forward-line 1))
549       (goto-char (point-min))
550       (when (re-search-forward "^References:" nil t)
551         (narrow-to-region
552          (point) (if (re-search-forward "^$\\|^[^:]+:" nil t)
553                      (match-beginning 0)
554                    (point-max)))
555         (goto-char (point-min))
556         (while (not (eobp))
557           (unless (looking-at "References")
558             (insert "\t")
559             (forward-line 1)))
560         (goto-char (point-min))
561         (while (search-forward "," nil t)
562           (replace-match " " t t)))
563       (widen)
564       (set-marker body nil))))
565
566 (defun nnweb-reference-search (search)
567   (url-insert-file-contents
568    (concat
569     (nnweb-definition 'address)
570     "?"
571     (nnweb-encode-www-form-urlencoded
572      `(("search" . "advanced")
573        ("querytext" . ,search)
574        ("subj" . "")
575        ("name" . "")
576        ("login" . "")
577        ("host" . "")
578        ("organization" . "")
579        ("groups" . "")
580        ("keywords" . "")
581        ("choice" . "Search")
582        ("startmonth" . "Jul")
583        ("startday" . "25")
584        ("startyear" . "1996")
585        ("endmonth" . "Aug")
586        ("endday" . "24")
587        ("endyear" . "1996")
588        ("mode" . "Quick")
589        ("verbosity" . "Verbose")
590        ("ranking" . "Relevance")
591        ("first" . "1")
592        ("last" . "25")
593        ("score" . "50")))))
594   (setq buffer-file-name nil)
595   t)
596
597 ;;;
598 ;;; Alta Vista
599 ;;;
600
601 (defun nnweb-altavista-create-mapping ()
602   "Perform the search and create an number-to-url alist."
603   (save-excursion
604     (set-buffer nnweb-buffer)
605     (erase-buffer)
606     (let ((part 0))
607       (when (funcall (nnweb-definition 'search) nnweb-search part)
608         (let ((i 0)
609               (more t)
610               (case-fold-search t)
611               (active (or (cadr (assoc nnweb-group nnweb-group-alist))
612                           (cons 1 0)))
613               subject date from id group
614               map url)
615           (while more
616             ;; Go through all the article hits on this page.
617             (goto-char (point-min))
618             (search-forward "<dt>" nil t)
619             (delete-region (point-min) (match-beginning 0))
620             (goto-char (point-min))
621             (while (search-forward "<dt>" nil t)
622               (replace-match "\n<blubb>"))
623             (nnweb-decode-entities)
624             (goto-char (point-min))
625             (while (re-search-forward "<blubb>.*href=\"\\([^\"]+\\)\"><strong>\\([^>]*\\)</strong></a><dd>\\([^-]+\\)- <b>\\([^<]+\\)<.*href=\"news:\\([^\"]+\\)\">.*\">\\(.+\\)</a><P>"
626                                       nil t)
627               (setq url (match-string 1)
628                     subject (match-string 2)
629                     date (match-string 3)
630                     group (match-string 4)
631                     id (concat "<" (match-string 5) ">")
632                     from (match-string 6))
633               (incf i)
634               (unless (nnweb-get-hashtb url)
635                 (push
636                  (list
637                   (incf (cdr active))
638                   (make-full-mail-header
639                    (cdr active) (concat  "(" group ") " subject) from date
640                    id nil 0 0 url))
641                  map)
642                 (nnweb-set-hashtb (cadar map) (car map))))
643             ;; See if we want more.
644             (when (or (not nnweb-articles)
645                       (>= i nnweb-max-hits)
646                       (not (funcall (nnweb-definition 'search)
647                                     nnweb-search (incf part))))
648               (setq more nil)))
649           ;; Return the articles in the right order.
650           (setq nnweb-articles
651                 (sort (nconc nnweb-articles map) 'car-less-than-car)))))))
652
653 (defun nnweb-altavista-wash-article ()
654   (goto-char (point-min))
655   (let ((case-fold-search t))
656     (when (re-search-forward "^<strong>" nil t)
657       (delete-region (point-min) (match-beginning 0)))
658     (goto-char (point-min))
659     (while (looking-at "<strong>\\([^ ]+\\) +</strong> +\\(.*\\)$")
660       (replace-match "\\1: \\2" t)
661       (forward-line 1))
662     (when (re-search-backward "^References:" nil t)
663       (narrow-to-region (point) (progn (forward-line 1) (point)))
664       (goto-char (point-min))
665       (while (re-search-forward "<A.*\\?id@\\([^\"]+\\)\">[0-9]+</A>" nil t)
666         (replace-match "&lt;\\1&gt; " t)))
667     (widen)
668     (nnweb-remove-markup)))
669
670 (defun nnweb-altavista-search (search &optional part)
671   (url-insert-file-contents
672    (concat
673     (nnweb-definition 'address)
674     "?"
675     (nnweb-encode-www-form-urlencoded
676      `(("pg" . "aq")
677        ("what" . "news")
678        ,@(when part `(("stq" . ,(int-to-string (* part 30)))))
679        ("fmt" . "d")
680        ("q" . ,search)
681        ("r" . "")
682        ("d0" . "")
683        ("d1" . "")))))
684   (setq buffer-file-name nil)
685   t)
686
687 ;;;
688 ;;; General web/w3 interface utility functions
689 ;;;
690
691 (defun nnweb-insert-html (parse)
692   "Insert HTML based on a w3 parse tree."
693   (if (stringp parse)
694       (insert parse)
695     (insert "<" (symbol-name (car parse)) " ")
696     (insert (mapconcat
697              (lambda (param)
698                (concat (symbol-name (car param)) "="
699                        (prin1-to-string
700                         (if (consp (cdr param))
701                             (cadr param)
702                           (cdr param)))))
703              (nth 1 parse)
704              " "))
705     (insert ">\n")
706     (mapcar 'nnweb-insert-html (nth 2 parse))
707     (insert "</" (symbol-name (car parse)) ">\n")))
708
709 (defun nnweb-encode-www-form-urlencoded (pairs)
710   "Return PAIRS encoded for forms."
711   (mapconcat
712    (function
713     (lambda (data)
714       (concat (w3-form-encode-xwfu (car data)) "="
715               (w3-form-encode-xwfu (cdr data)))))
716    pairs "&"))
717
718 (defun nnweb-fetch-form (url pairs)
719   "Fetch a form from URL with PAIRS as the data using the POST method."
720   (let ((url-request-data (nnweb-encode-www-form-urlencoded pairs))
721         (url-request-method "POST")
722         (url-request-extra-headers
723          '(("Content-type" . "application/x-www-form-urlencoded"))))
724     (url-insert-file-contents url)
725     (setq buffer-file-name nil))
726   t)
727
728 (defun nnweb-decode-entities ()
729   "Decode all HTML entities."
730   (goto-char (point-min))
731   (while (re-search-forward "&\\(#[0-9]+\\|[a-z]+\\);" nil t)
732     (let ((elem (if (eq (aref (match-string 1) 0) ?\#)
733                         (let ((c
734                                (string-to-number (substring 
735                                                   (match-string 1) 1))))
736                           (if (mm-char-or-char-int-p c) c 32))
737                       (or (cdr (assq (intern (match-string 1))
738                                      w3-html-entities))
739                           ?#))))
740       (unless (stringp elem)
741         (setq elem (char-to-string elem)))
742       (replace-match elem t t))))
743
744 (defun nnweb-decode-entities-string (string)
745   (with-temp-buffer
746     (insert string)
747     (nnweb-decode-entities)
748     (buffer-substring (point-min) (point-max))))
749
750 (defun nnweb-remove-markup ()
751   "Remove all HTML markup, leaving just plain text."
752   (goto-char (point-min))
753   (while (search-forward "<!--" nil t)
754     (delete-region (match-beginning 0)
755                    (or (search-forward "-->" nil t)
756                        (point-max))))
757   (goto-char (point-min))
758   (while (re-search-forward "<[^>]+>" nil t)
759     (replace-match "" t t)))
760
761 (defun nnweb-insert (url &optional follow-refresh)
762   "Insert the contents from an URL in the current buffer.
763 If FOLLOW-REFRESH is non-nil, redirect refresh url in META."
764   (let ((name buffer-file-name))
765     (if follow-refresh
766         (save-restriction
767           (narrow-to-region (point) (point))
768           (url-insert-file-contents url)
769           (goto-char (point-min))
770           (when (re-search-forward 
771                  "<meta[ \t\r\n]*http-equiv=\"Refresh\"[^>]*URL=\\([^\"]+\\)\"" nil t)
772             (let ((url (match-string 1)))
773               (delete-region (point-min) (point-max))
774               (nnweb-insert url t))))
775       (url-insert-file-contents url))
776     (setq buffer-file-name name)))
777
778 (defun nnweb-parse-find (type parse &optional maxdepth)
779   "Find the element of TYPE in PARSE."
780   (catch 'found
781     (nnweb-parse-find-1 type parse maxdepth)))
782
783 (defun nnweb-parse-find-1 (type contents maxdepth)
784   (when (or (null maxdepth)
785             (not (zerop maxdepth)))
786     (when (consp contents)
787       (when (eq (car contents) type)
788         (throw 'found contents))
789       (when (listp (cdr contents))
790         (dolist (element contents)
791           (when (consp element)
792             (nnweb-parse-find-1 type element
793                                 (and maxdepth (1- maxdepth)))))))))
794
795 (defun nnweb-parse-find-all (type parse)
796   "Find all elements of TYPE in PARSE."
797   (catch 'found
798     (nnweb-parse-find-all-1 type parse)))
799
800 (defun nnweb-parse-find-all-1 (type contents)
801   (let (result)
802     (when (consp contents)
803       (if (eq (car contents) type)
804           (push contents result)
805         (when (listp (cdr contents))
806           (dolist (element contents)
807             (when (consp element)
808               (setq result
809                     (nconc result (nnweb-parse-find-all-1 type element))))))))
810     result))
811
812 (defvar nnweb-text)
813 (defun nnweb-text (parse)
814   "Return a list of text contents in PARSE."
815   (let ((nnweb-text nil))
816     (nnweb-text-1 parse)
817     (nreverse nnweb-text)))
818
819 (defun nnweb-text-1 (contents)
820   (dolist (element contents)
821     (if (stringp element)
822         (push element nnweb-text)
823       (when (and (consp element)
824                  (listp (cdr element)))
825         (nnweb-text-1 element)))))
826
827 (defun nnweb-replace-in-string (string match newtext)
828   (while (string-match match string)
829     (setq string (replace-match newtext t t string)))
830   string)
831
832 (provide 'nnweb)
833
834 ;;; nnweb.el ends here