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