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