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