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