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