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