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