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