*** empty log message ***
[gnus] / lisp / nnheader.el
1 ;;; nnheader.el --- header access macros for Gnus and its backends
2 ;; Copyright (C) 1987,88,89,90,93,94,95,96 Free Software Foundation, Inc.
3
4 ;; Author: Masanobu UMEDA <umerin@flab.flab.fujitsu.junet>
5 ;;      Lars Magne Ingebrigtsen <larsi@ifi.uio.no>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; These macros may look very much like the ones in GNUS 4.1.  They
28 ;; are, in a way, but you should note that the indices they use have
29 ;; been changed from the internal GNUS format to the NOV format.  The
30 ;; makes it possible to read headers from XOVER much faster.
31 ;;
32 ;; The format of a header is now:
33 ;; [number subject from date id references chars lines xref]
34 ;;
35 ;; (That last entry is defined as "misc" in the NOV format, but Gnus
36 ;; uses it for xrefs.)
37
38 ;;; Code:
39
40 (require 'mail-utils)
41 (eval-when-compile (require 'cl))
42
43 (defvar nnheader-max-head-length 4096
44   "*Max length of the head of articles.")
45
46 (defvar nnheader-file-name-translation-alist nil
47   "*Alist that says how to translate characters in file names.
48 For instance, if \":\" is illegal as a file character in file names
49 on your system, you could say something like:
50
51 \(setq nnheader-file-name-translation-alist '((?: . ?_)))")
52
53 ;;; Header access macros.
54
55 (defmacro mail-header-number (header)
56   "Return article number in HEADER."
57   `(aref ,header 0))
58
59 (defmacro mail-header-set-number (header number)
60   "Set article number of HEADER to NUMBER."
61   `(aset ,header 0 ,number))
62
63 (defmacro mail-header-subject (header)
64   "Return subject string in HEADER."
65   `(aref ,header 1))
66
67 (defmacro mail-header-set-subject (header subject)
68   "Set article subject of HEADER to SUBJECT."
69   `(aset ,header 1 ,subject))
70
71 (defmacro mail-header-from (header)
72   "Return author string in HEADER."
73   `(aref ,header 2))
74
75 (defmacro mail-header-set-from (header from)
76   "Set article author of HEADER to FROM."
77   `(aset ,header 2 ,from))
78
79 (defmacro mail-header-date (header)
80   "Return date in HEADER."
81   `(aref ,header 3))
82
83 (defmacro mail-header-set-date (header date)
84   "Set article date of HEADER to DATE."
85   `(aset ,header 3 ,date))
86
87 (defalias 'mail-header-message-id 'mail-header-id)
88 (defmacro mail-header-id (header)
89   "Return Id in HEADER."
90   `(aref ,header 4))
91
92 (defalias 'mail-header-set-message-id 'mail-header-set-id)
93 (defmacro mail-header-set-id (header id)
94   "Set article Id of HEADER to ID."
95   `(aset ,header 4 ,id))
96
97 (defmacro mail-header-references (header)
98   "Return references in HEADER."
99   `(aref ,header 5))
100
101 (defmacro mail-header-set-references (header ref)
102   "Set article references of HEADER to REF."
103   `(aset ,header 5 ,ref))
104
105 (defmacro mail-header-chars (header)
106   "Return number of chars of article in HEADER."
107   `(aref ,header 6))
108
109 (defmacro mail-header-set-chars (header chars)
110   "Set number of chars in article of HEADER to CHARS."
111   `(aset ,header 6 ,chars))
112
113 (defmacro mail-header-lines (header)
114   "Return lines in HEADER."
115   `(aref ,header 7))
116
117 (defmacro mail-header-set-lines (header lines)
118   "Set article lines of HEADER to LINES."
119   `(aset ,header 7 ,lines))
120
121 (defmacro mail-header-xref (header)
122   "Return xref string in HEADER."
123   `(aref ,header 8))
124
125 (defmacro mail-header-set-xref (header xref)
126   "Set article xref of HEADER to xref."
127   `(aset ,header 8 ,xref))
128
129 (defun make-mail-header (&optional init)
130   "Create a new mail header structure initialized with INIT."
131   (make-vector 9 init))
132
133 ;; Parsing headers and NOV lines.
134
135 (defsubst nnheader-header-value ()
136   (buffer-substring (match-end 0) (gnus-point-at-eol)))
137
138 (defvar nnheader-newsgroup-none-id 1)
139
140 (defun nnheader-parse-head (&optional naked)
141   (let ((case-fold-search t)
142         (cur (current-buffer))
143         (buffer-read-only nil)
144         end ref in-reply-to lines p)
145     (goto-char (point-min))
146     (when naked
147       (insert "\n"))
148     ;; Search to the beginning of the next header. Error messages
149     ;; do not begin with 2 or 3.
150     (prog1
151         (when (or naked (re-search-forward "^[23][0-9]+ " nil t))
152           ;; This implementation of this function, with nine
153           ;; search-forwards instead of the one re-search-forward and
154           ;; a case (which basically was the old function) is actually
155           ;; about twice as fast, even though it looks messier.  You
156           ;; can't have everything, I guess.  Speed and elegance
157           ;; doesn't always go hand in hand.
158           (vector
159            ;; Number.
160            (if naked
161                (progn
162                  (setq p (point-min))
163                  0)
164              (prog1
165                  (read cur)
166                (end-of-line)
167                (setq p (point))
168                (narrow-to-region (point)
169                                  (or (and (search-forward "\n.\n" nil t)
170                                           (- (point) 2))
171                                      (point)))))
172            ;; Subject.
173            (progn
174              (goto-char p)
175              (if (search-forward "\nsubject: " nil t)
176                  (nnheader-header-value) "(none)"))
177            ;; From.
178            (progn
179              (goto-char p)
180              (if (search-forward "\nfrom: " nil t)
181                  (nnheader-header-value) "(nobody)"))
182            ;; Date.
183            (progn
184              (goto-char p)
185              (if (search-forward "\ndate: " nil t)
186                  (nnheader-header-value) ""))
187            ;; Message-ID.
188            (progn
189              (goto-char p)
190              (if (search-forward "\nmessage-id: " nil t)
191                  (nnheader-header-value)
192                ;; If there was no message-id, we just fake one to make
193                ;; subsequent routines simpler.
194                (concat "none+"
195                        (int-to-string
196                         (incf nnheader-newsgroup-none-id)))))
197            ;; References.
198            (progn
199              (goto-char p)
200              (if (search-forward "\nreferences: " nil t)
201                  (nnheader-header-value)
202                ;; Get the references from the in-reply-to header if there
203                ;; were no references and the in-reply-to header looks
204                ;; promising.
205                (if (and (search-forward "\nin-reply-to: " nil t)
206                         (setq in-reply-to (nnheader-header-value))
207                         (string-match "<[^>]+>" in-reply-to))
208                    (substring in-reply-to (match-beginning 0)
209                               (match-end 0))
210                  "")))
211            ;; Chars.
212            0
213            ;; Lines.
214            (progn
215              (goto-char p)
216              (if (search-forward "\nlines: " nil t)
217                  (if (numberp (setq lines (read cur)))
218                      lines 0)
219                0))
220            ;; Xref.
221            (progn
222              (goto-char p)
223              (and (search-forward "\nxref: " nil t)
224                   (nnheader-header-value)))))
225       (when naked
226         (goto-char (point-min))
227         (delete-char 1)))))
228
229 (defun nnheader-insert-nov (header)
230   (princ (mail-header-number header) (current-buffer))
231   (insert 
232    "\t"
233    (or (mail-header-subject header) "(none)") "\t"
234    (or (mail-header-from header) "(nobody)") "\t"
235    (or (mail-header-date header) "") "\t"
236    (or (mail-header-id header) "") "\t"
237    (or (mail-header-references header) "") "\t")
238   (princ (or (mail-header-chars header) 0) (current-buffer))
239   (insert "\t")
240   (princ (or (mail-header-lines header) 0) (current-buffer))
241   (insert "\t")
242   (when (mail-header-xref header) 
243     (insert "Xref: " (mail-header-xref header) "\t"))
244   (insert "\n"))
245
246 (defun nnheader-insert-article-line (article)
247   (goto-char (point-min))
248   (insert "220 ")
249   (princ article (current-buffer))
250   (insert " Article retrieved.\n")
251   (search-forward "\n\n" nil 'move)
252   (delete-region (point) (point-max))
253   (forward-char -1)
254   (insert "."))
255
256 ;; Various cruft the backends and Gnus need to communicate.
257
258 (defvar nntp-server-buffer nil)
259 (defvar gnus-verbose-backends 7
260   "*A number that says how talkative the Gnus backends should be.")
261 (defvar gnus-nov-is-evil nil
262   "If non-nil, Gnus backends will never output headers in the NOV format.")
263 (defvar news-reply-yank-from nil)
264 (defvar news-reply-yank-message-id nil)
265
266 (defvar nnheader-callback-function nil)
267
268 (defun nnheader-init-server-buffer ()
269   "Initialize the Gnus-backend communication buffer."
270   (save-excursion
271     (setq nntp-server-buffer (get-buffer-create " *nntpd*"))
272     (set-buffer nntp-server-buffer)
273     (buffer-disable-undo (current-buffer))
274     (erase-buffer)
275     (kill-all-local-variables)
276     (setq case-fold-search t)           ;Should ignore case.
277     t))
278
279
280 ;;; Various functions the backends use.
281
282 (defun nnheader-file-error (file)
283   "Return a string that says what is wrong with FILE."
284   (format
285    (cond
286     ((not (file-exists-p file))
287      "%s does not exist")
288     ((file-directory-p file)
289      "%s is a directory")
290     ((not (file-readable-p file))
291      "%s is not readable"))
292    file))
293
294 (defun nnheader-insert-head (file)
295   "Insert the head of the article."
296   (when (file-exists-p file)
297     (if (eq nnheader-max-head-length t)
298         ;; Just read the entire file.
299         (nnheader-insert-file-contents-literally file)
300       ;; Read 1K blocks until we find a separator.
301       (let ((beg 0)
302             format-alist 
303             (chop 1024))
304         (while (and (eq chop (nth 1 (insert-file-contents
305                                      file nil beg (incf beg chop))))
306                     (prog1 (not (search-forward "\n\n" nil t)) 
307                       (goto-char (point-max)))
308                     (or (null nnheader-max-head-length)
309                         (< beg nnheader-max-head-length))))))
310     t))
311
312 (defun nnheader-article-p ()
313   "Say whether the current buffer looks like an article."
314   (goto-char (point-min))
315   (if (not (search-forward "\n\n" nil t))
316       nil
317     (narrow-to-region (point-min) (1- (point)))
318     (goto-char (point-min))
319     (while (looking-at "[A-Z][^ \t]+:.*\n\\([ \t].*\n\\)*\\|From .*\n")
320       (goto-char (match-end 0)))
321     (prog1
322         (eobp)
323       (widen))))    
324
325 (defun nnheader-insert-references (references message-id)
326   "Insert a References header based on REFERENCES and MESSAGE-ID."
327   (if (and (not references) (not message-id)) 
328       ()        ; This is illegal, but not all articles have Message-IDs.
329     (mail-position-on-field "References")
330     (let ((begin (save-excursion (beginning-of-line) (point)))
331           (fill-column 78)
332           (fill-prefix "\t"))
333       (if references (insert references))
334       (if (and references message-id) (insert " "))
335       (if message-id (insert message-id))
336       ;; Fold long References lines to conform to RFC1036 (sort of).
337       ;; The region must end with a newline to fill the region
338       ;; without inserting extra newline.
339       (fill-region-as-paragraph begin (1+ (point))))))
340
341 (defun nnheader-replace-header (header new-value)
342   "Remove HEADER and insert the NEW-VALUE."
343   (save-excursion
344     (save-restriction
345       (nnheader-narrow-to-headers)
346       (prog1
347           (message-remove-header header)
348         (goto-char (point-max))
349         (insert header ": " new-value "\n")))))
350
351 (defun nnheader-narrow-to-headers ()
352   "Narrow to the head of an article."
353   (widen)
354   (narrow-to-region
355    (goto-char (point-min))
356    (if (search-forward "\n\n" nil t)
357        (1- (point))
358      (point-max)))
359   (goto-char (point-min)))
360
361 (defun nnheader-set-temp-buffer (name)
362   "Set-buffer to an empty (possibly new) buffer called NAME with undo disabled."
363   (set-buffer (get-buffer-create name))
364   (buffer-disable-undo (current-buffer))
365   (erase-buffer)
366   (current-buffer))
367
368 (defmacro nnheader-temp-write (file &rest forms)
369   "Create a new buffer, evaluate FORM there, and write the buffer to FILE."
370   `(save-excursion
371      (let ((nnheader-temp-file ,file)
372            (nnheader-temp-cur-buffer
373             (nnheader-set-temp-buffer
374              (generate-new-buffer-name " *nnheader temp*"))))
375        (when (and nnheader-temp-file 
376                   (not (file-directory-p (file-name-directory 
377                                           nnheader-temp-file))))
378          (make-directory (file-name-directory nnheader-temp-file) t))
379        (unwind-protect
380            (prog1
381                (progn
382                  ,@forms)
383              (when nnheader-temp-file
384                (set-buffer nnheader-temp-cur-buffer)
385                (write-region (point-min) (point-max) 
386                              nnheader-temp-file nil 'nomesg)))
387          (when (buffer-name nnheader-temp-cur-buffer)
388            (kill-buffer nnheader-temp-cur-buffer))))))
389
390 (put 'nnheader-temp-write 'lisp-indent-function 1)
391 (put 'nnheader-temp-write 'lisp-indent-hook 1)
392 (put 'nnheader-temp-write 'edebug-form-spec '(file &rest form))
393
394 (defvar jka-compr-compression-info-list)
395 (defvar nnheader-numerical-files
396   (if (boundp 'jka-compr-compression-info-list)
397       (concat "\\([0-9]+\\)\\(" 
398               (mapconcat (lambda (i) (aref i 0))
399                          jka-compr-compression-info-list "\\|")
400               "\\)?")
401     "[0-9]+$")
402   "Regexp that match numerical files.")
403
404 (defvar nnheader-numerical-short-files (concat "^" nnheader-numerical-files)
405   "Regexp that matches numerical file names.")
406
407 (defvar nnheader-numerical-full-files (concat "/" nnheader-numerical-files)
408   "Regexp that matches numerical full file paths.")
409
410 (defsubst nnheader-file-to-number (file)
411   "Take a file name and return the article number."
412   (if (not (boundp 'jka-compr-compression-info-list))
413       (string-to-int file)
414     (string-match nnheader-numerical-short-files file)
415     (string-to-int (match-string 0 file))))
416
417 (defun nnheader-directory-articles (dir)
418   "Return a list of all article files in a directory."
419   (mapcar 'nnheader-file-to-number
420           (directory-files dir nil nnheader-numerical-short-files t)))
421
422 (defun nnheader-article-to-file-alist (dir)
423   "Return an alist of article/file pairs in DIR."
424   (mapcar (lambda (file) (cons (nnheader-file-to-number file) file))
425           (directory-files dir nil nnheader-numerical-short-files t)))
426
427 (defun nnheader-fold-continuation-lines ()
428   "Fold continuation lines in the current buffer."
429   (goto-char (point-min))
430   (while (re-search-forward "\\(\r?\n[ \t]+\\)+" nil t)
431     (replace-match " " t t)))
432
433 (defun nnheader-translate-file-chars (file)
434   (if (null nnheader-file-name-translation-alist)
435       ;; No translation is necessary.
436       file 
437     ;; We translate -- but only the file name.  We leave the directory
438     ;; alone.
439     (let* ((new (file-name-nondirectory file))
440            (len (length new))
441            (i 0)
442           trans)
443       (while (< i len)
444         (when (setq trans (cdr (assq (aref new i)
445                                      nnheader-file-name-translation-alist)))
446           (aset new i trans))
447         (incf i))
448       (concat (file-name-directory file) new))))
449
450 (defun nnheader-report (backend &rest args)
451   "Report an error from the BACKEND.
452 The first string in ARGS can be a format string."
453   (set (intern (format "%s-status-string" backend))
454        (if (< (length args) 2)
455            (car args)
456          (apply 'format args)))
457   nil)
458
459 (defun nnheader-get-report (backend)
460   (message "%s" (symbol-value (intern (format "%s-status-string" backend)))))
461
462 (defun nnheader-insert (format &rest args)
463   "Clear the communicaton buffer and insert FORMAT and ARGS into the buffer.
464 If FORMAT isn't a format string, it and all ARGS will be inserted
465 without formatting."
466   (save-excursion
467     (set-buffer nntp-server-buffer)
468     (erase-buffer)
469     (if (string-match "%" format)
470         (insert (apply 'format format args))
471       (apply 'insert format args))
472     t))
473
474 (defun nnheader-mail-file-mbox-p (file)
475   "Say whether FILE looks like an Unix mbox file."
476   (when (and (file-exists-p file)
477              (file-readable-p file)
478              (file-regular-p file))
479     (save-excursion
480       (nnheader-set-temp-buffer " *mail-file-mbox-p*")
481       (nnheader-insert-file-contents-literally file)
482       (goto-char (point-min))
483       (prog1
484           (looking-at message-unix-mail-delimiter)
485         (kill-buffer (current-buffer))))))
486
487 (defun nnheader-replace-chars-in-string (string from to)
488   "Replace characters in STRING from FROM to TO."
489   (let ((string (substring string 0))   ;Copy string.
490         (len (length string))
491         (idx 0))
492     ;; Replace all occurrences of FROM with TO.
493     (while (< idx len)
494       (if (= (aref string idx) from)
495           (aset string idx to))
496       (setq idx (1+ idx)))
497     string))
498
499 (defun nnheader-file-to-group (file &optional top)
500   "Return a group name based on FILE and TOP."
501   (nnheader-replace-chars-in-string 
502    (if (not top)
503        file
504      (condition-case ()
505          (substring (expand-file-name file)
506                     (length 
507                      (expand-file-name
508                       (file-name-as-directory top))))
509        (error "")))
510    ?/ ?.))
511
512 (defun nnheader-message (level &rest args)
513   "Message if the Gnus backends are talkative."
514   (if (or (not (numberp gnus-verbose-backends))
515           (<= level gnus-verbose-backends))
516       (apply 'message args)
517     (apply 'format args)))
518
519 (defun nnheader-be-verbose (level)
520   "Return whether the backends should be verbose on LEVEL."
521   (or (not (numberp gnus-verbose-backends))
522       (<= level gnus-verbose-backends)))
523
524 (defun nnheader-group-pathname (group dir &optional file)
525   "Make pathname for GROUP."
526   (concat
527    (let ((dir (file-name-as-directory (expand-file-name dir))))
528      ;; If this directory exists, we use it directly.
529      (if (file-directory-p (concat dir group))
530          (concat dir group "/")
531        ;; If not, we translate dots into slashes.
532        (concat dir (nnheader-replace-chars-in-string group ?. ?/) "/")))
533    (cond ((null file) "")
534          ((numberp file) (int-to-string file))
535          (t file))))
536
537 (defun nnheader-functionp (form)
538   "Return non-nil if FORM is funcallable."
539   (or (and (symbolp form) (fboundp form))
540       (and (listp form) (eq (car form) 'lambda))))
541
542 (defun nnheader-concat (dir file)
543   "Concat DIR as directory to FILE."
544   (concat (file-name-as-directory dir) file))
545
546 (require 'nnheaderems)
547
548 (run-hooks 'nnheader-load-hook)
549
550 (provide 'nnheader)
551
552 ;;; nnheader.el ends here