Synch with Oort Gnus.
[elisp/gnus.git-] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Semi-gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001
3 ;;        Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
7 ;; Keywords: mail, news, MIME
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
24 ;; Boston, MA 02111-1307, USA.
25
26 ;;; Commentary:
27
28 ;; Nothing in this file depends on any other parts of Gnus -- all
29 ;; functions and macros in this file are utility functions that are
30 ;; used by Gnus and may be used by any other package without loading
31 ;; Gnus first.
32
33 ;;; Code:
34
35 (eval-when-compile
36   (require 'cl)
37   ;; Fixme: this should be a gnus variable, not nnmail-.
38   (defvar nnmail-pathname-coding-system))
39 (eval-when-compile (require 'static))
40
41 (require 'custom)
42 (require 'nnheader)
43 (require 'time-date)
44
45 (eval-and-compile
46   (autoload 'message-fetch-field "message")
47   (autoload 'rmail-insert-rmail-file-header "rmail")
48   (autoload 'rmail-count-new-messages "rmail")
49   (autoload 'rmail-show-message "rmail"))
50
51 (defun gnus-boundp (variable)
52   "Return non-nil if VARIABLE is bound and non-nil."
53   (and (boundp variable)
54        (symbol-value variable)))
55
56 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
57   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
58   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
59         (w (make-symbol "w"))
60         (buf (make-symbol "buf"))
61         (frame (make-symbol "frame")))
62     `(let* ((,tempvar (selected-window))
63             (,buf ,buffer)
64             (,w (get-buffer-window ,buf 'visible))
65             ,frame)
66        (unwind-protect
67            (progn
68              (if ,w
69                  (progn
70                    (select-window ,w)
71                    (set-buffer (window-buffer ,w)))
72                (pop-to-buffer ,buf))
73              ,@forms)
74          (setq ,frame (selected-frame))
75          (select-window ,tempvar)
76          (select-frame ,frame)))))
77
78 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
79 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
80
81 (defmacro gnus-intern-safe (string hashtable)
82   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
83   `(let ((symbol (intern ,string ,hashtable)))
84      (or (boundp symbol)
85          (set symbol nil))
86      symbol))
87
88 ;; Avoid byte-compile warning.
89 ;; In Mule, this function will be redefined to `truncate-string',
90 ;; which takes 3 or 4 args.
91 (defun gnus-truncate-string (str width &rest ignore)
92   (substring str 0 width))
93
94 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
95 ;; to limit the length of a string.  This function is necessary since
96 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
97 (defsubst gnus-limit-string (str width)
98   (if (> (length str) width)
99       (substring str 0 width)
100     str))
101
102 (defsubst gnus-functionp (form)
103   "Return non-nil if FORM is funcallable."
104   (or (and (symbolp form) (fboundp form))
105       (and (listp form) (eq (car form) 'lambda))
106       (byte-code-function-p form)))
107
108 (defsubst gnus-goto-char (point)
109   (and point (goto-char point)))
110
111 (defmacro gnus-buffer-exists-p (buffer)
112   `(let ((buffer ,buffer))
113      (when buffer
114        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
115                 buffer))))
116
117 (defmacro gnus-kill-buffer (buffer)
118   `(let ((buf ,buffer))
119      (when (gnus-buffer-exists-p buf)
120        (kill-buffer buf))))
121
122 (static-cond
123  ((fboundp 'point-at-bol)
124   (defalias 'gnus-point-at-bol 'point-at-bol))
125  ((fboundp 'line-beginning-position)
126   (defalias 'gnus-point-at-bol 'line-beginning-position))
127  (t
128   (defun gnus-point-at-bol ()
129     "Return point at the beginning of the line."
130     (let ((p (point)))
131       (beginning-of-line)
132       (prog1
133           (point)
134         (goto-char p))))
135   ))
136 (static-cond
137  ((fboundp 'point-at-eol)
138   (defalias 'gnus-point-at-eol 'point-at-eol))
139  ((fboundp 'line-end-position)
140   (defalias 'gnus-point-at-eol 'line-end-position))
141  (t
142   (defun gnus-point-at-eol ()
143     "Return point at the end of the line."
144     (let ((p (point)))
145       (end-of-line)
146       (prog1
147           (point)
148         (goto-char p))))
149   ))
150
151 (defun gnus-delete-first (elt list)
152   "Delete by side effect the first occurrence of ELT as a member of LIST."
153   (if (equal (car list) elt)
154       (cdr list)
155     (let ((total list))
156       (while (and (cdr list)
157                   (not (equal (cadr list) elt)))
158         (setq list (cdr list)))
159       (when (cdr list)
160         (setcdr list (cddr list)))
161       total)))
162
163 ;; Delete the current line (and the next N lines).
164 (defmacro gnus-delete-line (&optional n)
165   `(delete-region (progn (beginning-of-line) (point))
166                   (progn (forward-line ,(or n 1)) (point))))
167
168 (defun gnus-byte-code (func)
169   "Return a form that can be `eval'ed based on FUNC."
170   (let ((fval (indirect-function func)))
171     (if (byte-code-function-p fval)
172         (let ((flist (append fval nil)))
173           (setcar flist 'byte-code)
174           flist)
175       (cons 'progn (cddr fval)))))
176
177 (defun gnus-extract-address-components (from)
178   (let (name address)
179     ;; First find the address - the thing with the @ in it.  This may
180     ;; not be accurate in mail addresses, but does the trick most of
181     ;; the time in news messages.
182     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
183       (setq address (substring from (match-beginning 0) (match-end 0))))
184     ;; Then we check whether the "name <address>" format is used.
185     (and address
186          ;; Linear white space is not required.
187          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
188          (and (setq name (substring from 0 (match-beginning 0)))
189               ;; Strip any quotes from the name.
190               (string-match "\".*\"" name)
191               (setq name (substring name 1 (1- (match-end 0))))))
192     ;; If not, then "address (name)" is used.
193     (or name
194         (and (string-match "(.+)" from)
195              (setq name (substring from (1+ (match-beginning 0))
196                                    (1- (match-end 0)))))
197         (and (string-match "()" from)
198              (setq name address))
199         ;; XOVER might not support folded From headers.
200         (and (string-match "(.*" from)
201              (setq name (substring from (1+ (match-beginning 0))
202                                    (match-end 0)))))
203     (list (if (string= name "") nil name) (or address from))))
204
205
206 (defun gnus-fetch-field (field)
207   "Return the value of the header FIELD of current article."
208   (save-excursion
209     (save-restriction
210       (let ((case-fold-search t)
211             (inhibit-point-motion-hooks t))
212         (nnheader-narrow-to-headers)
213         (message-fetch-field field)))))
214
215 (defun gnus-goto-colon ()
216   (beginning-of-line)
217   (let ((eol (gnus-point-at-eol)))
218     (goto-char (or (text-property-any (point) eol 'gnus-position t)
219                    (search-forward ":" eol t)
220                    (point)))))
221
222 (defun gnus-remove-text-with-property (prop)
223   "Delete all text in the current buffer with text property PROP."
224   (save-excursion
225     (goto-char (point-min))
226     (while (not (eobp))
227       (while (get-text-property (point) prop)
228         (delete-char 1))
229       (goto-char (next-single-property-change (point) prop nil (point-max))))))
230
231 (require 'nnheader)
232 (defun gnus-newsgroup-directory-form (newsgroup)
233   "Make hierarchical directory name from NEWSGROUP name."
234   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
235          (idx (string-match ":" newsgroup)))
236     (concat
237      (if idx (substring newsgroup 0 idx))
238      (if idx "/")
239      (nnheader-replace-chars-in-string
240       (if idx (substring newsgroup (1+ idx)) newsgroup)
241       ?. ?/))))
242
243 (defun gnus-newsgroup-savable-name (group)
244   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
245   ;; with dots.
246   (nnheader-replace-chars-in-string group ?/ ?.))
247
248 (defun gnus-string> (s1 s2)
249   (not (or (string< s1 s2)
250            (string= s1 s2))))
251
252 ;;; Time functions.
253
254 (defun gnus-file-newer-than (file date)
255   (let ((fdate (nth 5 (file-attributes file))))
256     (or (> (car fdate) (car date))
257         (and (= (car fdate) (car date))
258              (> (nth 1 fdate) (nth 1 date))))))
259
260 ;;; Keymap macros.
261
262 (defmacro gnus-local-set-keys (&rest plist)
263   "Set the keys in PLIST in the current keymap."
264   `(gnus-define-keys-1 (current-local-map) ',plist))
265
266 (defmacro gnus-define-keys (keymap &rest plist)
267   "Define all keys in PLIST in KEYMAP."
268   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
269
270 (defmacro gnus-define-keys-safe (keymap &rest plist)
271   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
272   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
273
274 (put 'gnus-define-keys 'lisp-indent-function 1)
275 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
276 (put 'gnus-local-set-keys 'lisp-indent-function 1)
277
278 (defmacro gnus-define-keymap (keymap &rest plist)
279   "Define all keys in PLIST in KEYMAP."
280   `(gnus-define-keys-1 ,keymap (quote ,plist)))
281
282 (put 'gnus-define-keymap 'lisp-indent-function 1)
283
284 (defun gnus-define-keys-1 (keymap plist &optional safe)
285   (when (null keymap)
286     (error "Can't set keys in a null keymap"))
287   (cond ((symbolp keymap)
288          (setq keymap (symbol-value keymap)))
289         ((keymapp keymap))
290         ((listp keymap)
291          (set (car keymap) nil)
292          (define-prefix-command (car keymap))
293          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
294          (setq keymap (symbol-value (car keymap)))))
295   (let (key)
296     (while plist
297       (when (symbolp (setq key (pop plist)))
298         (setq key (symbol-value key)))
299       (if (or (not safe)
300               (eq (lookup-key keymap key) 'undefined))
301           (define-key keymap key (pop plist))
302         (pop plist)))))
303
304 (defun gnus-completing-read (default prompt &rest args)
305   ;; Like `completing-read', except that DEFAULT is the default argument.
306   (let* ((prompt (if default
307                      (concat prompt " (default " default ") ")
308                    (concat prompt " ")))
309          (answer (apply 'completing-read prompt args)))
310     (if (or (null answer) (zerop (length answer)))
311         default
312       answer)))
313
314 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
315 ;; the echo area.
316 (defun gnus-y-or-n-p (prompt)
317   (prog1
318       (y-or-n-p prompt)
319     (message "")))
320
321 (defun gnus-yes-or-no-p (prompt)
322   (prog1
323       (yes-or-no-p prompt)
324     (message "")))
325
326 (defun gnus-dd-mmm (messy-date)
327   "Return a string like DD-MMM from a big messy string."
328   (condition-case ()
329       (format-time-string "%d-%b" (safe-date-to-time messy-date))
330     (error "  -   ")))
331
332 (defmacro gnus-date-get-time (date)
333   "Convert DATE string to Emacs time.
334 Cache the result as a text property stored in DATE."
335   ;; Either return the cached value...
336   `(let ((d ,date))
337      (if (equal "" d)
338          '(0 0)
339        (or (get-text-property 0 'gnus-time d)
340            ;; or compute the value...
341            (let ((time (safe-date-to-time d)))
342              ;; and store it back in the string.
343              (put-text-property 0 1 'gnus-time time d)
344              time)))))
345
346 (defsubst gnus-time-iso8601 (time)
347   "Return a string of TIME in YYYYMMDDTHHMMSS format."
348   (format-time-string "%Y%m%dT%H%M%S" time))
349
350 (defun gnus-date-iso8601 (date)
351   "Convert the DATE to YYYYMMDDTHHMMSS."
352   (condition-case ()
353       (gnus-time-iso8601 (gnus-date-get-time date))
354     (error "")))
355
356 (defun gnus-mode-string-quote (string)
357   "Quote all \"%\"'s in STRING."
358   (save-excursion
359     (gnus-set-work-buffer)
360     (insert string)
361     (goto-char (point-min))
362     (while (search-forward "%" nil t)
363       (insert "%"))
364     (buffer-string)))
365
366 ;; Make a hash table (default and minimum size is 256).
367 ;; Optional argument HASHSIZE specifies the table size.
368 (defun gnus-make-hashtable (&optional hashsize)
369   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
370
371 ;; Make a number that is suitable for hashing; bigger than MIN and
372 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
373 ;; hardware modulo operation, so they implement it in software.  On
374 ;; many sparcs over 50% of the time to intern is spent in the modulo.
375 ;; Yes, it's slower than actually computing the hash from the string!
376 ;; So we use powers of 2 so people can optimize the modulo to a mask.
377 (defun gnus-create-hash-size (min)
378   (let ((i 1))
379     (while (< i min)
380       (setq i (* 2 i)))
381     i))
382
383 (defcustom gnus-verbose 7
384   "*Integer that says how verbose Gnus should be.
385 The higher the number, the more messages Gnus will flash to say what
386 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
387 display most important messages; and at ten, Gnus will keep on
388 jabbering all the time."
389   :group 'gnus-start
390   :type 'integer)
391
392 ;; Show message if message has a lower level than `gnus-verbose'.
393 ;; Guideline for numbers:
394 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
395 ;; for things that take a long time, 7 - not very important messages
396 ;; on stuff, 9 - messages inside loops.
397 (defun gnus-message (level &rest args)
398   (if (<= level gnus-verbose)
399       (apply 'message args)
400     ;; We have to do this format thingy here even if the result isn't
401     ;; shown - the return value has to be the same as the return value
402     ;; from `message'.
403     (apply 'format args)))
404
405 (defun gnus-error (level &rest args)
406   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
407   (when (<= (floor level) gnus-verbose)
408     (apply 'message args)
409     (ding)
410     (let (duration)
411       (when (and (floatp level)
412                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
413         (sit-for duration))))
414   nil)
415
416 (defun gnus-split-references (references)
417   "Return a list of Message-IDs in REFERENCES."
418   (let ((beg 0)
419         ids)
420     (while (string-match "<[^> \t]+>" references beg)
421       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
422             ids))
423     (nreverse ids)))
424
425 (defsubst gnus-parent-id (references &optional n)
426   "Return the last Message-ID in REFERENCES.
427 If N, return the Nth ancestor instead."
428   (when references
429     (let ((ids (inline (gnus-split-references references))))
430       (while (nthcdr (or n 1) ids)
431         (setq ids (cdr ids)))
432       (car ids))))
433
434 (defsubst gnus-buffer-live-p (buffer)
435   "Say whether BUFFER is alive or not."
436   (and buffer
437        (get-buffer buffer)
438        (buffer-name (get-buffer buffer))))
439
440 (defun gnus-horizontal-recenter ()
441   "Recenter the current buffer horizontally."
442   (if (< (current-column) (/ (window-width) 2))
443       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
444     (let* ((orig (point))
445            (end (window-end (get-buffer-window (current-buffer) t)))
446            (max 0))
447       (when end
448         ;; Find the longest line currently displayed in the window.
449         (goto-char (window-start))
450         (while (and (not (eobp))
451                     (< (point) end))
452           (end-of-line)
453           (setq max (max max (current-column)))
454           (forward-line 1))
455         (goto-char orig)
456         ;; Scroll horizontally to center (sort of) the point.
457         (if (> max (window-width))
458             (set-window-hscroll
459              (get-buffer-window (current-buffer) t)
460              (min (- (current-column) (/ (window-width) 3))
461                   (+ 2 (- max (window-width)))))
462           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
463         max))))
464
465 (defun gnus-read-event-char ()
466   "Get the next event."
467   (let ((event (read-event)))
468     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
469     (cons (and (numberp event) event) event)))
470
471 (defun gnus-sortable-date (date)
472   "Make string suitable for sorting from DATE."
473   (gnus-time-iso8601 (date-to-time date)))
474
475 (defun gnus-copy-file (file &optional to)
476   "Copy FILE to TO."
477   (interactive
478    (list (read-file-name "Copy file: " default-directory)
479          (read-file-name "Copy file to: " default-directory)))
480   (unless to
481     (setq to (read-file-name "Copy file to: " default-directory)))
482   (when (file-directory-p to)
483     (setq to (concat (file-name-as-directory to)
484                      (file-name-nondirectory file))))
485   (copy-file file to))
486
487 (defvar gnus-work-buffer " *gnus work*")
488
489 (defun gnus-set-work-buffer ()
490   "Put point in the empty Gnus work buffer."
491   (if (get-buffer gnus-work-buffer)
492       (progn
493         (set-buffer gnus-work-buffer)
494         (erase-buffer))
495     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
496     (kill-all-local-variables)))
497
498 (defmacro gnus-group-real-name (group)
499   "Find the real name of a foreign newsgroup."
500   `(let ((gname ,group))
501      (if (string-match "^[^:]+:" gname)
502          (substring gname (match-end 0))
503        gname)))
504
505 (defun gnus-make-sort-function (funs)
506   "Return a composite sort condition based on the functions in FUNC."
507   (cond
508    ;; Just a simple function.
509    ((gnus-functionp funs) funs)
510    ;; No functions at all.
511    ((null funs) funs)
512    ;; A list of functions.
513    ((or (cdr funs)
514         (listp (car funs)))
515     (gnus-byte-compile
516      `(lambda (t1 t2)
517         ,(gnus-make-sort-function-1 (reverse funs)))))
518    ;; A list containing just one function.
519    (t
520     (car funs))))
521
522 (defun gnus-make-sort-function-1 (funs)
523   "Return a composite sort condition based on the functions in FUNC."
524   (let ((function (car funs))
525         (first 't1)
526         (last 't2))
527     (when (consp function)
528       (cond
529        ;; Reversed spec.
530        ((eq (car function) 'not)
531         (setq function (cadr function)
532               first 't2
533               last 't1))
534        ((gnus-functionp function)
535         ;; Do nothing.
536         )
537        (t
538         (error "Invalid sort spec: %s" function))))
539     (if (cdr funs)
540         `(or (,function ,first ,last)
541              (and (not (,function ,last ,first))
542                   ,(gnus-make-sort-function-1 (cdr funs))))
543       `(,function ,first ,last))))
544
545 (defun gnus-turn-off-edit-menu (type)
546   "Turn off edit menu in `gnus-TYPE-mode-map'."
547   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
548     [menu-bar edit] 'undefined))
549
550 (defun gnus-prin1 (form)
551   "Use `prin1' on FORM in the current buffer.
552 Bind `print-quoted' and `print-readably' to t while printing."
553   (let ((print-quoted t)
554         (print-readably t)
555         (print-escape-multibyte nil)
556         print-level print-length)
557     (prin1 form (current-buffer))))
558
559 (defun gnus-prin1-to-string (form)
560   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
561   (let ((print-quoted t)
562         (print-readably t))
563     (prin1-to-string form)))
564
565 (defun gnus-make-directory (directory)
566   "Make DIRECTORY (and all its parents) if it doesn't exist."
567   (require 'nnmail)
568   (let ((file-name-coding-system nnmail-pathname-coding-system)
569         (pathname-coding-system nnmail-pathname-coding-system))
570     (when (and directory
571                (not (file-exists-p directory)))
572       (make-directory directory t)))
573   t)
574
575 (defun gnus-write-buffer (file)
576   "Write the current buffer's contents to FILE."
577   ;; Make sure the directory exists.
578   (gnus-make-directory (file-name-directory file))
579   (let ((file-name-coding-system nnmail-pathname-coding-system)
580         (pathname-coding-system nnmail-pathname-coding-system))
581     ;; Write the buffer.
582     (write-region (point-min) (point-max) file nil 'quietly)))
583
584 (defun gnus-write-buffer-as-binary (file)
585   "Write the current buffer's contents to FILE without code conversion."
586   ;; Make sure the directory exists.
587   (gnus-make-directory (file-name-directory file))
588   ;; Write the buffer.
589   (write-region-as-binary (point-min) (point-max) file nil 'quietly))
590
591 (defun gnus-write-buffer-as-coding-system (coding-system file)
592   "Write the current buffer's contents to FILE with code conversion."
593   ;; Make sure the directory exists.
594   (gnus-make-directory (file-name-directory file))
595   ;; Write the buffer.
596   (write-region-as-coding-system
597    coding-system (point-min) (point-max) file nil 'quietly))
598
599 (defun gnus-delete-file (file)
600   "Delete FILE if it exists."
601   (when (file-exists-p file)
602     (delete-file file)))
603
604 (defun gnus-strip-whitespace (string)
605   "Return STRING stripped of all whitespace."
606   (while (string-match "[\r\n\t ]+" string)
607     (setq string (replace-match "" t t string)))
608   string)
609
610 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
611   "The same as `put-text-property', but don't put this prop on any newlines in the region."
612   (save-match-data
613     (save-excursion
614       (save-restriction
615         (goto-char beg)
616         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
617           (gnus-put-text-property beg (match-beginning 0) prop val)
618           (setq beg (point)))
619         (gnus-put-text-property beg (point) prop val)))))
620
621 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
622                                                                    prop val)
623   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
624   (let ((b beg))
625     (while (/= b end)
626       (when (get-text-property b 'gnus-face)
627         (setq b (next-single-property-change b 'gnus-face nil end)))
628       (when (/= b end)
629         (gnus-put-text-property
630          b (setq b (next-single-property-change b 'gnus-face nil end))
631          prop val)))))
632
633 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
634 ;;; The primary idea here is to try to protect internal datastructures
635 ;;; from becoming corrupted when the user hits C-g, or if a hook or
636 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
637 ;;; updated at the same time, or information can be lost.
638
639 (defvar gnus-atomic-be-safe t
640   "If t, certain operations will be protected from interruption by C-g.")
641
642 (defmacro gnus-atomic-progn (&rest forms)
643   "Evaluate FORMS atomically, which means to protect the evaluation
644 from being interrupted by the user.  An error from the forms themselves
645 will return without finishing the operation.  Since interrupts from
646 the user are disabled, it is recommended that only the most minimal
647 operations are performed by FORMS.  If you wish to assign many
648 complicated values atomically, compute the results into temporary
649 variables and then do only the assignment atomically."
650   `(let ((inhibit-quit gnus-atomic-be-safe))
651      ,@forms))
652
653 (put 'gnus-atomic-progn 'lisp-indent-function 0)
654
655 (defmacro gnus-atomic-progn-assign (protect &rest forms)
656   "Evaluate FORMS, but insure that the variables listed in PROTECT
657 are not changed if anything in FORMS signals an error or otherwise
658 non-locally exits.  The variables listed in PROTECT are updated atomically.
659 It is safe to use gnus-atomic-progn-assign with long computations.
660
661 Note that if any of the symbols in PROTECT were unbound, they will be
662 set to nil on a sucessful assignment.  In case of an error or other
663 non-local exit, it will still be unbound."
664   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
665                                                   (concat (symbol-name x)
666                                                           "-tmp"))
667                                                  x))
668                                protect))
669          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
670                                temp-sym-map))
671          (temp-sym-let (mapcar (lambda (x) (list (car x)
672                                                  `(and (boundp ',(cadr x))
673                                                        ,(cadr x))))
674                                temp-sym-map))
675          (sym-temp-let sym-temp-map)
676          (temp-sym-assign (apply 'append temp-sym-map))
677          (sym-temp-assign (apply 'append sym-temp-map))
678          (result (make-symbol "result-tmp")))
679     `(let (,@temp-sym-let
680            ,result)
681        (let ,sym-temp-let
682          (setq ,result (progn ,@forms))
683          (setq ,@temp-sym-assign))
684        (let ((inhibit-quit gnus-atomic-be-safe))
685          (setq ,@sym-temp-assign))
686        ,result)))
687
688 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
689 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
690
691 (defmacro gnus-atomic-setq (&rest pairs)
692   "Similar to setq, except that the real symbols are only assigned when
693 there are no errors.  And when the real symbols are assigned, they are
694 done so atomically.  If other variables might be changed via side-effect,
695 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
696 with potentially long computations."
697   (let ((tpairs pairs)
698         syms)
699     (while tpairs
700       (push (car tpairs) syms)
701       (setq tpairs (cddr tpairs)))
702     `(gnus-atomic-progn-assign ,syms
703        (setq ,@pairs))))
704
705 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
706
707
708 ;;; Functions for saving to babyl/mail files.
709
710 (defvar rmail-default-rmail-file)
711 (defun gnus-output-to-rmail (filename &optional ask)
712   "Append the current article to an Rmail file named FILENAME."
713   (require 'rmail)
714   ;; Most of these codes are borrowed from rmailout.el.
715   (setq filename (expand-file-name filename))
716   (setq rmail-default-rmail-file filename)
717   (let ((artbuf (current-buffer))
718         (tmpbuf (get-buffer-create " *Gnus-output*")))
719     (save-excursion
720       (or (get-file-buffer filename)
721           (file-exists-p filename)
722           (if (or (not ask)
723                   (gnus-yes-or-no-p
724                    (concat "\"" filename "\" does not exist, create it? ")))
725               (let ((file-buffer (create-file-buffer filename)))
726                 (save-excursion
727                   (set-buffer file-buffer)
728                   (rmail-insert-rmail-file-header)
729                   (let ((require-final-newline nil))
730                     (gnus-write-buffer-as-coding-system
731                      nnheader-text-coding-system filename)))
732                 (kill-buffer file-buffer))
733             (error "Output file does not exist")))
734       (set-buffer tmpbuf)
735       (erase-buffer)
736       (insert-buffer-substring artbuf)
737       (gnus-convert-article-to-rmail)
738       ;; Decide whether to append to a file or to an Emacs buffer.
739       (let ((outbuf (get-file-buffer filename)))
740         (if (not outbuf)
741             (let ((file-name-coding-system nnmail-pathname-coding-system)
742                   (pathname-coding-system nnmail-pathname-coding-system))
743               (write-region-as-binary (point-min) (point-max)
744                                       filename 'append))
745           ;; File has been visited, in buffer OUTBUF.
746           (set-buffer outbuf)
747           (let ((buffer-read-only nil)
748                 (msg (and (boundp 'rmail-current-message)
749                           (symbol-value 'rmail-current-message))))
750             ;; If MSG is non-nil, buffer is in RMAIL mode.
751             (when msg
752               (widen)
753               (narrow-to-region (point-max) (point-max)))
754             (insert-buffer-substring tmpbuf)
755             (when msg
756               (goto-char (point-min))
757               (widen)
758               (search-backward "\n\^_")
759               (narrow-to-region (point) (point-max))
760               (rmail-count-new-messages t)
761               (when (rmail-summary-exists)
762                 (rmail-select-summary
763                  (rmail-update-summary)))
764               (rmail-count-new-messages t)
765               (rmail-show-message msg))
766             (save-buffer)))))
767     (kill-buffer tmpbuf)))
768
769 (defun gnus-output-to-mail (filename &optional ask)
770   "Append the current article to a mail file named FILENAME."
771   (setq filename (expand-file-name filename))
772   (let ((artbuf (current-buffer))
773         (tmpbuf (get-buffer-create " *Gnus-output*")))
774     (save-excursion
775       ;; Create the file, if it doesn't exist.
776       (when (and (not (get-file-buffer filename))
777                  (not (file-exists-p filename)))
778         (if (or (not ask)
779                 (gnus-y-or-n-p
780                  (concat "\"" filename "\" does not exist, create it? ")))
781             (let ((file-buffer (create-file-buffer filename)))
782               (save-excursion
783                 (set-buffer file-buffer)
784                 (let ((require-final-newline nil))
785                   (gnus-write-buffer-as-coding-system
786                    nnheader-text-coding-system filename)))
787               (kill-buffer file-buffer))
788           (error "Output file does not exist")))
789       (set-buffer tmpbuf)
790       (erase-buffer)
791       (insert-buffer-substring artbuf)
792       (goto-char (point-min))
793       (if (looking-at "From ")
794           (forward-line 1)
795         (insert "From nobody " (current-time-string) "\n"))
796       (let (case-fold-search)
797         (while (re-search-forward "^From " nil t)
798           (beginning-of-line)
799           (insert ">")))
800       ;; Decide whether to append to a file or to an Emacs buffer.
801       (let ((outbuf (get-file-buffer filename)))
802         (if (not outbuf)
803             (let ((buffer-read-only nil))
804               (save-excursion
805                 (goto-char (point-max))
806                 (forward-char -2)
807                 (unless (looking-at "\n\n")
808                   (goto-char (point-max))
809                   (unless (bolp)
810                     (insert "\n"))
811                   (insert "\n"))
812                 (goto-char (point-max))
813                 (let ((file-name-coding-system nnmail-pathname-coding-system)
814                       (pathname-coding-system nnmail-pathname-coding-system))
815                   (write-region-as-binary (point-min) (point-max)
816                                           filename 'append))))
817           ;; File has been visited, in buffer OUTBUF.
818           (set-buffer outbuf)
819           (let ((buffer-read-only nil))
820             (goto-char (point-max))
821             (unless (eobp)
822               (insert "\n"))
823             (insert "\n")
824             (insert-buffer-substring tmpbuf)))))
825     (kill-buffer tmpbuf)))
826
827 (defun gnus-convert-article-to-rmail ()
828   "Convert article in current buffer to Rmail message format."
829   (let ((buffer-read-only nil))
830     ;; Convert article directly into Babyl format.
831     (goto-char (point-min))
832     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
833     (while (search-forward "\n\^_" nil t) ;single char
834       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
835     (goto-char (point-max))
836     (insert "\^_")))
837
838 (defun gnus-map-function (funs arg)
839   "Applies the result of the first function in FUNS to the second, and so on.
840 ARG is passed to the first function."
841   (let ((myfuns funs))
842     (while myfuns
843       (setq arg (funcall (pop myfuns) arg)))
844     arg))
845
846 (defun gnus-run-hooks (&rest funcs)
847   "Does the same as `run-hooks', but saves excursion."
848   (let ((buf (current-buffer)))
849     (unwind-protect
850         (apply 'run-hooks funcs)
851       (set-buffer buf))))
852
853 ;;;
854 ;;; .netrc and .authinforc parsing
855 ;;;
856
857 (defun gnus-parse-netrc (file)
858   "Parse FILE and return an list of all entries in the file."
859   (when (file-exists-p file)
860     (with-temp-buffer
861       (let ((tokens '("machine" "default" "login"
862                       "password" "account" "macdef" "force"
863                       "port"))
864             alist elem result pair)
865         (insert-file-contents file)
866         (goto-char (point-min))
867         ;; Go through the file, line by line.
868         (while (not (eobp))
869           (narrow-to-region (point) (gnus-point-at-eol))
870           ;; For each line, get the tokens and values.
871           (while (not (eobp))
872             (skip-chars-forward "\t ")
873             ;; Skip lines that begin with a "#".
874             (if (eq (char-after) ?#)
875                 (goto-char (point-max))
876               (unless (eobp)
877                 (setq elem
878                       (if (= (following-char) ?\")
879                           (read (current-buffer))
880                         (buffer-substring
881                          (point) (progn (skip-chars-forward "^\t ")
882                                         (point)))))
883                 (cond
884                  ((equal elem "macdef")
885                   ;; We skip past the macro definition.
886                   (widen)
887                   (while (and (zerop (forward-line 1))
888                               (looking-at "$")))
889                   (narrow-to-region (point) (point)))
890                  ((member elem tokens)
891                   ;; Tokens that don't have a following value are ignored,
892                   ;; except "default".
893                   (when (and pair (or (cdr pair)
894                                       (equal (car pair) "default")))
895                     (push pair alist))
896                   (setq pair (list elem)))
897                  (t
898                   ;; Values that haven't got a preceding token are ignored.
899                   (when pair
900                     (setcdr pair elem)
901                     (push pair alist)
902                     (setq pair nil)))))))
903           (when alist
904             (push (nreverse alist) result))
905           (setq alist nil
906                 pair nil)
907           (widen)
908           (forward-line 1))
909         (nreverse result)))))
910
911 (defun gnus-netrc-machine (list machine &optional port defaultport)
912   "Return the netrc values from LIST for MACHINE or for the default entry.
913 If PORT specified, only return entries with matching port tokens.
914 Entries without port tokens default to DEFAULTPORT."
915   (let ((rest list)
916         result)
917     (while list
918       (when (equal (cdr (assoc "machine" (car list))) machine)
919         (push (car list) result))
920       (pop list))
921     (unless result
922       ;; No machine name matches, so we look for default entries.
923       (while rest
924         (when (assoc "default" (car rest))
925           (push (car rest) result))
926         (pop rest)))
927     (when result
928       (setq result (nreverse result))
929       (while (and result
930                   (not (equal (or port defaultport "nntp")
931                               (or (gnus-netrc-get (car result) "port")
932                                   defaultport "nntp"))))
933         (pop result))
934       (car result))))
935
936 (defun gnus-netrc-get (alist type)
937   "Return the value of token TYPE from ALIST."
938   (cdr (assoc type alist)))
939
940 ;;; Various
941
942 (defvar gnus-group-buffer)              ; Compiler directive
943 (defun gnus-alive-p ()
944   "Say whether Gnus is running or not."
945   (and (boundp 'gnus-group-buffer)
946        (get-buffer gnus-group-buffer)
947        (save-excursion
948          (set-buffer gnus-group-buffer)
949          (eq major-mode 'gnus-group-mode))))
950
951 (defun gnus-remove-duplicates (list)
952   (let (new (tail list))
953     (while tail
954       (or (member (car tail) new)
955           (setq new (cons (car tail) new)))
956       (setq tail (cdr tail)))
957     (nreverse new)))
958
959 (defun gnus-delete-if (predicate list)
960   "Delete elements from LIST that satisfy PREDICATE."
961   (let (out)
962     (while list
963       (unless (funcall predicate (car list))
964         (push (car list) out))
965       (pop list))
966     (nreverse out)))
967
968 (if (fboundp 'assq-delete-all)
969     (defalias 'gnus-delete-alist 'assq-delete-all)
970   (defun gnus-delete-alist (key alist)
971     "Delete from ALIST all elements whose car is KEY.
972 Return the modified alist."
973     (let (entry)
974       (while (setq entry (assq key alist))
975         (setq alist (delq entry alist)))
976       alist)))
977
978 (defmacro gnus-pull (key alist &optional assoc-p)
979   "Modify ALIST to be without KEY."
980   (unless (symbolp alist)
981     (error "Not a symbol: %s" alist))
982   (let ((fun (if assoc-p 'assoc 'assq)))
983     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
984
985 (defun gnus-globalify-regexp (re)
986   "Returns a regexp that matches a whole line, iff RE matches a part of it."
987   (concat (unless (string-match "^\\^" re) "^.*")
988           re
989           (unless (string-match "\\$$" re) ".*$")))
990
991 (defun gnus-set-window-start (&optional point)
992   "Set the window start to POINT, or (point) if nil."
993   (let ((win (get-buffer-window (current-buffer) t)))
994     (when win
995       (set-window-start win (or point (point))))))
996
997 (defun gnus-annotation-in-region-p (b e)
998   (if (= b e)
999       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1000     (text-property-any b e 'gnus-undeletable t)))
1001
1002 (defun gnus-or (&rest elems)
1003   "Return non-nil if any of the elements are non-nil."
1004   (catch 'found
1005     (while elems
1006       (when (pop elems)
1007         (throw 'found t)))))
1008
1009 (defun gnus-and (&rest elems)
1010   "Return non-nil if all of the elements are non-nil."
1011   (catch 'found
1012     (while elems
1013       (unless (pop elems)
1014         (throw 'found nil)))
1015     t))
1016
1017 (defun gnus-write-active-file (file hashtb &optional full-names)
1018   (let ((output-coding-system nnmail-active-file-coding-system)
1019         (coding-system-for-write nnmail-active-file-coding-system))
1020     (with-temp-file file
1021       (mapatoms
1022        (lambda (sym)
1023          (when (and sym
1024                     (boundp sym)
1025                     (symbol-value sym))
1026            (insert (format "%S %d %d y\n"
1027                            (if full-names
1028                                sym
1029                              (intern (gnus-group-real-name (symbol-name sym))))
1030                            (or (cdr (symbol-value sym))
1031                                (car (symbol-value sym)))
1032                            (car (symbol-value sym))))))
1033        hashtb)
1034       (goto-char (point-max))
1035       (while (search-backward "\\." nil t)
1036         (delete-char 1)))))
1037
1038 (if (fboundp 'union)
1039     (defalias 'gnus-union 'union)
1040   (defun gnus-union (l1 l2)
1041     "Set union of lists L1 and L2."
1042     (cond ((null l1) l2)
1043           ((null l2) l1)
1044           ((equal l1 l2) l1)
1045           (t
1046            (or (>= (length l1) (length l2))
1047                (setq l1 (prog1 l2 (setq l2 l1))))
1048            (while l2
1049              (or (member (car l2) l1)
1050                  (push (car l2) l1))
1051              (pop l2))
1052            l1))))
1053
1054 (defun gnus-add-text-properties-when
1055   (property value start end properties &optional object)
1056   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1057   (let (point)
1058     (while (and start
1059                 (< start end) ;; XEmacs will loop for every when start=end.
1060                 (setq point (text-property-not-all start end property value)))
1061       (gnus-add-text-properties start point properties object)
1062       (setq start (text-property-any point end property value)))
1063     (if start
1064         (gnus-add-text-properties start end properties object))))
1065
1066 (defun gnus-remove-text-properties-when
1067   (property value start end properties &optional object)
1068   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1069   (let (point)
1070     (while (and start
1071                 (< start end)
1072                 (setq point (text-property-not-all start end property value)))
1073       (remove-text-properties start point properties object)
1074       (setq start (text-property-any point end property value)))
1075     (if start
1076         (remove-text-properties start end properties object))
1077     t))
1078
1079 (defun gnus-string-equal (x y)
1080   "Like `string-equal', except it compares case-insensitively."
1081   (and (= (length x) (length y))
1082        (or (string-equal x y)
1083            (string-equal (downcase x) (downcase y)))))
1084
1085 (defcustom gnus-use-byte-compile t
1086   "If non-nil, byte-compile crucial run-time codes."
1087   :type 'boolean
1088   :version "21.1"
1089   :group 'gnus-various)
1090
1091 (defun gnus-byte-compile (form)
1092   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1093   (if gnus-use-byte-compile
1094       (progn
1095         (require 'bytecomp)
1096         (defalias 'gnus-byte-compile 'byte-compile)
1097         (byte-compile form))
1098     form))
1099
1100 (defun gnus-remassoc (key alist)
1101   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1102 The modified LIST is returned.  If the first member
1103 of LIST has a car that is `equal' to KEY, there is no way to remove it
1104 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1105 sure of changing the value of `foo'."
1106   (when alist
1107     (if (equal key (caar alist))
1108         (cdr alist)
1109       (setcdr alist (gnus-remassoc key (cdr alist)))
1110       alist)))
1111
1112 (defun gnus-update-alist-soft (key value alist)
1113   (if value
1114       (cons (cons key value) (gnus-remassoc key alist))
1115     (gnus-remassoc key alist)))
1116
1117 (defun gnus-create-info-command (node)
1118   "Create a command that will go to info NODE."
1119   `(lambda ()
1120      (interactive)
1121      ,(concat "Enter the info system at node " node)
1122      (Info-goto-node ,node)
1123      (setq gnus-info-buffer (current-buffer))
1124      (gnus-configure-windows 'info)))
1125
1126 (defun gnus-not-ignore (&rest args)
1127   t)
1128
1129 (provide 'gnus-util)
1130
1131 ;;; gnus-util.el ends here