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