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