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