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