1999-02-11 Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
[elisp/gnus.git-] / lisp / nnheader.el
1 ;;; nnheader.el --- header access macros for Semi-gnus and its backends
2 ;; Copyright (C) 1987-1990,1993-1999 Free Software Foundation, Inc.
3
4 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
5 ;;      Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      MORIOKA Tomohiko <morioka@jaist.ac.jp>
7 ;;      Katsumi Yamaoka <yamaoka@jpl.org>
8 ;; Keywords: mail, news, MIME
9
10 ;; This file is part of GNU Emacs.
11
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 2, or (at your option)
15 ;; any later version.
16
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.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26
27 ;;; Commentary:
28
29 ;; These macros may look very much like the ones in GNUS 4.1.  They
30 ;; are, in a way, but you should note that the indices they use have
31 ;; been changed from the internal GNUS format to the NOV format.  The
32 ;; makes it possible to read headers from XOVER much faster.
33 ;;
34 ;; The format of a header is now:
35 ;; [number subject from date id references chars lines xref]
36 ;;
37 ;; (That last entry is defined as "misc" in the NOV format, but Gnus
38 ;; uses it for xrefs.)
39
40 ;;; Code:
41
42 (eval-when-compile (require 'cl))
43
44 (require 'mail-utils)
45 (require 'mime)
46
47 (defvar nnheader-max-head-length 4096
48   "*Max length of the head of articles.")
49
50 (defvar nnheader-head-chop-length 2048
51   "*Length of each read operation when trying to fetch HEAD headers.")
52
53 (defvar nnheader-file-name-translation-alist nil
54   "*Alist that says how to translate characters in file names.
55 For instance, if \":\" is invalid as a file character in file names
56 on your system, you could say something like:
57
58 \(setq nnheader-file-name-translation-alist '((?: . ?_)))")
59
60 (eval-and-compile
61  (autoload 'nnmail-message-id "nnmail")
62  (autoload 'mail-position-on-field "sendmail")
63  (autoload 'message-remove-header "message")
64  (autoload 'cancel-function-timers "timers")
65  (autoload 'gnus-point-at-eol "gnus-util")
66  (autoload 'gnus-delete-line "gnus-util")
67  (autoload 'gnus-buffer-live-p "gnus-util"))
68
69 ;;; Header access macros.
70
71 (defmacro mail-header-number (header)
72   "Return article number in HEADER."
73   `(mime-entity-location-internal ,header))
74
75 (defmacro mail-header-set-number (header number)
76   "Set article number of HEADER to NUMBER."
77   `(mime-entity-set-location-internal ,header ,number))
78
79 (defalias 'mail-header-subject 'mime-entity-decoded-subject-internal)
80 (defalias 'mail-header-set-subject 'mime-entity-set-decoded-subject-internal)
81
82 (defalias 'mail-header-from 'mime-entity-decoded-from-internal)
83 (defalias 'mail-header-set-from 'mime-entity-set-decoded-from-internal)
84
85 (defalias 'mail-header-date 'mime-entity-date-internal)
86 (defalias 'mail-header-set-date 'mime-entity-set-date-internal)
87
88 (defalias 'mail-header-message-id 'mime-entity-message-id-internal)
89 (defalias 'mail-header-id 'mime-entity-message-id-internal)
90 (defalias 'mail-header-set-message-id 'mime-entity-set-message-id-internal)
91 (defalias 'mail-header-set-id 'mime-entity-set-message-id-internal)
92
93 (defalias 'mail-header-references 'mime-entity-references-internal)
94 (defalias 'mail-header-set-references 'mime-entity-set-references-internal)
95
96 (defalias 'mail-header-chars 'mime-entity-chars-internal)
97 (defalias 'mail-header-set-chars 'mime-entity-set-chars-internal)
98
99 (defalias 'mail-header-lines 'mime-entity-lines-internal)
100 (defalias 'mail-header-set-lines 'mime-entity-set-lines-internal)
101
102 (defalias 'mail-header-xref 'mime-entity-xref-internal)
103 (defalias 'mail-header-set-xref 'mime-entity-set-xref-internal)
104
105 (defalias 'nnheader-decode-subject
106   (mime-find-field-decoder 'Subject 'nov))
107 (defalias 'nnheader-decode-from
108   (mime-find-field-decoder 'From 'nov))
109
110 (defalias 'mail-header-extra 'ignore)
111 (defalias 'mail-header-set-extra 'ignore)
112
113 (defsubst nnheader-decode-field-body (field-body field-name
114                                                  &optional mode max-column)
115   (mime-decode-field-body field-body
116                           (if (stringp field-name)
117                               (intern (capitalize field-name))
118                             field-name)
119                           mode max-column))
120
121 (defsubst make-full-mail-header
122   (&optional number subject from date id references chars lines xref extra)
123   "Create a new mail header structure initialized with the parameters given."
124   (make-mime-entity-internal
125    'gnus number
126    nil
127    nil nil nil
128    (if subject
129        (nnheader-decode-subject subject)
130      )
131    (if from
132        (nnheader-decode-from from)
133      )
134    date id references
135    chars lines xref
136    (list (cons 'Subject subject)
137          (cons 'From from))
138    nil nil nil nil nil nil
139 ;;   extra
140    ))
141
142 (defsubst make-full-mail-header-from-decoded-header
143   (&optional number subject from date id references chars lines xref extra)
144   "Create a new mail header structure initialized with the parameters given."
145   (make-mime-entity-internal
146    'gnus number
147    nil
148    nil nil nil
149    subject
150    from
151    date id references
152    chars lines xref
153    nil
154    nil nil nil nil nil nil
155 ;;   extra
156    ))
157
158 (defun make-mail-header (&optional init)
159   "Create a new mail header structure initialized with INIT."
160   (make-full-mail-header init init init init init
161                          init init init init init))
162
163 ;; fake message-ids: generation and detection
164
165 (defvar nnheader-fake-message-id 1)
166
167 (defsubst nnheader-generate-fake-message-id ()
168   (concat "fake+none+" (int-to-string (incf nnheader-fake-message-id))))
169
170 (defsubst nnheader-fake-message-id-p (id)
171   (save-match-data                      ; regular message-id's are <.*>
172     (string-match "\\`fake\\+none\\+[0-9]+\\'" id)))
173
174 ;; Parsing headers and NOV lines.
175
176 (defsubst nnheader-header-value ()
177   (buffer-substring (match-end 0) (gnus-point-at-eol)))
178
179 (defun nnheader-parse-head (&optional naked)
180   (let ((case-fold-search t)
181         (cur (current-buffer))
182         (buffer-read-only nil)
183         in-reply-to lines p ref)
184     (goto-char (point-min))
185     (when naked
186       (insert "\n"))
187     ;; Search to the beginning of the next header.  Error messages
188     ;; do not begin with 2 or 3.
189     (prog1
190         (when (or naked (re-search-forward "^[23][0-9]+ " nil t))
191           ;; This implementation of this function, with nine
192           ;; search-forwards instead of the one re-search-forward and
193           ;; a case (which basically was the old function) is actually
194           ;; about twice as fast, even though it looks messier.  You
195           ;; can't have everything, I guess.  Speed and elegance
196           ;; don't always go hand in hand.
197           (make-full-mail-header
198            ;; Number.
199            (if naked
200                (progn
201                  (setq p (point-min))
202                  0)
203              (prog1
204                  (read cur)
205                (end-of-line)
206                (setq p (point))
207                (narrow-to-region (point)
208                                  (or (and (search-forward "\n.\n" nil t)
209                                           (- (point) 2))
210                                      (point)))))
211            ;; Subject.
212            (progn
213              (goto-char p)
214              (if (search-forward "\nsubject: " nil t)
215                  (nnheader-header-value) "(none)"))
216            ;; From.
217            (progn
218              (goto-char p)
219              (if (search-forward "\nfrom: " nil t)
220                  (nnheader-header-value) "(nobody)"))
221            ;; Date.
222            (progn
223              (goto-char p)
224              (if (search-forward "\ndate: " nil t)
225                  (nnheader-header-value) ""))
226            ;; Message-ID.
227            (progn
228              (goto-char p)
229              (if (search-forward "\nmessage-id:" nil t)
230                  (buffer-substring
231                   (1- (or (search-forward "<" (gnus-point-at-eol) t)
232                           (point)))
233                   (or (search-forward ">" (gnus-point-at-eol) t) (point)))
234                ;; If there was no message-id, we just fake one to make
235                ;; subsequent routines simpler.
236                (nnheader-generate-fake-message-id)))
237            ;; References.
238            (progn
239              (goto-char p)
240              (if (search-forward "\nreferences: " nil t)
241                  (nnheader-header-value)
242                ;; Get the references from the in-reply-to header if there
243                ;; were no references and the in-reply-to header looks
244                ;; promising.
245                (if (and (search-forward "\nin-reply-to: " nil t)
246                         (setq in-reply-to (nnheader-header-value))
247                         (string-match "<[^>]+>" in-reply-to))
248                    (let (ref2)
249                      (setq ref (substring in-reply-to (match-beginning 0)
250                                           (match-end 0)))
251                      (while (string-match "<[^>]+>" in-reply-to (match-end 0))
252                        (setq ref2 (substring in-reply-to (match-beginning 0)
253                                              (match-end 0)))
254                        (when (> (length ref2) (length ref))
255                          (setq ref ref2)))
256                      ref)
257                  nil)))
258            ;; Chars.
259            0
260            ;; Lines.
261            (progn
262              (goto-char p)
263              (if (search-forward "\nlines: " nil t)
264                  (if (numberp (setq lines (read cur)))
265                      lines 0)
266                0))
267            ;; Xref.
268            (progn
269              (goto-char p)
270              (and (search-forward "\nxref: " nil t)
271                   (nnheader-header-value)))
272
273            ;; Extra.
274            (when nnmail-extra-headers
275              (let ((extra nnmail-extra-headers)
276                    out)
277                (while extra
278                  (goto-char p)
279                  (when (search-forward
280                         (concat "\n" (symbol-name (car extra)) ": ") nil t)
281                    (push (cons (car extra) (nnheader-header-value))
282                          out))
283                  (pop extra))
284                out))))
285       (when naked
286         (goto-char (point-min))
287         (delete-char 1)))))
288
289 (defmacro nnheader-nov-skip-field ()
290   '(search-forward "\t" eol 'move))
291
292 (defmacro nnheader-nov-field ()
293   '(buffer-substring (point) (if (nnheader-nov-skip-field) (1- (point)) eol)))
294
295 (defmacro nnheader-nov-read-integer ()
296   '(prog1
297        (if (eq (char-after) ?\t)
298            0
299          (let ((num (ignore-errors (read (current-buffer)))))
300            (if (numberp num) num 0)))
301      (unless (eobp)
302        (search-forward "\t" eol 'move))))
303
304 (defmacro nnheader-nov-parse-extra ()
305   '(let (out string)
306      (while (not (memq (char-after) '(?\n nil)))
307        (setq string (nnheader-nov-field))
308        (when (string-match "^\\([^ :]+\\): " string)
309          (push (cons (intern (match-string 1 string))
310                      (substring string (match-end 0)))
311                out)))
312      out))
313
314 (defmacro nnheader-nov-read-message-id ()
315   '(let ((id (nnheader-nov-field)))
316      (if (string-match "^<[^>]+>$" id)
317          id
318        (nnheader-generate-fake-message-id))))
319
320 (defun nnheader-parse-nov ()
321   (let ((eol (gnus-point-at-eol)))
322     (make-full-mail-header
323      (nnheader-nov-read-integer)        ; number
324      (nnheader-nov-field)               ; subject
325      (nnheader-nov-field)               ; from
326      (nnheader-nov-field)               ; date
327      (nnheader-nov-read-message-id)     ; id
328      (nnheader-nov-field)               ; refs
329      (nnheader-nov-read-integer)        ; chars
330      (nnheader-nov-read-integer)        ; lines
331      (if (eq (char-after) ?\n)
332          nil
333        (nnheader-nov-field))            ; misc
334      (nnheader-nov-parse-extra))))      ; extra
335
336 (defun nnheader-insert-nov (header)
337   (princ (mail-header-number header) (current-buffer))
338   (insert
339    "\t"
340    (or (mime-fetch-field 'Subject header) "(none)") "\t"
341    (or (mime-fetch-field 'From header) "(nobody)") "\t"
342    (or (mail-header-date header) "") "\t"
343    (or (mail-header-id header)
344        (nnmail-message-id))
345    "\t"
346    (or (mail-header-references header) "") "\t")
347   (princ (or (mail-header-chars header) 0) (current-buffer))
348   (insert "\t")
349   (princ (or (mail-header-lines header) 0) (current-buffer))
350   (insert "\t")
351   (when (mail-header-xref header)
352     (insert "Xref: " (mail-header-xref header)))
353   (when (or (mail-header-xref header)
354             (mail-header-extra header))
355     (insert "\t"))
356   (when (mail-header-extra header)
357     (let ((extra (mail-header-extra header)))
358       (while extra
359         (insert (symbol-name (caar extra))
360                 ": " (cdar extra) "\t")
361         (pop extra))))
362   (insert "\n"))
363
364 (defun nnheader-insert-article-line (article)
365   (goto-char (point-min))
366   (insert "220 ")
367   (princ article (current-buffer))
368   (insert " Article retrieved.\n")
369   (search-forward "\n\n" nil 'move)
370   (delete-region (point) (point-max))
371   (forward-char -1)
372   (insert "."))
373
374 (defun nnheader-nov-delete-outside-range (beg end)
375   "Delete all NOV lines that lie outside the BEG to END range."
376   ;; First we find the first wanted line.
377   (nnheader-find-nov-line beg)
378   (delete-region (point-min) (point))
379   ;; Then we find the last wanted line.
380   (when (nnheader-find-nov-line end)
381     (forward-line 1))
382   (delete-region (point) (point-max)))
383
384 (defun nnheader-find-nov-line (article)
385   "Put point at the NOV line that start with ARTICLE.
386 If ARTICLE doesn't exist, put point where that line
387 would have been.  The function will return non-nil if
388 the line could be found."
389   ;; This function basically does a binary search.
390   (let ((max (point-max))
391         (min (goto-char (point-min)))
392         (cur (current-buffer))
393         (prev (point-min))
394         num found)
395     (while (not found)
396       (goto-char (/ (+ max min) 2))
397       (beginning-of-line)
398       (if (or (= (point) prev)
399               (eobp))
400           (setq found t)
401         (setq prev (point))
402         (while (and (not (numberp (setq num (read cur))))
403                     (not (eobp)))
404           (gnus-delete-line))
405         (cond ((> num article)
406                (setq max (point)))
407               ((< num article)
408                (setq min (point)))
409               (t
410                (setq found 'yes)))))
411     ;; We may be at the first line.
412     (when (and (not num)
413                (not (eobp)))
414       (setq num (read cur)))
415     ;; Now we may have found the article we're looking for, or we
416     ;; may be somewhere near it.
417     (when (and (not (eq found 'yes))
418                (not (eq num article)))
419       (setq found (point))
420       (while (and (< (point) max)
421                   (or (not (numberp num))
422                       (< num article)))
423         (forward-line 1)
424         (setq found (point))
425         (or (eobp)
426             (= (setq num (read cur)) article)))
427       (unless (eq num article)
428         (goto-char found)))
429     (beginning-of-line)
430     (eq num article)))
431
432 (defun nnheader-retrieve-headers-from-directory* (articles
433                                                   directory dependencies
434                                                   &optional
435                                                   fetch-old force-new large
436                                                   backend)
437   (with-temp-buffer
438     (let* ((file nil)
439            (number (length articles))
440            (count 0)
441            (pathname-coding-system 'binary)
442            (case-fold-search t)
443            (cur (current-buffer))
444            article
445            headers header id end ref in-reply-to lines chars ctype)
446       ;; We don't support fetching by Message-ID.
447       (if (stringp (car articles))
448           'headers
449         (while articles
450           (when (and (file-exists-p
451                       (setq file (expand-file-name
452                                   (int-to-string
453                                    (setq article (pop articles)))
454                                   directory)))
455                      (not (file-directory-p file)))
456             (erase-buffer)
457             (nnheader-insert-head file)
458             (save-restriction
459               (std11-narrow-to-header)
460               (setq
461                header
462                (make-full-mail-header
463                 ;; Number.
464                 article
465                 ;; Subject.
466                 (or (std11-fetch-field "Subject")
467                     "(none)")
468                 ;; From.
469                 (or (std11-fetch-field "From")
470                     "(nobody)")
471                 ;; Date.
472                 (or (std11-fetch-field "Date")
473                     "")
474                 ;; Message-ID.
475                 (progn
476                   (goto-char (point-min))
477                   (setq id (if (re-search-forward
478                                 "^Message-ID: *\\(<[^\n\t> ]+>\\)" nil t)
479                                ;; We do it this way to make sure the Message-ID
480                                ;; is (somewhat) syntactically valid.
481                                (buffer-substring (match-beginning 1)
482                                                  (match-end 1))
483                              ;; If there was no message-id, we just fake one
484                              ;; to make subsequent routines simpler.
485                              (nnheader-generate-fake-message-id))))
486                 ;; References.
487                 (progn
488                   (goto-char (point-min))
489                   (if (search-forward "\nReferences: " nil t)
490                       (progn
491                         (setq end (point))
492                         (prog1
493                             (buffer-substring (match-end 0) (std11-field-end))
494                           (setq ref
495                                 (buffer-substring
496                                  (progn
497                                    ;; (end-of-line)
498                                    (search-backward ">" end t)
499                                    (1+ (point)))
500                                  (progn
501                                    (search-backward "<" end t)
502                                    (point))))))
503                     ;; Get the references from the in-reply-to header if there
504                     ;; were no references and the in-reply-to header looks
505                     ;; promising.
506                     (if (and (search-forward "\nIn-Reply-To: " nil t)
507                              (setq in-reply-to
508                                    (buffer-substring (match-end 0)
509                                                      (std11-field-end)))
510                              (string-match "<[^>]+>" in-reply-to))
511                         (let (ref2)
512                           (setq ref (substring in-reply-to (match-beginning 0)
513                                                (match-end 0)))
514                           (while (string-match "<[^>]+>"
515                                                in-reply-to (match-end 0))
516                             (setq ref2
517                                   (substring in-reply-to (match-beginning 0)
518                                              (match-end 0)))
519                             (when (> (length ref2) (length ref))
520                               (setq ref ref2)))
521                           ref)
522                       (setq ref nil))))
523                 ;; Chars.
524                 (progn
525                   (goto-char (point-min))
526                   (if (search-forward "\nChars: " nil t)
527                       (if (numberp (setq chars (ignore-errors (read cur))))
528                           chars 0)
529                     0))
530                 ;; Lines.
531                 (progn
532                   (goto-char (point-min))
533                   (if (search-forward "\nLines: " nil t)
534                       (if (numberp (setq lines (ignore-errors (read cur))))
535                           lines 0)
536                     0))
537                 ;; Xref.
538                 (std11-fetch-field "Xref")
539                 ))
540               (goto-char (point-min))
541               (if (setq ctype (std11-fetch-field "Content-Type"))
542                   (mime-entity-set-content-type-internal
543                    header (mime-parse-Content-Type ctype)))
544               )
545             (when (setq header
546                         (gnus-dependencies-add-header
547                          header dependencies force-new))
548               (push header headers))
549             )
550           (setq count (1+ count))
551
552           (and large
553                (zerop (% count 20))
554                (nnheader-message 5 "%s: Receiving headers... %d%%"
555                                  backend
556                                  (/ (* count 100) number))))
557
558         (when large
559           (nnheader-message 5 "%s: Receiving headers...done" backend))
560
561         headers))))
562
563 (defun nnheader-retrieve-headers-from-directory (articles
564                                                  directory dependencies
565                                                  &optional
566                                                  fetch-old force-new large
567                                                  backend)
568   (cons 'header
569         (nreverse (nnheader-retrieve-headers-from-directory*
570                    articles directory dependencies
571                    fetch-old force-new large backend))))
572
573 (defun nnheader-get-newsgroup-headers-xover* (sequence
574                                               &optional
575                                               force-new dependencies
576                                               group)
577   "Parse the news overview data in the server buffer, and return a
578 list of headers that match SEQUENCE (see `nntp-retrieve-headers')."
579   ;; Get the Xref when the users reads the articles since most/some
580   ;; NNTP servers do not include Xrefs when using XOVER.
581   ;; (setq gnus-article-internal-prepare-hook '(gnus-article-get-xrefs))
582   (let ((cur nntp-server-buffer)
583         number headers header)
584     (save-excursion
585       (set-buffer nntp-server-buffer)
586       ;; Allow the user to mangle the headers before parsing them.
587       (gnus-run-hooks 'gnus-parse-headers-hook)
588       (goto-char (point-min))
589       (while (not (eobp))
590         (condition-case ()
591             (while (and sequence (not (eobp)))
592               (setq number (read cur))
593               (while (and sequence
594                           (< (car sequence) number))
595                 (setq sequence (cdr sequence)))
596               (and sequence
597                    (eq number (car sequence))
598                    (progn
599                      (setq sequence (cdr sequence))
600                      (setq header (inline
601                                     (gnus-nov-parse-line
602                                      number dependencies force-new))))
603                    (push header headers))
604               (forward-line 1))
605           (error
606            (gnus-error 4 "Strange nov line (%d)"
607                        (count-lines (point-min) (point)))))
608         (forward-line 1))
609       ;; A common bug in inn is that if you have posted an article and
610       ;; then retrieves the active file, it will answer correctly --
611       ;; the new article is included.  However, a NOV entry for the
612       ;; article may not have been generated yet, so this may fail.
613       ;; We work around this problem by retrieving the last few
614       ;; headers using HEAD.
615       headers)))
616
617 ;; Various cruft the backends and Gnus need to communicate.
618
619 (defvar nntp-server-buffer nil)
620 (defvar nntp-process-response nil)
621 (defvar gnus-verbose-backends 7
622   "*A number that says how talkative the Gnus backends should be.")
623 (defvar gnus-nov-is-evil nil
624   "If non-nil, Gnus backends will never output headers in the NOV format.")
625 (defvar news-reply-yank-from nil)
626 (defvar news-reply-yank-message-id nil)
627
628 (defvar nnheader-callback-function nil)
629
630 (defun nnheader-init-server-buffer ()
631   "Initialize the Gnus-backend communication buffer."
632   (save-excursion
633     (unless (gnus-buffer-live-p nntp-server-buffer)
634       (setq nntp-server-buffer (get-buffer-create " *nntpd*")))
635     (set-buffer nntp-server-buffer)
636     (erase-buffer)
637     (kill-all-local-variables)
638     (setq case-fold-search t)           ;Should ignore case.
639     (set (make-local-variable 'nntp-process-response) nil)
640     t))
641
642 ;;; Various functions the backends use.
643
644 (defun nnheader-file-error (file)
645   "Return a string that says what is wrong with FILE."
646   (format
647    (cond
648     ((not (file-exists-p file))
649      "%s does not exist")
650     ((file-directory-p file)
651      "%s is a directory")
652     ((not (file-readable-p file))
653      "%s is not readable"))
654    file))
655
656 (defun nnheader-insert-head (file)
657   "Insert the head of the article."
658   (when (file-exists-p file)
659     (if (eq nnheader-max-head-length t)
660         ;; Just read the entire file.
661         (nnheader-insert-file-contents file)
662       ;; Read 1K blocks until we find a separator.
663       (let ((beg 0)
664             format-alist)
665         (while (and (eq nnheader-head-chop-length
666                         (nth 1 (nnheader-insert-file-contents
667                                 file nil beg
668                                 (incf beg nnheader-head-chop-length))))
669                     (prog1 (not (search-forward "\n\n" nil t))
670                       (goto-char (point-max)))
671                     (or (null nnheader-max-head-length)
672                         (< beg nnheader-max-head-length))))))
673     t))
674
675 (defun nnheader-article-p ()
676   "Say whether the current buffer looks like an article."
677   (goto-char (point-min))
678   (if (not (search-forward "\n\n" nil t))
679       nil
680     (narrow-to-region (point-min) (1- (point)))
681     (goto-char (point-min))
682     (while (looking-at "[a-zA-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
683       (goto-char (match-end 0)))
684     (prog1
685         (eobp)
686       (widen))))
687
688 (defun nnheader-insert-references (references message-id)
689   "Insert a References header based on REFERENCES and MESSAGE-ID."
690   (if (and (not references) (not message-id))
691       ;; This is invalid, but not all articles have Message-IDs.
692       ()
693     (mail-position-on-field "References")
694     (let ((begin (save-excursion (beginning-of-line) (point)))
695           (fill-column 78)
696           (fill-prefix "\t"))
697       (when references
698         (insert references))
699       (when (and references message-id)
700         (insert " "))
701       (when message-id
702         (insert message-id))
703       ;; Fold long References lines to conform to RFC1036 (sort of).
704       ;; The region must end with a newline to fill the region
705       ;; without inserting extra newline.
706       (fill-region-as-paragraph begin (1+ (point))))))
707
708 (defun nnheader-replace-header (header new-value)
709   "Remove HEADER and insert the NEW-VALUE."
710   (save-excursion
711     (save-restriction
712       (nnheader-narrow-to-headers)
713       (prog1
714           (message-remove-header header)
715         (goto-char (point-max))
716         (insert header ": " new-value "\n")))))
717
718 (defun nnheader-narrow-to-headers ()
719   "Narrow to the head of an article."
720   (widen)
721   (narrow-to-region
722    (goto-char (point-min))
723    (if (search-forward "\n\n" nil t)
724        (1- (point))
725      (point-max)))
726   (goto-char (point-min)))
727
728 (defun nnheader-set-temp-buffer (name &optional noerase)
729   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
730   (set-buffer (get-buffer-create name))
731   (buffer-disable-undo)
732   (unless noerase
733     (erase-buffer))
734   (current-buffer))
735
736 (defvar jka-compr-compression-info-list)
737 (defvar nnheader-numerical-files
738   (if (boundp 'jka-compr-compression-info-list)
739       (concat "\\([0-9]+\\)\\("
740               (mapconcat (lambda (i) (aref i 0))
741                          jka-compr-compression-info-list "\\|")
742               "\\)?")
743     "[0-9]+$")
744   "Regexp that match numerical files.")
745
746 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
747   "Regexp that matches numerical file names.")
748
749 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
750   "Regexp that matches numerical full file paths.")
751
752 (defsubst nnheader-file-to-number (file)
753   "Take a file name and return the article number."
754   (if (string= nnheader-numerical-short-files "^[0-9]+$")
755       (string-to-int file)
756     (string-match nnheader-numerical-short-files file)
757     (string-to-int (match-string 0 file))))
758
759 (defun nnheader-directory-files-safe (&rest args)
760   ;; It has been reported numerous times that `directory-files'
761   ;; fails with an alarming frequency on NFS mounted file systems.
762   ;; This function executes that function twice and returns
763   ;; the longest result.
764   (let ((first (apply 'directory-files args))
765         (second (apply 'directory-files args)))
766     (if (> (length first) (length second))
767         first
768       second)))
769
770 (defun nnheader-directory-articles (dir)
771   "Return a list of all article files in a directory."
772   (mapcar 'nnheader-file-to-number
773           (nnheader-directory-files-safe
774            dir nil nnheader-numerical-short-files t)))
775
776 (defun nnheader-article-to-file-alist (dir)
777   "Return an alist of article/file pairs in DIR."
778   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
779           (nnheader-directory-files-safe
780            dir nil nnheader-numerical-short-files t)))
781
782 (defun nnheader-fold-continuation-lines ()
783   "Fold continuation lines in the current buffer."
784   (nnheader-replace-regexp "\\(\r?\n[ \t]+\\)+" " "))
785
786 (defun nnheader-translate-file-chars (file &optional full)
787   "Translate FILE into something that can be a file name.
788 If FULL, translate everything."
789   (if (null nnheader-file-name-translation-alist)
790       ;; No translation is necessary.
791       file
792     (let* ((i 0)
793            trans leaf path len)
794       (if full
795           ;; Do complete translation.
796           (setq leaf (copy-sequence file)
797                 path "")
798         ;; We translate -- but only the file name.  We leave the directory
799         ;; alone.
800         (if (string-match "/[^/]+\\'" file)
801             ;; This is needed on NT's and stuff.
802             (setq leaf (substring file (1+ (match-beginning 0)))
803                   path (substring file 0 (1+ (match-beginning 0))))
804           ;; Fall back on this.
805           (setq leaf (file-name-nondirectory file)
806                 path (file-name-directory file))))
807       (setq len (length leaf))
808       (while (< i len)
809         (when (setq trans (cdr (assq (aref leaf i)
810                                      nnheader-file-name-translation-alist)))
811           (aset leaf i trans))
812         (incf i))
813       (concat path leaf))))
814
815 (defun nnheader-report (backend &rest args)
816   "Report an error from the BACKEND.
817 The first string in ARGS can be a format string."
818   (set (intern (format "%s-status-string" backend))
819        (if (< (length args) 2)
820            (car args)
821          (apply 'format args)))
822   nil)
823
824 (defun nnheader-get-report (backend)
825   "Get the most recent report from BACKEND."
826   (condition-case ()
827       (nnheader-message 5 "%s" (symbol-value (intern (format "%s-status-string"
828                                                   backend))))
829     (error (nnheader-message 5 ""))))
830
831 (defun nnheader-insert (format &rest args)
832   "Clear the communication buffer and insert FORMAT and ARGS into the buffer.
833 If FORMAT isn't a format string, it and all ARGS will be inserted
834 without formatting."
835   (save-excursion
836     (set-buffer nntp-server-buffer)
837     (erase-buffer)
838     (if (string-match "%" format)
839         (insert (apply 'format format args))
840       (apply 'insert format args))
841     t))
842
843 (defun nnheader-replace-chars-in-string (string from to)
844   "Replace characters in STRING from FROM to TO."
845   (let ((string (substring string 0))   ;Copy string.
846         (len (length string))
847         (idx 0))
848     ;; Replace all occurrences of FROM with TO.
849     (while (< idx len)
850       (when (= (aref string idx) from)
851         (aset string idx to))
852       (setq idx (1+ idx)))
853     string))
854
855 (defun nnheader-file-to-group (file &optional top)
856   "Return a group name based on FILE and TOP."
857   (nnheader-replace-chars-in-string
858    (if (not top)
859        file
860      (condition-case ()
861          (substring (expand-file-name file)
862                     (length
863                      (expand-file-name
864                       (file-name-as-directory top))))
865        (error "")))
866    ?/ ?.))
867
868 (defun nnheader-message (level &rest args)
869   "Message if the Gnus backends are talkative."
870   (if (or (not (numberp gnus-verbose-backends))
871           (<= level gnus-verbose-backends))
872       (apply 'message args)
873     (apply 'format args)))
874
875 (defun nnheader-be-verbose (level)
876   "Return whether the backends should be verbose on LEVEL."
877   (or (not (numberp gnus-verbose-backends))
878       (<= level gnus-verbose-backends)))
879
880 (defvar nnheader-pathname-coding-system 'binary
881   "*Coding system for pathname.")
882
883 (defun nnheader-group-pathname (group dir &optional file)
884   "Make pathname for GROUP."
885   (concat
886    (let ((dir (file-name-as-directory (expand-file-name dir))))
887      ;; If this directory exists, we use it directly.
888      (if (file-directory-p (concat dir group))
889          (concat dir group "/")
890        ;; If not, we translate dots into slashes.
891        (concat dir
892                (encode-coding-string
893                 (nnheader-replace-chars-in-string group ?. ?/)
894                 nnheader-pathname-coding-system)
895                "/")))
896    (cond ((null file) "")
897          ((numberp file) (int-to-string file))
898          (t file))))
899
900 (defun nnheader-functionp (form)
901   "Return non-nil if FORM is funcallable."
902   (or (and (symbolp form) (fboundp form))
903       (and (listp form) (eq (car form) 'lambda))))
904
905 (defun nnheader-concat (dir &rest files)
906   "Concat DIR as directory to FILE."
907   (apply 'concat (file-name-as-directory dir) files))
908
909 (defun nnheader-ms-strip-cr ()
910   "Strip ^M from the end of all lines."
911   (save-excursion
912     (goto-char (point-min))
913     (while (re-search-forward "\r$" nil t)
914       (delete-backward-char 1))))
915
916 (defun nnheader-file-size (file)
917   "Return the file size of FILE or 0."
918   (or (nth 7 (file-attributes file)) 0))
919
920 (defun nnheader-find-etc-directory (package &optional file)
921   "Go through the path and find the \".../etc/PACKAGE\" directory.
922 If FILE, find the \".../etc/PACKAGE\" file instead."
923   (let ((path load-path)
924         dir result)
925     ;; We try to find the dir by looking at the load path,
926     ;; stripping away the last component and adding "etc/".
927     (while path
928       (if (and (car path)
929                (file-exists-p
930                 (setq dir (concat
931                            (file-name-directory
932                             (directory-file-name (car path)))
933                            "etc/" package
934                            (if file "" "/"))))
935                (or file (file-directory-p dir)))
936           (setq result dir
937                 path nil)
938         (setq path (cdr path))))
939     result))
940
941 (defvar ange-ftp-path-format)
942 (defvar efs-path-regexp)
943 (defun nnheader-re-read-dir (path)
944   "Re-read directory PATH if PATH is on a remote system."
945   (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
946       (when (string-match efs-path-regexp path)
947         (efs-re-read-dir path))
948     (when (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
949       (when (string-match (car ange-ftp-path-format) path)
950         (ange-ftp-re-read-dir path)))))
951
952 (defvar nnheader-file-coding-system 'raw-text
953   "Coding system used in file backends of Gnus.")
954
955 (defun nnheader-insert-file-contents (filename &optional visit beg end replace)
956   "Like `insert-file-contents', q.v., but only reads in the file.
957 A buffer may be modified in several ways after reading into the buffer due
958 to advanced Emacs features, such as file-name-handlers, format decoding,
959 find-file-hooks, etc.
960   This function ensures that none of these modifications will take place."
961   (let ((format-alist nil)
962         (auto-mode-alist (nnheader-auto-mode-alist))
963         (default-major-mode 'fundamental-mode)
964         (enable-local-variables nil)
965         (after-insert-file-functions nil)
966         (find-file-hooks nil))
967     (insert-file-contents-as-coding-system
968      nnheader-file-coding-system filename visit beg end replace)))
969
970 (defun nnheader-find-file-noselect (&rest args)
971   (let ((format-alist nil)
972         (auto-mode-alist (nnheader-auto-mode-alist))
973         (default-major-mode 'fundamental-mode)
974         (enable-local-variables nil)
975         (after-insert-file-functions nil)
976         (find-file-hooks nil))
977     (apply 'find-file-noselect-as-coding-system
978            nnheader-file-coding-system args)))
979
980 (defun nnheader-auto-mode-alist ()
981   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
982   (let ((alist auto-mode-alist)
983         out)
984     (while alist
985       (when (listp (cdar alist))
986         (push (car alist) out))
987       (pop alist))
988     (nreverse out)))
989
990 (defun nnheader-directory-regular-files (dir)
991   "Return a list of all regular files in DIR."
992   (let ((files (directory-files dir t))
993         out)
994     (while files
995       (when (file-regular-p (car files))
996         (push (car files) out))
997       (pop files))
998     (nreverse out)))
999
1000 (defun nnheader-directory-files (&rest args)
1001   "Same as `directory-files', but prune \".\" and \"..\"."
1002   (let ((files (apply 'directory-files args))
1003         out)
1004     (while files
1005       (unless (member (file-name-nondirectory (car files)) '("." ".."))
1006         (push (car files) out))
1007       (pop files))
1008     (nreverse out)))
1009
1010 (defmacro nnheader-skeleton-replace (from &optional to regexp)
1011   `(let ((new (generate-new-buffer " *nnheader replace*"))
1012          (cur (current-buffer))
1013          (start (point-min)))
1014      (set-buffer cur)
1015      (goto-char (point-min))
1016      (while (,(if regexp 're-search-forward 'search-forward)
1017              ,from nil t)
1018        (insert-buffer-substring
1019         cur start (prog1 (match-beginning 0) (set-buffer new)))
1020        (goto-char (point-max))
1021        ,(when to `(insert ,to))
1022        (set-buffer cur)
1023        (setq start (point)))
1024      (insert-buffer-substring
1025       cur start (prog1 (point-max) (set-buffer new)))
1026      (copy-to-buffer cur (point-min) (point-max))
1027      (kill-buffer (current-buffer))
1028      (set-buffer cur)))
1029
1030 (defun nnheader-replace-string (from to)
1031   "Do a fast replacement of FROM to TO from point to point-max."
1032   (nnheader-skeleton-replace from to))
1033
1034 (defun nnheader-replace-regexp (from to)
1035   "Do a fast regexp replacement of FROM to TO from point to point-max."
1036   (nnheader-skeleton-replace from to t))
1037
1038 (defun nnheader-strip-cr ()
1039   "Strip all \r's from the current buffer."
1040   (nnheader-skeleton-replace "\r"))
1041
1042 (fset 'nnheader-run-at-time 'run-at-time)
1043 (fset 'nnheader-cancel-timer 'cancel-timer)
1044 (fset 'nnheader-cancel-function-timers 'cancel-function-timers)
1045
1046 (defun nnheader-Y-or-n-p (prompt)
1047   "Ask user a \"Y/n\" question. Return t if answer is neither \"n\", \"N\" nor \"C-g\"."
1048   (let ((cursor-in-echo-area t)
1049         (echo-keystrokes 0)
1050         (inhibit-quit t)
1051         ans)
1052     (let (message-log-max)
1053       (while (not (memq ans '(?\  ?N ?Y ?\C-g ?\e ?\n ?\r ?n ?y)))
1054         (message "%s(Y/n) " prompt)
1055         (setq ans (read-char-exclusive))))
1056     (if (memq ans '(?\C-g ?N ?n))
1057         (progn
1058           (message "%s(Y/n) No" prompt)
1059           nil)
1060       (message "%s(Y/n) Yes" prompt)
1061       t)))
1062
1063 (when (string-match "XEmacs\\|Lucid" emacs-version)
1064   (require 'nnheaderxm))
1065
1066 (run-hooks 'nnheader-load-hook)
1067
1068 (provide 'nnheader)
1069
1070 ;;; nnheader.el ends here