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