T-gnus 6.14.3.
[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            (pathname-coding-system 'binary)
459            (case-fold-search t)
460            (cur (current-buffer))
461            article
462            headers header id end ref in-reply-to lines chars ctype)
463       ;; We don't support fetching by Message-ID.
464       (if (stringp (car articles))
465           'headers
466         (while articles
467           (when (and (file-exists-p
468                       (setq file (expand-file-name
469                                   (int-to-string
470                                    (setq article (pop articles)))
471                                   directory)))
472                      (not (file-directory-p file)))
473             (erase-buffer)
474             (nnheader-insert-head file)
475             (save-restriction
476               (std11-narrow-to-header)
477               (setq
478                header
479                (make-full-mail-header
480                 ;; Number.
481                 article
482                 ;; Subject.
483                 (or (std11-fetch-field "Subject")
484                     "(none)")
485                 ;; From.
486                 (or (std11-fetch-field "From")
487                     "(nobody)")
488                 ;; Date.
489                 (or (std11-fetch-field "Date")
490                     "")
491                 ;; Message-ID.
492                 (progn
493                   (goto-char (point-min))
494                   (setq id (if (re-search-forward
495                                 "^Message-ID: *\\(<[^\n\t> ]+>\\)" nil t)
496                                ;; We do it this way to make sure the Message-ID
497                                ;; is (somewhat) syntactically valid.
498                                (buffer-substring (match-beginning 1)
499                                                  (match-end 1))
500                              ;; If there was no message-id, we just fake one
501                              ;; to make subsequent routines simpler.
502                              (nnheader-generate-fake-message-id))))
503                 ;; References.
504                 (progn
505                   (goto-char (point-min))
506                   (if (search-forward "\nReferences: " nil t)
507                       (progn
508                         (setq end (point))
509                         (prog1
510                             (buffer-substring (match-end 0) (std11-field-end))
511                           (setq ref
512                                 (buffer-substring
513                                  (progn
514                                    ;; (end-of-line)
515                                    (search-backward ">" end t)
516                                    (1+ (point)))
517                                  (progn
518                                    (search-backward "<" end t)
519                                    (point))))))
520                     ;; Get the references from the in-reply-to header if there
521                     ;; were no references and the in-reply-to header looks
522                     ;; promising.
523                     (if (and (search-forward "\nIn-Reply-To: " nil t)
524                              (setq in-reply-to
525                                    (buffer-substring (match-end 0)
526                                                      (std11-field-end)))
527                              (string-match "<[^>]+>" in-reply-to))
528                         (let (ref2)
529                           (setq ref (substring in-reply-to (match-beginning 0)
530                                                (match-end 0)))
531                           (while (string-match "<[^>]+>"
532                                                in-reply-to (match-end 0))
533                             (setq ref2
534                                   (substring in-reply-to (match-beginning 0)
535                                              (match-end 0)))
536                             (when (> (length ref2) (length ref))
537                               (setq ref ref2)))
538                           ref)
539                       (setq ref nil))))
540                 ;; Chars.
541                 (progn
542                   (goto-char (point-min))
543                   (if (search-forward "\nChars: " nil t)
544                       (if (numberp (setq chars (ignore-errors (read cur))))
545                           chars 0)
546                     0))
547                 ;; Lines.
548                 (progn
549                   (goto-char (point-min))
550                   (if (search-forward "\nLines: " nil t)
551                       (if (numberp (setq lines (ignore-errors (read cur))))
552                           lines 0)
553                     0))
554                 ;; Xref.
555                 (std11-fetch-field "Xref")
556                 ))
557               (goto-char (point-min))
558               (if (setq ctype (std11-fetch-field "Content-Type"))
559                   (mime-entity-set-content-type-internal
560                    header (mime-parse-Content-Type ctype)))
561               )
562             (when (setq header
563                         (gnus-dependencies-add-header
564                          header dependencies force-new))
565               (push header headers))
566             )
567           (setq count (1+ count))
568
569           (and large
570                (zerop (% count 20))
571                (nnheader-message 5 "%s: Receiving headers... %d%%"
572                                  backend
573                                  (/ (* count 100) number))))
574
575         (when large
576           (nnheader-message 5 "%s: Receiving headers...done" backend))
577
578         headers))))
579
580 (defun nnheader-retrieve-headers-from-directory (articles
581                                                  directory dependencies
582                                                  &optional
583                                                  fetch-old force-new large
584                                                  backend)
585   (cons 'header
586         (nreverse (nnheader-retrieve-headers-from-directory*
587                    articles directory dependencies
588                    fetch-old force-new large backend))))
589
590 (defun nnheader-get-newsgroup-headers-xover* (sequence
591                                               &optional
592                                               force-new dependencies
593                                               group)
594   "Parse the news overview data in the server buffer, and return a
595 list of headers that match SEQUENCE (see `nntp-retrieve-headers')."
596   ;; Get the Xref when the users reads the articles since most/some
597   ;; NNTP servers do not include Xrefs when using XOVER.
598   ;; (setq gnus-article-internal-prepare-hook '(gnus-article-get-xrefs))
599   (let ((cur nntp-server-buffer)
600         number headers header)
601     (save-excursion
602       (set-buffer nntp-server-buffer)
603       ;; Allow the user to mangle the headers before parsing them.
604       (gnus-run-hooks 'gnus-parse-headers-hook)
605       (goto-char (point-min))
606       (while (not (eobp))
607         (condition-case ()
608             (while (and sequence (not (eobp)))
609               (setq number (read cur))
610               (while (and sequence
611                           (< (car sequence) number))
612                 (setq sequence (cdr sequence)))
613               (and sequence
614                    (eq number (car sequence))
615                    (progn
616                      (setq sequence (cdr sequence))
617                      (setq header (inline
618                                     (gnus-nov-parse-line
619                                      number dependencies force-new))))
620                    (push header headers))
621               (forward-line 1))
622           (error
623            (gnus-error 4 "Strange nov line (%d)"
624                        (count-lines (point-min) (point)))))
625         (forward-line 1))
626       ;; A common bug in inn is that if you have posted an article and
627       ;; then retrieves the active file, it will answer correctly --
628       ;; the new article is included.  However, a NOV entry for the
629       ;; article may not have been generated yet, so this may fail.
630       ;; We work around this problem by retrieving the last few
631       ;; headers using HEAD.
632       headers)))
633
634 ;; Various cruft the backends and Gnus need to communicate.
635
636 (defvar nntp-server-buffer nil)
637 (defvar nntp-process-response nil)
638 (defvar gnus-verbose-backends 7
639   "*A number that says how talkative the Gnus backends should be.")
640 (defvar gnus-nov-is-evil nil
641   "If non-nil, Gnus backends will never output headers in the NOV format.")
642 (defvar news-reply-yank-from nil)
643 (defvar news-reply-yank-message-id nil)
644
645 (defvar nnheader-callback-function nil)
646
647 (defun nnheader-init-server-buffer ()
648   "Initialize the Gnus-backend communication buffer."
649   (save-excursion
650     (unless (gnus-buffer-live-p nntp-server-buffer)
651       (setq nntp-server-buffer (get-buffer-create " *nntpd*")))
652     (set-buffer nntp-server-buffer)
653     (erase-buffer)
654     (kill-all-local-variables)
655     (setq case-fold-search t)           ;Should ignore case.
656     (set (make-local-variable 'nntp-process-response) nil)
657     t))
658
659 ;;; Various functions the backends use.
660
661 (defun nnheader-file-error (file)
662   "Return a string that says what is wrong with FILE."
663   (format
664    (cond
665     ((not (file-exists-p file))
666      "%s does not exist")
667     ((file-directory-p file)
668      "%s is a directory")
669     ((not (file-readable-p file))
670      "%s is not readable"))
671    file))
672
673 (defun nnheader-insert-head (file)
674   "Insert the head of the article."
675   (when (file-exists-p file)
676     (if (eq nnheader-max-head-length t)
677         ;; Just read the entire file.
678         (nnheader-insert-file-contents file)
679       ;; Read 1K blocks until we find a separator.
680       (let ((beg 0)
681             format-alist)
682         (while (and (eq nnheader-head-chop-length
683                         (nth 1 (nnheader-insert-file-contents
684                                 file nil beg
685                                 (incf beg nnheader-head-chop-length))))
686                     (prog1 (not (search-forward "\n\n" nil t))
687                       (goto-char (point-max)))
688                     (or (null nnheader-max-head-length)
689                         (< beg nnheader-max-head-length))))))
690     t))
691
692 (defun nnheader-article-p ()
693   "Say whether the current buffer looks like an article."
694   (goto-char (point-min))
695   (if (not (search-forward "\n\n" nil t))
696       nil
697     (narrow-to-region (point-min) (1- (point)))
698     (goto-char (point-min))
699     (while (looking-at "[a-zA-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
700       (goto-char (match-end 0)))
701     (prog1
702         (eobp)
703       (widen))))
704
705 (defun nnheader-insert-references (references message-id)
706   "Insert a References header based on REFERENCES and MESSAGE-ID."
707   (if (and (not references) (not message-id))
708       ;; This is invalid, but not all articles have Message-IDs.
709       ()
710     (mail-position-on-field "References")
711     (let ((begin (save-excursion (beginning-of-line) (point)))
712           (fill-column 78)
713           (fill-prefix "\t"))
714       (when references
715         (insert references))
716       (when (and references message-id)
717         (insert " "))
718       (when message-id
719         (insert message-id))
720       ;; Fold long References lines to conform to RFC1036 (sort of).
721       ;; The region must end with a newline to fill the region
722       ;; without inserting extra newline.
723       (fill-region-as-paragraph begin (1+ (point))))))
724
725 (defun nnheader-replace-header (header new-value)
726   "Remove HEADER and insert the NEW-VALUE."
727   (save-excursion
728     (save-restriction
729       (nnheader-narrow-to-headers)
730       (prog1
731           (message-remove-header header)
732         (goto-char (point-max))
733         (insert header ": " new-value "\n")))))
734
735 (defun nnheader-narrow-to-headers ()
736   "Narrow to the head of an article."
737   (widen)
738   (narrow-to-region
739    (goto-char (point-min))
740    (if (search-forward "\n\n" nil t)
741        (1- (point))
742      (point-max)))
743   (goto-char (point-min)))
744
745 (defun nnheader-set-temp-buffer (name &optional noerase)
746   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
747   (set-buffer (get-buffer-create name))
748   (buffer-disable-undo)
749   (unless noerase
750     (erase-buffer))
751   (current-buffer))
752
753 (defvar jka-compr-compression-info-list)
754 (defvar nnheader-numerical-files
755   (if (boundp 'jka-compr-compression-info-list)
756       (concat "\\([0-9]+\\)\\("
757               (mapconcat (lambda (i) (aref i 0))
758                          jka-compr-compression-info-list "\\|")
759               "\\)?")
760     "[0-9]+$")
761   "Regexp that match numerical files.")
762
763 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
764   "Regexp that matches numerical file names.")
765
766 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
767   "Regexp that matches numerical full file paths.")
768
769 (defsubst nnheader-file-to-number (file)
770   "Take a file name and return the article number."
771   (if (string= nnheader-numerical-short-files "^[0-9]+$")
772       (string-to-int file)
773     (string-match nnheader-numerical-short-files file)
774     (string-to-int (match-string 0 file))))
775
776 (defun nnheader-directory-files-safe (&rest args)
777   ;; It has been reported numerous times that `directory-files'
778   ;; fails with an alarming frequency on NFS mounted file systems.
779   ;; This function executes that function twice and returns
780   ;; the longest result.
781   (let ((first (apply 'directory-files args))
782         (second (apply 'directory-files args)))
783     (if (> (length first) (length second))
784         first
785       second)))
786
787 (defun nnheader-directory-articles (dir)
788   "Return a list of all article files in a directory."
789   (mapcar 'nnheader-file-to-number
790           (nnheader-directory-files-safe
791            dir nil nnheader-numerical-short-files t)))
792
793 (defun nnheader-article-to-file-alist (dir)
794   "Return an alist of article/file pairs in DIR."
795   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
796           (nnheader-directory-files-safe
797            dir nil nnheader-numerical-short-files t)))
798
799 (defun nnheader-fold-continuation-lines ()
800   "Fold continuation lines in the current buffer."
801   (nnheader-replace-regexp "\\(\r?\n[ \t]+\\)+" " "))
802
803 (defun nnheader-translate-file-chars (file &optional full)
804   "Translate FILE into something that can be a file name.
805 If FULL, translate everything."
806   (if (null nnheader-file-name-translation-alist)
807       ;; No translation is necessary.
808       file
809     (let* ((i 0)
810            trans leaf path len)
811       (if full
812           ;; Do complete translation.
813           (setq leaf (copy-sequence file)
814                 path ""
815                 i (if (and (< 1 (length leaf)) (eq ?: (aref leaf 1))) 
816                       2 0))
817         ;; We translate -- but only the file name.  We leave the directory
818         ;; alone.
819         (if (string-match "/[^/]+\\'" file)
820             ;; This is needed on NT's and stuff.
821             (setq leaf (substring file (1+ (match-beginning 0)))
822                   path (substring file 0 (1+ (match-beginning 0))))
823           ;; Fall back on this.
824           (setq leaf (file-name-nondirectory file)
825                 path (file-name-directory file))))
826       (setq len (length leaf))
827       (while (< i len)
828         (when (setq trans (cdr (assq (aref leaf i)
829                                      nnheader-file-name-translation-alist)))
830           (aset leaf i trans))
831         (incf i))
832       (concat path leaf))))
833
834 (defun nnheader-report (backend &rest args)
835   "Report an error from the BACKEND.
836 The first string in ARGS can be a format string."
837   (set (intern (format "%s-status-string" backend))
838        (if (< (length args) 2)
839            (car args)
840          (apply 'format args)))
841   nil)
842
843 (defun nnheader-get-report (backend)
844   "Get the most recent report from BACKEND."
845   (condition-case ()
846       (nnheader-message 5 "%s" (symbol-value (intern (format "%s-status-string"
847                                                              backend))))
848     (error (nnheader-message 5 ""))))
849
850 (defun nnheader-insert (format &rest args)
851   "Clear the communication buffer and insert FORMAT and ARGS into the buffer.
852 If FORMAT isn't a format string, it and all ARGS will be inserted
853 without formatting."
854   (save-excursion
855     (set-buffer nntp-server-buffer)
856     (erase-buffer)
857     (if (string-match "%" format)
858         (insert (apply 'format format args))
859       (apply 'insert format args))
860     t))
861
862 (defun nnheader-replace-chars-in-string (string from to)
863   "Replace characters in STRING from FROM to TO."
864   (let ((string (substring string 0))   ;Copy string.
865         (len (length string))
866         (idx 0))
867     ;; Replace all occurrences of FROM with TO.
868     (while (< idx len)
869       (when (= (aref string idx) from)
870         (aset string idx to))
871       (setq idx (1+ idx)))
872     string))
873
874 (defun nnheader-replace-duplicate-chars-in-string (string from to)
875   "Replace characters in STRING from FROM to TO."
876   (let ((string (substring string 0))   ;Copy string.
877         (len (length string))
878         (idx 0) prev i)
879     ;; Replace all occurrences of FROM with TO.
880     (while (< idx len)
881       (setq i (aref string idx))
882       (when (and (eq prev from) (= i from))
883         (aset string (1- idx) to)
884         (aset string idx to))
885       (setq prev i)
886       (setq idx (1+ idx)))
887     string))
888
889 (defun nnheader-file-to-group (file &optional top)
890   "Return a group name based on FILE and TOP."
891   (nnheader-replace-chars-in-string
892    (if (not top)
893        file
894      (condition-case ()
895          (substring (expand-file-name file)
896                     (length
897                      (expand-file-name
898                       (file-name-as-directory top))))
899        (error "")))
900    ?/ ?.))
901
902 (defun nnheader-message (level &rest args)
903   "Message if the Gnus backends are talkative."
904   (if (or (not (numberp gnus-verbose-backends))
905           (<= level gnus-verbose-backends))
906       (apply 'message args)
907     (apply 'format args)))
908
909 (defun nnheader-be-verbose (level)
910   "Return whether the backends should be verbose on LEVEL."
911   (or (not (numberp gnus-verbose-backends))
912       (<= level gnus-verbose-backends)))
913
914 (defvar nnheader-pathname-coding-system 'binary
915   "*Coding system for pathname.")
916
917 (defun nnheader-group-pathname (group dir &optional file)
918   "Make pathname for GROUP."
919   (concat
920    (let ((dir (file-name-as-directory (expand-file-name dir))))
921      ;; If this directory exists, we use it directly.
922      (file-name-as-directory
923       (if (file-directory-p (concat dir group))
924           (expand-file-name group dir)
925         ;; If not, we translate dots into slashes.
926         (expand-file-name (encode-coding-string
927                            (nnheader-replace-chars-in-string group ?. ?/)
928                            nnheader-pathname-coding-system)
929                           dir))))
930    (cond ((null file) "")
931          ((numberp file) (int-to-string file))
932          (t file))))
933
934 (defun nnheader-functionp (form)
935   "Return non-nil if FORM is funcallable."
936   (or (and (symbolp form) (fboundp form))
937       (and (listp form) (eq (car form) 'lambda))))
938
939 (defun nnheader-concat (dir &rest files)
940   "Concat DIR as directory to FILE."
941   (apply 'concat (file-name-as-directory dir) files))
942
943 (defun nnheader-ms-strip-cr ()
944   "Strip ^M from the end of all lines."
945   (save-excursion
946     (goto-char (point-min))
947     (while (re-search-forward "\r$" nil t)
948       (delete-backward-char 1))))
949
950 (defun nnheader-file-size (file)
951   "Return the file size of FILE or 0."
952   (or (nth 7 (file-attributes file)) 0))
953
954 (defun nnheader-find-etc-directory (package &optional file)
955   "Go through the path and find the \".../etc/PACKAGE\" directory.
956 If FILE, find the \".../etc/PACKAGE\" file instead."
957   (let ((path load-path)
958         dir result)
959     ;; We try to find the dir by looking at the load path,
960     ;; stripping away the last component and adding "etc/".
961     (while path
962       (if (and (car path)
963                (file-exists-p
964                 (setq dir (concat
965                            (file-name-directory
966                             (directory-file-name (car path)))
967                            "etc/" package
968                            (if file "" "/"))))
969                (or file (file-directory-p dir)))
970           (setq result dir
971                 path nil)
972         (setq path (cdr path))))
973     result))
974
975 (defvar ange-ftp-path-format)
976 (defvar efs-path-regexp)
977 (defun nnheader-re-read-dir (path)
978   "Re-read directory PATH if PATH is on a remote system."
979   (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
980       (when (string-match efs-path-regexp path)
981         (efs-re-read-dir path))
982     (when (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
983       (when (string-match (car ange-ftp-path-format) path)
984         (ange-ftp-re-read-dir path)))))
985
986 (defvar nnheader-file-coding-system 'raw-text
987   "Coding system used in file backends of Gnus.")
988
989 (defun nnheader-insert-file-contents (filename &optional visit beg end replace)
990   "Like `insert-file-contents', q.v., but only reads in the file.
991 A buffer may be modified in several ways after reading into the buffer due
992 to advanced Emacs features, such as file-name-handlers, format decoding,
993 find-file-hooks, etc.
994   This function ensures that none of these modifications will take place."
995   (let ((format-alist nil)
996         (auto-mode-alist (nnheader-auto-mode-alist))
997         (default-major-mode 'fundamental-mode)
998         (enable-local-variables nil)
999         (after-insert-file-functions nil)
1000         (enable-local-eval nil)
1001         (find-file-hooks nil))
1002     (insert-file-contents-as-coding-system
1003      nnheader-file-coding-system filename visit beg end replace)))
1004
1005 (defun nnheader-find-file-noselect (&rest args)
1006   (let ((format-alist nil)
1007         (auto-mode-alist (nnheader-auto-mode-alist))
1008         (default-major-mode 'fundamental-mode)
1009         (enable-local-variables nil)
1010         (after-insert-file-functions nil)
1011         (enable-local-eval nil)
1012         (find-file-hooks nil))
1013     (apply 'find-file-noselect-as-coding-system
1014            nnheader-file-coding-system args)))
1015
1016 (defun nnheader-auto-mode-alist ()
1017   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
1018   (let ((alist auto-mode-alist)
1019         out)
1020     (while alist
1021       (when (listp (cdar alist))
1022         (push (car alist) out))
1023       (pop alist))
1024     (nreverse out)))
1025
1026 (defun nnheader-directory-regular-files (dir)
1027   "Return a list of all regular files in DIR."
1028   (let ((files (directory-files dir t))
1029         out)
1030     (while files
1031       (when (file-regular-p (car files))
1032         (push (car files) out))
1033       (pop files))
1034     (nreverse out)))
1035
1036 (defun nnheader-directory-files (&rest args)
1037   "Same as `directory-files', but prune \".\" and \"..\"."
1038   (let ((files (apply 'directory-files args))
1039         out)
1040     (while files
1041       (unless (member (file-name-nondirectory (car files)) '("." ".."))
1042         (push (car files) out))
1043       (pop files))
1044     (nreverse out)))
1045
1046 (defmacro nnheader-skeleton-replace (from &optional to regexp)
1047   `(let ((new (generate-new-buffer " *nnheader replace*"))
1048          (cur (current-buffer))
1049          (start (point-min)))
1050      (set-buffer cur)
1051      (goto-char (point-min))
1052      (while (,(if regexp 're-search-forward 'search-forward)
1053              ,from nil t)
1054        (insert-buffer-substring
1055         cur start (prog1 (match-beginning 0) (set-buffer new)))
1056        (goto-char (point-max))
1057        ,(when to `(insert ,to))
1058        (set-buffer cur)
1059        (setq start (point)))
1060      (insert-buffer-substring
1061       cur start (prog1 (point-max) (set-buffer new)))
1062      (copy-to-buffer cur (point-min) (point-max))
1063      (kill-buffer (current-buffer))
1064      (set-buffer cur)))
1065
1066 (defun nnheader-replace-string (from to)
1067   "Do a fast replacement of FROM to TO from point to point-max."
1068   (nnheader-skeleton-replace from to))
1069
1070 (defun nnheader-replace-regexp (from to)
1071   "Do a fast regexp replacement of FROM to TO from point to point-max."
1072   (nnheader-skeleton-replace from to t))
1073
1074 (defun nnheader-strip-cr ()
1075   "Strip all \r's from the current buffer."
1076   (nnheader-skeleton-replace "\r"))
1077
1078 (fset 'nnheader-run-at-time 'run-at-time)
1079 (fset 'nnheader-cancel-timer 'cancel-timer)
1080 (fset 'nnheader-cancel-function-timers 'cancel-function-timers)
1081
1082 (defun nnheader-Y-or-n-p (prompt)
1083   "Ask user a \"Y/n\" question. Return t if answer is neither \"n\", \"N\" nor \"C-g\"."
1084   (let ((cursor-in-echo-area t)
1085         (echo-keystrokes 0)
1086         (inhibit-quit t)
1087         ans)
1088     (let (message-log-max)
1089       (while (not (memq ans '(?\  ?N ?Y ?\C-g ?\e ?\n ?\r ?n ?y)))
1090         (message "%s(Y/n) " prompt)
1091         (setq ans (read-char-exclusive))))
1092     (if (memq ans '(?\C-g ?N ?n))
1093         (progn
1094           (message "%s(Y/n) No" prompt)
1095           nil)
1096       (message "%s(Y/n) Yes" prompt)
1097       t)))
1098
1099 (when (string-match "XEmacs\\|Lucid" emacs-version)
1100   (require 'nnheaderxm))
1101
1102 (run-hooks 'nnheader-load-hook)
1103
1104 (provide 'nnheader)
1105
1106 ;;; nnheader.el ends here