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