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