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