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