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