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