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