c16bdefd9b1dc1074725b3e377bcb52146ea2250
[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,98 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 ref)
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 "<" (gnus-point-at-eol) t)
218                           (point)))
219                   (or (search-forward ">" (gnus-point-at-eol) t) (point)))
220                ;; If there was no message-id, we just fake one to make
221                ;; subsequent routines simpler.
222                (nnheader-generate-fake-message-id)))
223            ;; References.
224            (progn
225              (goto-char p)
226              (if (search-forward "\nreferences: " nil t)
227                  (nnheader-header-value)
228                ;; Get the references from the in-reply-to header if there
229                ;; were no references and the in-reply-to header looks
230                ;; promising.
231                (if (and (search-forward "\nin-reply-to: " nil t)
232                         (setq in-reply-to (nnheader-header-value))
233                         (string-match "<[^>]+>" in-reply-to))
234                    (let (ref2)
235                      (setq ref (substring in-reply-to (match-beginning 0)
236                                           (match-end 0)))
237                      (while (string-match "<[^>]+>" in-reply-to (match-end 0))
238                        (setq ref2 (substring in-reply-to (match-beginning 0)
239                                              (match-end 0)))
240                        (when (> (length ref2) (length ref))
241                          (setq ref ref2))))
242                  "")))
243            ;; Chars.
244            0
245            ;; Lines.
246            (progn
247              (goto-char p)
248              (if (search-forward "\nlines: " nil t)
249                  (if (numberp (setq lines (read cur)))
250                      lines 0)
251                0))
252            ;; Xref.
253            (progn
254              (goto-char p)
255              (and (search-forward "\nxref: " nil t)
256                   (nnheader-header-value)))))
257       (when naked
258         (goto-char (point-min))
259         (delete-char 1)))))
260
261 (defmacro nnheader-nov-skip-field ()
262   '(search-forward "\t" eol 'move))
263
264 (defmacro nnheader-nov-field ()
265   '(buffer-substring (point) (if (nnheader-nov-skip-field) (1- (point)) eol)))
266
267 (defmacro nnheader-nov-read-integer ()
268   '(prog1
269        (if (= (following-char) ?\t)
270            0
271          (let ((num (ignore-errors (read (current-buffer)))))
272            (if (numberp num) num 0)))
273      (or (eobp) (forward-char 1))))
274
275 ;; (defvar nnheader-none-counter 0)
276
277 (defun nnheader-parse-nov ()
278   (let ((eol (gnus-point-at-eol)))
279     (vector
280      (nnheader-nov-read-integer)        ; number
281      (nnheader-nov-field)               ; subject
282      (nnheader-nov-field)               ; from
283      (nnheader-nov-field)               ; date
284      (or (nnheader-nov-field)
285          (nnheader-generate-fake-message-id)) ; id
286      (nnheader-nov-field)               ; refs
287      (nnheader-nov-read-integer)        ; chars
288      (nnheader-nov-read-integer)        ; lines
289      (if (= (following-char) ?\n)
290          nil
291        (nnheader-nov-field))            ; misc
292      )))
293
294 (defun nnheader-insert-nov (header)
295   (princ (mail-header-number header) (current-buffer))
296   (insert
297    "\t"
298    (or (mail-header-subject header) "(none)") "\t"
299    (or (mail-header-from header) "(nobody)") "\t"
300    (or (mail-header-date header) "") "\t"
301    (or (mail-header-id header)
302        (nnmail-message-id))
303    "\t"
304    (or (mail-header-references header) "") "\t")
305   (princ (or (mail-header-chars header) 0) (current-buffer))
306   (insert "\t")
307   (princ (or (mail-header-lines header) 0) (current-buffer))
308   (insert "\t")
309   (when (mail-header-xref header)
310     (insert "Xref: " (mail-header-xref header) "\t"))
311   (insert "\n"))
312
313 (defun nnheader-insert-article-line (article)
314   (goto-char (point-min))
315   (insert "220 ")
316   (princ article (current-buffer))
317   (insert " Article retrieved.\n")
318   (search-forward "\n\n" nil 'move)
319   (delete-region (point) (point-max))
320   (forward-char -1)
321   (insert "."))
322
323 (defun nnheader-nov-delete-outside-range (beg end)
324   "Delete all NOV lines that lie outside the BEG to END range."
325   ;; First we find the first wanted line.
326   (nnheader-find-nov-line beg)
327   (delete-region (point-min) (point))
328   ;; Then we find the last wanted line.
329   (when (nnheader-find-nov-line end)
330     (forward-line 1))
331   (delete-region (point) (point-max)))
332
333 (defun nnheader-find-nov-line (article)
334   "Put point at the NOV line that start with ARTICLE.
335 If ARTICLE doesn't exist, put point where that line
336 would have been.  The function will return non-nil if
337 the line could be found."
338   ;; This function basically does a binary search.
339   (let ((max (point-max))
340         (min (goto-char (point-min)))
341         (cur (current-buffer))
342         (prev (point-min))
343         num found)
344     (while (not found)
345       (goto-char (/ (+ max min) 2))
346       (beginning-of-line)
347       (if (or (= (point) prev)
348               (eobp))
349           (setq found t)
350         (setq prev (point))
351         (while (and (not (numberp (setq num (read cur))))
352                     (not (eobp)))
353           (gnus-delete-line))
354         (cond ((> num article)
355                (setq max (point)))
356               ((< num article)
357                (setq min (point)))
358               (t
359                (setq found 'yes)))))
360     ;; We may be at the first line.
361     (when (and (not num)
362                (not (eobp)))
363       (setq num (read cur)))
364     ;; Now we may have found the article we're looking for, or we
365     ;; may be somewhere near it.
366     (when (and (not (eq found 'yes))
367                (not (eq num article)))
368       (setq found (point))
369       (while (and (< (point) max)
370                   (or (not (numberp num))
371                       (< num article)))
372         (forward-line 1)
373         (setq found (point))
374         (or (eobp)
375             (= (setq num (read cur)) article)))
376       (unless (eq num article)
377         (goto-char found)))
378     (beginning-of-line)
379     (eq num article)))
380
381 ;; Various cruft the backends and Gnus need to communicate.
382
383 (defvar nntp-server-buffer nil)
384 (defvar gnus-verbose-backends 7
385   "*A number that says how talkative the Gnus backends should be.")
386 (defvar gnus-nov-is-evil nil
387   "If non-nil, Gnus backends will never output headers in the NOV format.")
388 (defvar news-reply-yank-from nil)
389 (defvar news-reply-yank-message-id nil)
390
391 (defvar nnheader-callback-function nil)
392
393 (defun nnheader-init-server-buffer ()
394   "Initialize the Gnus-backend communication buffer."
395   (save-excursion
396     (unless (gnus-buffer-live-p nntp-server-buffer)
397       (setq nntp-server-buffer (get-buffer-create " *nntpd*")))
398     (set-buffer nntp-server-buffer)
399     (buffer-disable-undo (current-buffer))
400     (erase-buffer)
401     (kill-all-local-variables)
402     (setq case-fold-search t)           ;Should ignore case.
403     t))
404
405 ;;; Various functions the backends use.
406
407 (defun nnheader-file-error (file)
408   "Return a string that says what is wrong with FILE."
409   (format
410    (cond
411     ((not (file-exists-p file))
412      "%s does not exist")
413     ((file-directory-p file)
414      "%s is a directory")
415     ((not (file-readable-p file))
416      "%s is not readable"))
417    file))
418
419 (defun nnheader-insert-head (file)
420   "Insert the head of the article."
421   (when (file-exists-p file)
422     (if (eq nnheader-max-head-length t)
423         ;; Just read the entire file.
424         (nnheader-insert-file-contents file)
425       ;; Read 1K blocks until we find a separator.
426       (let ((beg 0)
427             format-alist)
428         (while (and (eq nnheader-head-chop-length
429                         (nth 1 (nnheader-insert-file-contents
430                                 file nil beg
431                                 (incf beg nnheader-head-chop-length))))
432                     (prog1 (not (search-forward "\n\n" nil t))
433                       (goto-char (point-max)))
434                     (or (null nnheader-max-head-length)
435                         (< beg nnheader-max-head-length))))))
436     t))
437
438 (defun nnheader-article-p ()
439   "Say whether the current buffer looks like an article."
440   (goto-char (point-min))
441   (if (not (search-forward "\n\n" nil t))
442       nil
443     (narrow-to-region (point-min) (1- (point)))
444     (goto-char (point-min))
445     (while (looking-at "[A-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
446       (goto-char (match-end 0)))
447     (prog1
448         (eobp)
449       (widen))))
450
451 (defun nnheader-insert-references (references message-id)
452   "Insert a References header based on REFERENCES and MESSAGE-ID."
453   (if (and (not references) (not message-id))
454       ()                                ; This is illegal, but not all articles have Message-IDs.
455     (mail-position-on-field "References")
456     (let ((begin (save-excursion (beginning-of-line) (point)))
457           (fill-column 78)
458           (fill-prefix "\t"))
459       (when references
460         (insert references))
461       (when (and references message-id)
462         (insert " "))
463       (when message-id
464         (insert message-id))
465       ;; Fold long References lines to conform to RFC1036 (sort of).
466       ;; The region must end with a newline to fill the region
467       ;; without inserting extra newline.
468       (fill-region-as-paragraph begin (1+ (point))))))
469
470 (defun nnheader-replace-header (header new-value)
471   "Remove HEADER and insert the NEW-VALUE."
472   (save-excursion
473     (save-restriction
474       (nnheader-narrow-to-headers)
475       (prog1
476           (message-remove-header header)
477         (goto-char (point-max))
478         (insert header ": " new-value "\n")))))
479
480 (defun nnheader-narrow-to-headers ()
481   "Narrow to the head of an article."
482   (widen)
483   (narrow-to-region
484    (goto-char (point-min))
485    (if (search-forward "\n\n" nil t)
486        (1- (point))
487      (point-max)))
488   (goto-char (point-min)))
489
490 (defun nnheader-set-temp-buffer (name &optional noerase)
491   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
492   (set-buffer (get-buffer-create name))
493   (buffer-disable-undo (current-buffer))
494   (unless noerase
495     (erase-buffer))
496   (current-buffer))
497
498 (defmacro nnheader-temp-write (file &rest forms)
499   "Create a new buffer, evaluate FORMS there, and write the buffer to FILE.
500 Return the value of FORMS.
501 If FILE is nil, just evaluate FORMS and don't save anything.
502 If FILE is t, return the buffer contents as a string."
503   (let ((temp-file (make-symbol "temp-file"))
504         (temp-buffer (make-symbol "temp-buffer"))
505         (temp-results (make-symbol "temp-results")))
506     `(save-excursion
507        (let* ((,temp-file ,file)
508               (default-major-mode 'fundamental-mode)
509               (,temp-buffer
510                (set-buffer
511                 (get-buffer-create
512                  (generate-new-buffer-name " *nnheader temp*"))))
513               ,temp-results)
514          (unwind-protect
515              (progn
516                (setq ,temp-results (progn ,@forms))
517                (cond
518                 ;; Don't save anything.
519                 ((null ,temp-file)
520                  ,temp-results)
521                 ;; Return the buffer contents.
522                 ((eq ,temp-file t)
523                  (set-buffer ,temp-buffer)
524                  (buffer-string))
525                 ;; Save a file.
526                 (t
527                  (set-buffer ,temp-buffer)
528                  ;; Make sure the directory where this file is
529                  ;; to be saved exists.
530                  (when (not (file-directory-p
531                              (file-name-directory ,temp-file)))
532                    (make-directory (file-name-directory ,temp-file) t))
533                  ;; Save the file.
534                  (write-region (point-min) (point-max)
535                                ,temp-file nil 'nomesg)
536                  ,temp-results)))
537            ;; Kill the buffer.
538            (when (buffer-name ,temp-buffer)
539              (kill-buffer ,temp-buffer)))))))
540
541 (put 'nnheader-temp-write 'lisp-indent-function 1)
542 (put 'nnheader-temp-write 'edebug-form-spec '(form body))
543
544 (defvar jka-compr-compression-info-list)
545 (defvar nnheader-numerical-files
546   (if (boundp 'jka-compr-compression-info-list)
547       (concat "\\([0-9]+\\)\\("
548               (mapconcat (lambda (i) (aref i 0))
549                          jka-compr-compression-info-list "\\|")
550               "\\)?")
551     "[0-9]+$")
552   "Regexp that match numerical files.")
553
554 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
555   "Regexp that matches numerical file names.")
556
557 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
558   "Regexp that matches numerical full file paths.")
559
560 (defsubst nnheader-file-to-number (file)
561   "Take a file name and return the article number."
562   (if (not (boundp 'jka-compr-compression-info-list))
563       (string-to-int file)
564     (string-match nnheader-numerical-short-files file)
565     (string-to-int (match-string 0 file))))
566
567 (defun nnheader-directory-files-safe (&rest args)
568   ;; It has been reported numerous times that `directory-files'
569   ;; fails with an alarming frequency on NFS mounted file systems.
570   ;; This function executes that function twice and returns
571   ;; the longest result.
572   (let ((first (apply 'directory-files args))
573         (second (apply 'directory-files args)))
574     (if (> (length first) (length second))
575         first
576       second)))
577
578 (defun nnheader-directory-articles (dir)
579   "Return a list of all article files in a directory."
580   (mapcar 'nnheader-file-to-number
581           (nnheader-directory-files-safe
582            dir nil nnheader-numerical-short-files t)))
583
584 (defun nnheader-article-to-file-alist (dir)
585   "Return an alist of article/file pairs in DIR."
586   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
587           (nnheader-directory-files-safe
588            dir nil nnheader-numerical-short-files t)))
589
590 (defun nnheader-fold-continuation-lines ()
591   "Fold continuation lines in the current buffer."
592   (nnheader-replace-regexp "\\(\r?\n[ \t]+\\)+" " "))
593
594 (defun nnheader-translate-file-chars (file)
595   (if (null nnheader-file-name-translation-alist)
596       ;; No translation is necessary.
597       file
598     ;; We translate -- but only the file name.  We leave the directory
599     ;; alone.
600     (let* ((i 0)
601            trans leaf path len)
602       (if (string-match "/[^/]+\\'" file)
603           ;; This is needed on NT's and stuff.
604           (setq leaf (substring file (1+ (match-beginning 0)))
605                 path (substring file 0 (1+ (match-beginning 0))))
606         ;; Fall back on this.
607         (setq leaf (file-name-nondirectory file)
608               path (file-name-directory file)))
609       (setq len (length leaf))
610       (while (< i len)
611         (when (setq trans (cdr (assq (aref leaf i)
612                                      nnheader-file-name-translation-alist)))
613           (aset leaf i trans))
614         (incf i))
615       (concat path leaf))))
616
617 (defun nnheader-report (backend &rest args)
618   "Report an error from the BACKEND.
619 The first string in ARGS can be a format string."
620   (set (intern (format "%s-status-string" backend))
621        (if (< (length args) 2)
622            (car args)
623          (apply 'format args)))
624   nil)
625
626 (defun nnheader-get-report (backend)
627   "Get the most recent report from BACKEND."
628   (condition-case ()
629       (message "%s" (symbol-value (intern (format "%s-status-string"
630                                                   backend))))
631     (error (message ""))))
632
633 (defun nnheader-insert (format &rest args)
634   "Clear the communication buffer and insert FORMAT and ARGS into the buffer.
635 If FORMAT isn't a format string, it and all ARGS will be inserted
636 without formatting."
637   (save-excursion
638     (set-buffer nntp-server-buffer)
639     (erase-buffer)
640     (if (string-match "%" format)
641         (insert (apply 'format format args))
642       (apply 'insert format args))
643     t))
644
645 (defun nnheader-replace-chars-in-string (string from to)
646   "Replace characters in STRING from FROM to TO."
647   (let ((string (substring string 0))   ;Copy string.
648         (len (length string))
649         (idx 0))
650     ;; Replace all occurrences of FROM with TO.
651     (while (< idx len)
652       (when (= (aref string idx) from)
653         (aset string idx to))
654       (setq idx (1+ idx)))
655     string))
656
657 (defun nnheader-file-to-group (file &optional top)
658   "Return a group name based on FILE and TOP."
659   (nnheader-replace-chars-in-string
660    (if (not top)
661        file
662      (condition-case ()
663          (substring (expand-file-name file)
664                     (length
665                      (expand-file-name
666                       (file-name-as-directory top))))
667        (error "")))
668    ?/ ?.))
669
670 (defun nnheader-message (level &rest args)
671   "Message if the Gnus backends are talkative."
672   (if (or (not (numberp gnus-verbose-backends))
673           (<= level gnus-verbose-backends))
674       (apply 'message args)
675     (apply 'format args)))
676
677 (defun nnheader-be-verbose (level)
678   "Return whether the backends should be verbose on LEVEL."
679   (or (not (numberp gnus-verbose-backends))
680       (<= level gnus-verbose-backends)))
681
682 (defvar nnheader-pathname-coding-system 'iso-8859-1
683   "*Coding system for pathname.")
684
685 (defun nnheader-group-pathname (group dir &optional file)
686   "Make pathname for GROUP."
687   (concat
688    (let ((dir (file-name-as-directory (expand-file-name dir))))
689      ;; If this directory exists, we use it directly.
690      (if (file-directory-p (concat dir group))
691          (concat dir group "/")
692        ;; If not, we translate dots into slashes.
693        (concat dir
694                (gnus-encode-coding-string
695                 (nnheader-replace-chars-in-string group ?. ?/)
696                 nnheader-pathname-coding-system)
697                "/")))
698    (cond ((null file) "")
699          ((numberp file) (int-to-string file))
700          (t file))))
701
702 (defun nnheader-functionp (form)
703   "Return non-nil if FORM is funcallable."
704   (or (and (symbolp form) (fboundp form))
705       (and (listp form) (eq (car form) 'lambda))))
706
707 (defun nnheader-concat (dir &rest files)
708   "Concat DIR as directory to FILE."
709   (apply 'concat (file-name-as-directory dir) files))
710
711 (defun nnheader-ms-strip-cr ()
712   "Strip ^M from the end of all lines."
713   (save-excursion
714     (goto-char (point-min))
715     (while (re-search-forward "\r$" nil t)
716       (delete-backward-char 1))))
717
718 (defun nnheader-file-size (file)
719   "Return the file size of FILE or 0."
720   (or (nth 7 (file-attributes file)) 0))
721
722 (defun nnheader-find-etc-directory (package &optional file)
723   "Go through the path and find the \".../etc/PACKAGE\" directory.
724 If FILE, find the \".../etc/PACKAGE\" file instead."
725   (let ((path load-path)
726         dir result)
727     ;; We try to find the dir by looking at the load path,
728     ;; stripping away the last component and adding "etc/".
729     (while path
730       (if (and (car path)
731                (file-exists-p
732                 (setq dir (concat
733                            (file-name-directory
734                             (directory-file-name (car path)))
735                            "etc/" package
736                            (if file "" "/"))))
737                (or file (file-directory-p dir)))
738           (setq result dir
739                 path nil)
740         (setq path (cdr path))))
741     result))
742
743 (defvar ange-ftp-path-format)
744 (defvar efs-path-regexp)
745 (defun nnheader-re-read-dir (path)
746   "Re-read directory PATH if PATH is on a remote system."
747   (if (and (fboundp 'efs-re-read-dir) (boundp 'efs-path-regexp))
748       (when (string-match efs-path-regexp path)
749         (efs-re-read-dir path))
750     (when (and (fboundp 'ange-ftp-re-read-dir) (boundp 'ange-ftp-path-format))
751       (when (string-match (car ange-ftp-path-format) path)
752         (ange-ftp-re-read-dir path)))))
753
754 (defvar nnheader-file-coding-system 'raw-text
755   "Coding system used in file backends of Gnus.")
756
757 (defun nnheader-insert-file-contents (filename &optional visit beg end replace)
758   "Like `insert-file-contents', q.v., but only reads in the file.
759 A buffer may be modified in several ways after reading into the buffer due
760 to advanced Emacs features, such as file-name-handlers, format decoding,
761 find-file-hooks, etc.
762   This function ensures that none of these modifications will take place."
763   (let ((format-alist nil)
764         (auto-mode-alist (nnheader-auto-mode-alist))
765         (default-major-mode 'fundamental-mode)
766         (after-insert-file-functions nil)
767         (coding-system-for-read nnheader-file-coding-system))
768     (insert-file-contents filename visit beg end replace)))
769
770 (defun nnheader-find-file-noselect (&rest args)
771   (let ((format-alist nil)
772         (auto-mode-alist (nnheader-auto-mode-alist))
773         (default-major-mode 'fundamental-mode)
774         (enable-local-variables nil)
775         (after-insert-file-functions nil)
776         (coding-system-for-read nnheader-file-coding-system))
777     (apply 'find-file-noselect args)))
778
779 (defun nnheader-auto-mode-alist ()
780   "Return an `auto-mode-alist' with only the .gz (etc) thingies."
781   (let ((alist auto-mode-alist)
782         out)
783     (while alist
784       (when (listp (cdar alist))
785         (push (car alist) out))
786       (pop alist))
787     (nreverse out)))
788
789 (defun nnheader-directory-regular-files (dir)
790   "Return a list of all regular files in DIR."
791   (let ((files (directory-files dir t))
792         out)
793     (while files
794       (when (file-regular-p (car files))
795         (push (car files) out))
796       (pop files))
797     (nreverse out)))
798
799 (defun nnheader-directory-files (&rest args)
800   "Same as `directory-files', but prune \".\" and \"..\"."
801   (let ((files (apply 'directory-files args))
802         out)
803     (while files
804       (unless (member (file-name-nondirectory (car files)) '("." ".."))
805         (push (car files) out))
806       (pop files))
807     (nreverse out)))
808
809 (defmacro nnheader-skeleton-replace (from &optional to regexp)
810   `(let ((new (generate-new-buffer " *nnheader replace*"))
811          (cur (current-buffer))
812          (start (point-min)))
813      (set-buffer new)
814      (buffer-disable-undo (current-buffer))
815      (set-buffer cur)
816      (goto-char (point-min))
817      (while (,(if regexp 're-search-forward 'search-forward)
818              ,from nil t)
819        (insert-buffer-substring
820         cur start (prog1 (match-beginning 0) (set-buffer new)))
821        (goto-char (point-max))
822        ,(when to `(insert ,to))
823        (set-buffer cur)
824        (setq start (point)))
825      (insert-buffer-substring
826       cur start (prog1 (point-max) (set-buffer new)))
827      (copy-to-buffer cur (point-min) (point-max))
828      (kill-buffer (current-buffer))
829      (set-buffer cur)))
830
831 (defun nnheader-replace-string (from to)
832   "Do a fast replacement of FROM to TO from point to point-max."
833   (nnheader-skeleton-replace from to))
834
835 (defun nnheader-replace-regexp (from to)
836   "Do a fast regexp replacement of FROM to TO from point to point-max."
837   (nnheader-skeleton-replace from to t))
838
839 (defun nnheader-strip-cr ()
840   "Strip all \r's from the current buffer."
841   (nnheader-skeleton-replace "\r"))
842
843 (fset 'nnheader-run-at-time 'run-at-time)
844 (fset 'nnheader-cancel-timer 'cancel-timer)
845 (fset 'nnheader-cancel-function-timers 'cancel-function-timers)
846
847 (when (string-match "XEmacs\\|Lucid" emacs-version)
848   (require 'nnheaderxm))
849
850 (run-hooks 'nnheader-load-hook)
851
852 (provide 'nnheader)
853
854 ;;; nnheader.el ends here