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