1 ;;; gnus-util.el --- utility functions for Semi-gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002
3 ;; Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
7 ;; Keywords: mail, news, MIME
9 ;; This file is part of GNU Emacs.
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)
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.
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.
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
37 ;; Fixme: this should be a gnus variable, not nnmail-.
38 (defvar nnmail-pathname-coding-system))
39 (eval-when-compile (require 'static))
47 (autoload 'message-fetch-field "message")
48 (autoload 'gnus-get-buffer-window "gnus-win")
49 (autoload 'rmail-insert-rmail-file-header "rmail")
50 (autoload 'rmail-count-new-messages "rmail")
51 (autoload 'rmail-show-message "rmail"))
55 ((fboundp 'replace-in-string)
56 (defalias 'gnus-replace-in-string 'replace-in-string))
57 ((fboundp 'replace-regexp-in-string)
58 (defun gnus-replace-in-string (string regexp newtext &optional literal)
59 (replace-regexp-in-string regexp newtext string nil literal)))
61 (defun gnus-replace-in-string (string regexp newtext &optional literal)
63 (while (string-match regexp string start)
64 (setq tail (- (length string) (match-end 0)))
65 (setq string (replace-match newtext nil literal string))
66 (setq start (- (length string) tail))))
69 ;;; bring in the netrc functions as aliases
70 (defalias 'gnus-netrc-get 'netrc-get)
71 (defalias 'gnus-netrc-machine 'netrc-machine)
72 (defalias 'gnus-parse-netrc 'netrc-parse)
74 (defun gnus-boundp (variable)
75 "Return non-nil if VARIABLE is bound and non-nil."
76 (and (boundp variable)
77 (symbol-value variable)))
79 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
80 "Pop to BUFFER, evaluate FORMS, and then return to the original window."
81 (let ((tempvar (make-symbol "GnusStartBufferWindow"))
83 (buf (make-symbol "buf"))
84 (frame (make-symbol "frame")))
85 `(let* ((,tempvar (selected-window))
87 (,w (gnus-get-buffer-window ,buf 'visible))
94 (set-buffer (window-buffer ,w)))
97 (setq ,frame (selected-frame))
98 (select-window ,tempvar)
99 (select-frame ,frame)))))
101 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
102 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
104 (defmacro gnus-intern-safe (string hashtable)
105 "Set hash value. Arguments are STRING, VALUE, and HASHTABLE."
106 `(let ((symbol (intern ,string ,hashtable)))
111 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>. A safe way
112 ;; to limit the length of a string. This function is necessary since
113 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
114 (defsubst gnus-limit-string (str width)
115 (if (> (length str) width)
116 (substring str 0 width)
119 (defsubst gnus-functionp (form)
120 "Return non-nil if FORM is funcallable."
121 (or (and (symbolp form) (fboundp form))
122 (and (listp form) (eq (car form) 'lambda))
123 (byte-code-function-p form)))
125 (defsubst gnus-goto-char (point)
126 (and point (goto-char point)))
128 (defmacro gnus-buffer-exists-p (buffer)
129 `(let ((buffer ,buffer))
131 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
134 (defmacro gnus-kill-buffer (buffer)
135 `(let ((buf ,buffer))
136 (when (gnus-buffer-exists-p buf)
140 ((fboundp 'point-at-bol)
141 (defalias 'gnus-point-at-bol 'point-at-bol))
142 ((fboundp 'line-beginning-position)
143 (defalias 'gnus-point-at-bol 'line-beginning-position))
145 (defun gnus-point-at-bol ()
146 "Return point at the beginning of the line."
154 ((fboundp 'point-at-eol)
155 (defalias 'gnus-point-at-eol 'point-at-eol))
156 ((fboundp 'line-end-position)
157 (defalias 'gnus-point-at-eol 'line-end-position))
159 (defun gnus-point-at-eol ()
160 "Return point at the end of the line."
168 (defun gnus-delete-first (elt list)
169 "Delete by side effect the first occurrence of ELT as a member of LIST."
170 (if (equal (car list) elt)
173 (while (and (cdr list)
174 (not (equal (cadr list) elt)))
175 (setq list (cdr list)))
177 (setcdr list (cddr list)))
180 ;; Delete the current line (and the next N lines).
181 (defmacro gnus-delete-line (&optional n)
182 `(delete-region (progn (beginning-of-line) (point))
183 (progn (forward-line ,(or n 1)) (point))))
185 (defun gnus-byte-code (func)
186 "Return a form that can be `eval'ed based on FUNC."
187 (let ((fval (indirect-function func)))
188 (if (byte-code-function-p fval)
189 (let ((flist (append fval nil)))
190 (setcar flist 'byte-code)
192 (cons 'progn (cddr fval)))))
194 (defun gnus-extract-address-components (from)
196 ;; First find the address - the thing with the @ in it. This may
197 ;; not be accurate in mail addresses, but does the trick most of
198 ;; the time in news messages.
199 (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
200 (setq address (substring from (match-beginning 0) (match-end 0))))
201 ;; Then we check whether the "name <address>" format is used.
203 ;; Linear white space is not required.
204 (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
205 (and (setq name (substring from 0 (match-beginning 0)))
206 ;; Strip any quotes from the name.
207 (string-match "^\".*\"$" name)
208 (setq name (substring name 1 (1- (match-end 0))))))
209 ;; If not, then "address (name)" is used.
211 (and (string-match "(.+)" from)
212 (setq name (substring from (1+ (match-beginning 0))
213 (1- (match-end 0)))))
214 (and (string-match "()" from)
216 ;; XOVER might not support folded From headers.
217 (and (string-match "(.*" from)
218 (setq name (substring from (1+ (match-beginning 0))
220 (list (if (string= name "") nil name) (or address from))))
223 (defun gnus-fetch-field (field)
224 "Return the value of the header FIELD of current article."
227 (let ((case-fold-search t)
228 (inhibit-point-motion-hooks t))
229 (nnheader-narrow-to-headers)
230 (message-fetch-field field)))))
232 (defun gnus-goto-colon ()
234 (let ((eol (gnus-point-at-eol)))
235 (goto-char (or (text-property-any (point) eol 'gnus-position t)
236 (search-forward ":" eol t)
239 (defun gnus-decode-newsgroups (newsgroups group &optional method)
240 (let ((method (or method (gnus-find-method-for-group group))))
241 (mapconcat (lambda (group)
242 (gnus-group-name-decode group (gnus-group-name-charset
244 (message-tokenize-header newsgroups)
247 (defun gnus-remove-text-with-property (prop)
248 "Delete all text in the current buffer with text property PROP."
250 (goto-char (point-min))
252 (while (get-text-property (point) prop)
254 (goto-char (next-single-property-change (point) prop nil (point-max))))))
257 (defun gnus-newsgroup-directory-form (newsgroup)
258 "Make hierarchical directory name from NEWSGROUP name."
259 (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
260 (idx (string-match ":" newsgroup)))
262 (if idx (substring newsgroup 0 idx))
264 (nnheader-replace-chars-in-string
265 (if idx (substring newsgroup (1+ idx)) newsgroup)
268 (defun gnus-newsgroup-savable-name (group)
269 ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
271 (nnheader-replace-chars-in-string group ?/ ?.))
273 (defun gnus-string> (s1 s2)
274 (not (or (string< s1 s2)
279 (defun gnus-file-newer-than (file date)
280 (let ((fdate (nth 5 (file-attributes file))))
281 (or (> (car fdate) (car date))
282 (and (= (car fdate) (car date))
283 (> (nth 1 fdate) (nth 1 date))))))
287 (defmacro gnus-local-set-keys (&rest plist)
288 "Set the keys in PLIST in the current keymap."
289 `(gnus-define-keys-1 (current-local-map) ',plist))
291 (defmacro gnus-define-keys (keymap &rest plist)
292 "Define all keys in PLIST in KEYMAP."
293 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
295 (defmacro gnus-define-keys-safe (keymap &rest plist)
296 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
297 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
299 (put 'gnus-define-keys 'lisp-indent-function 1)
300 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
301 (put 'gnus-local-set-keys 'lisp-indent-function 1)
303 (defmacro gnus-define-keymap (keymap &rest plist)
304 "Define all keys in PLIST in KEYMAP."
305 `(gnus-define-keys-1 ,keymap (quote ,plist)))
307 (put 'gnus-define-keymap 'lisp-indent-function 1)
309 (defun gnus-define-keys-1 (keymap plist &optional safe)
311 (error "Can't set keys in a null keymap"))
312 (cond ((symbolp keymap)
313 (setq keymap (symbol-value keymap)))
316 (set (car keymap) nil)
317 (define-prefix-command (car keymap))
318 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
319 (setq keymap (symbol-value (car keymap)))))
322 (when (symbolp (setq key (pop plist)))
323 (setq key (symbol-value key)))
325 (eq (lookup-key keymap key) 'undefined))
326 (define-key keymap key (pop plist))
329 (defun gnus-completing-read-with-default (default prompt &rest args)
330 ;; Like `completing-read', except that DEFAULT is the default argument.
331 (let* ((prompt (if default
332 (concat prompt " (default " default ") ")
333 (concat prompt " ")))
334 (answer (apply 'completing-read prompt args)))
335 (if (or (null answer) (zerop (length answer)))
339 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
341 (defun gnus-y-or-n-p (prompt)
346 (defun gnus-yes-or-no-p (prompt)
351 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
352 ;; age-depending date representations. (e.g. just the time if it's
353 ;; from today, the day of the week if it's within the last 7 days and
354 ;; the full date if it's older)
355 (defun gnus-seconds-today ()
356 "Returns the number of seconds passed today"
357 (let ((now (decode-time (current-time))))
358 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
360 (defun gnus-seconds-month ()
361 "Returns the number of seconds passed this month"
362 (let ((now (decode-time (current-time))))
363 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
364 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
366 (defun gnus-seconds-year ()
367 "Returns the number of seconds passed this year"
368 (let ((now (decode-time (current-time)))
369 (days (format-time-string "%j" (current-time))))
370 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
371 (* (- (string-to-number days) 1) 3600 24))))
373 (defvar gnus-user-date-format-alist
374 '(((gnus-seconds-today) . "%k:%M")
375 (604800 . "%a %k:%M") ;;that's one week
376 ((gnus-seconds-month) . "%a %d")
377 ((gnus-seconds-year) . "%b %d")
378 (t . "%b %d '%y")) ;;this one is used when no
380 "Alist of time in seconds and format specification used to display dates not older.
381 The first element must be a number or a function returning a
382 number. The second element is a format-specification as described in
383 the documentation for format-time-string. The list must be ordered
384 smallest number up. When there is an element, which is not a number,
385 the corresponding format-specification will be used, disregarding any
386 following elements. You can use the functions gnus-seconds-today,
387 gnus-seconds-month, gnus-seconds-year which will return the number of
388 seconds which passed today/this month/this year.")
390 (defun gnus-user-date (messy-date)
391 "Format the messy-date acording to gnus-user-date-format-alist.
392 Returns \" ? \" if there's bad input or if an other error occurs.
393 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
395 (let* ((messy-date (safe-date-to-time messy-date))
397 ;;If we don't find something suitable we'll use this one
398 (my-format "%b %m '%y")
399 (high (lsh (- (car now) (car messy-date)) 16)))
400 (if (and (> high -1) (= (logand high 65535) 0))
401 ;;overflow and bad input
402 (let* ((difference (+ high (- (car (cdr now))
403 (car (cdr messy-date)))))
404 (templist gnus-user-date-format-alist)
405 (top (eval (caar templist))))
406 (while (if (numberp top) (< top difference) (not top))
408 (setq templist (cdr templist))
409 (setq top (eval (caar templist)))))
410 (if (stringp (cdr (car templist)))
411 (setq my-format (cdr (car templist))))))
412 (format-time-string (eval my-format) messy-date))
414 ;;end of Frank's code
416 (defun gnus-dd-mmm (messy-date)
417 "Return a string like DD-MMM from a big messy string."
419 (format-time-string "%d-%b" (safe-date-to-time messy-date))
422 (defmacro gnus-date-get-time (date)
423 "Convert DATE string to Emacs time.
424 Cache the result as a text property stored in DATE."
425 ;; Either return the cached value...
429 (or (get-text-property 0 'gnus-time d)
430 ;; or compute the value...
431 (let ((time (safe-date-to-time d)))
432 ;; and store it back in the string.
433 (put-text-property 0 1 'gnus-time time d)
436 (defsubst gnus-time-iso8601 (time)
437 "Return a string of TIME in YYYYMMDDTHHMMSS format."
438 (format-time-string "%Y%m%dT%H%M%S" time))
440 (defun gnus-date-iso8601 (date)
441 "Convert the DATE to YYYYMMDDTHHMMSS."
443 (gnus-time-iso8601 (gnus-date-get-time date))
446 (defun gnus-mode-string-quote (string)
447 "Quote all \"%\"'s in STRING."
448 (gnus-replace-in-string string "%" "%%"))
450 ;; Make a hash table (default and minimum size is 256).
451 ;; Optional argument HASHSIZE specifies the table size.
452 (defun gnus-make-hashtable (&optional hashsize)
453 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
455 ;; Make a number that is suitable for hashing; bigger than MIN and
456 ;; equal to some 2^x. Many machines (such as sparcs) do not have a
457 ;; hardware modulo operation, so they implement it in software. On
458 ;; many sparcs over 50% of the time to intern is spent in the modulo.
459 ;; Yes, it's slower than actually computing the hash from the string!
460 ;; So we use powers of 2 so people can optimize the modulo to a mask.
461 (defun gnus-create-hash-size (min)
467 (defcustom gnus-verbose 7
468 "*Integer that says how verbose Gnus should be.
469 The higher the number, the more messages Gnus will flash to say what
470 it's doing. At zero, Gnus will be totally mute; at five, Gnus will
471 display most important messages; and at ten, Gnus will keep on
472 jabbering all the time."
476 ;; Show message if message has a lower level than `gnus-verbose'.
477 ;; Guideline for numbers:
478 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
479 ;; for things that take a long time, 7 - not very important messages
480 ;; on stuff, 9 - messages inside loops.
481 (defun gnus-message (level &rest args)
482 (if (<= level gnus-verbose)
483 (apply 'message args)
484 ;; We have to do this format thingy here even if the result isn't
485 ;; shown - the return value has to be the same as the return value
487 (apply 'format args)))
489 (defun gnus-error (level &rest args)
490 "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
491 (when (<= (floor level) gnus-verbose)
492 (apply 'message args)
495 (when (and (floatp level)
496 (not (zerop (setq duration (* 10 (- level (floor level)))))))
497 (sit-for duration))))
500 (defun gnus-split-references (references)
501 "Return a list of Message-IDs in REFERENCES."
504 (while (string-match "<[^<]+[^< \t]" references beg)
505 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
509 (defsubst gnus-parent-id (references &optional n)
510 "Return the last Message-ID in REFERENCES.
511 If N, return the Nth ancestor instead."
512 (when (and references
513 (not (zerop (length references))))
515 (let ((ids (inline (gnus-split-references references))))
516 (while (nthcdr n ids)
517 (setq ids (cdr ids)))
519 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
520 (match-string 1 references)))))
522 (defun gnus-buffer-live-p (buffer)
523 "Say whether BUFFER is alive or not."
526 (buffer-name (get-buffer buffer))))
528 (defun gnus-horizontal-recenter ()
529 "Recenter the current buffer horizontally."
530 (if (< (current-column) (/ (window-width) 2))
531 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
532 (let* ((orig (point))
533 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
536 ;; Find the longest line currently displayed in the window.
537 (goto-char (window-start))
538 (while (and (not (eobp))
541 (setq max (max max (current-column)))
544 ;; Scroll horizontally to center (sort of) the point.
545 (if (> max (window-width))
547 (gnus-get-buffer-window (current-buffer) t)
548 (min (- (current-column) (/ (window-width) 3))
549 (+ 2 (- max (window-width)))))
550 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
553 (defun gnus-read-event-char ()
554 "Get the next event."
555 (let ((event (read-event)))
556 ;; should be gnus-characterp, but this can't be called in XEmacs anyway
557 (cons (and (numberp event) event) event)))
559 (defun gnus-sortable-date (date)
560 "Make string suitable for sorting from DATE."
561 (gnus-time-iso8601 (date-to-time date)))
563 (defun gnus-copy-file (file &optional to)
566 (list (read-file-name "Copy file: " default-directory)
567 (read-file-name "Copy file to: " default-directory)))
569 (setq to (read-file-name "Copy file to: " default-directory)))
570 (when (file-directory-p to)
571 (setq to (concat (file-name-as-directory to)
572 (file-name-nondirectory file))))
575 (defvar gnus-work-buffer " *gnus work*")
577 (defun gnus-set-work-buffer ()
578 "Put point in the empty Gnus work buffer."
579 (if (get-buffer gnus-work-buffer)
581 (set-buffer gnus-work-buffer)
583 (set-buffer (gnus-get-buffer-create gnus-work-buffer))
584 (kill-all-local-variables)))
586 (defmacro gnus-group-real-name (group)
587 "Find the real name of a foreign newsgroup."
588 `(let ((gname ,group))
589 (if (string-match "^[^:]+:" gname)
590 (substring gname (match-end 0))
593 (defun gnus-make-sort-function (funs)
594 "Return a composite sort condition based on the functions in FUNC."
596 ;; Just a simple function.
597 ((gnus-functionp funs) funs)
598 ;; No functions at all.
600 ;; A list of functions.
605 ,(gnus-make-sort-function-1 (reverse funs)))))
606 ;; A list containing just one function.
610 (defun gnus-make-sort-function-1 (funs)
611 "Return a composite sort condition based on the functions in FUNC."
612 (let ((function (car funs))
615 (when (consp function)
618 ((eq (car function) 'not)
619 (setq function (cadr function)
622 ((gnus-functionp function)
626 (error "Invalid sort spec: %s" function))))
628 `(or (,function ,first ,last)
629 (and (not (,function ,last ,first))
630 ,(gnus-make-sort-function-1 (cdr funs))))
631 `(,function ,first ,last))))
633 (defun gnus-turn-off-edit-menu (type)
634 "Turn off edit menu in `gnus-TYPE-mode-map'."
635 (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
636 [menu-bar edit] 'undefined))
638 (defun gnus-prin1 (form)
639 "Use `prin1' on FORM in the current buffer.
640 Bind `print-quoted' and `print-readably' to t while printing."
641 (let ((print-quoted t)
643 (print-escape-multibyte nil)
644 print-level print-length)
645 (prin1 form (current-buffer))))
647 (defun gnus-prin1-to-string (form)
648 "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
649 (let ((print-quoted t)
651 (prin1-to-string form)))
653 (defun gnus-make-directory (directory)
654 "Make DIRECTORY (and all its parents) if it doesn't exist."
656 (let ((file-name-coding-system nnmail-pathname-coding-system)
657 (pathname-coding-system nnmail-pathname-coding-system))
659 (not (file-exists-p directory)))
660 (make-directory directory t)))
663 (defun gnus-write-buffer (file)
664 "Write the current buffer's contents to FILE."
665 ;; Make sure the directory exists.
666 (gnus-make-directory (file-name-directory file))
667 (let ((file-name-coding-system nnmail-pathname-coding-system)
668 (pathname-coding-system nnmail-pathname-coding-system))
670 (write-region (point-min) (point-max) file nil 'quietly)))
672 (defun gnus-write-buffer-as-binary (file)
673 "Write the current buffer's contents to FILE without code conversion."
674 ;; Make sure the directory exists.
675 (gnus-make-directory (file-name-directory file))
677 (write-region-as-binary (point-min) (point-max) file nil 'quietly))
679 (defun gnus-write-buffer-as-coding-system (coding-system file)
680 "Write the current buffer's contents to FILE with code conversion."
681 ;; Make sure the directory exists.
682 (gnus-make-directory (file-name-directory file))
684 (write-region-as-coding-system
685 coding-system (point-min) (point-max) file nil 'quietly))
687 (defun gnus-delete-file (file)
688 "Delete FILE if it exists."
689 (when (file-exists-p file)
692 (defun gnus-strip-whitespace (string)
693 "Return STRING stripped of all whitespace."
694 (while (string-match "[\r\n\t ]+" string)
695 (setq string (replace-match "" t t string)))
698 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
699 "The same as `put-text-property', but don't put this prop on any newlines in the region."
704 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
705 (gnus-put-text-property beg (match-beginning 0) prop val)
707 (gnus-put-text-property beg (point) prop val)))))
709 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
710 "The same as `put-text-property', but don't put this prop on any newlines in the region."
715 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
717 (gnus-make-overlay beg (match-beginning 0))
720 (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
722 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
724 "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
727 (when (get-text-property b 'gnus-face)
728 (setq b (next-single-property-change b 'gnus-face nil end)))
731 (gnus-put-text-property
732 b (setq b (next-single-property-change b 'gnus-face nil end))
735 ;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
736 ;;; The primary idea here is to try to protect internal datastructures
737 ;;; from becoming corrupted when the user hits C-g, or if a hook or
738 ;;; similar blows up. Often in Gnus multiple tables/lists need to be
739 ;;; updated at the same time, or information can be lost.
741 (defvar gnus-atomic-be-safe t
742 "If t, certain operations will be protected from interruption by C-g.")
744 (defmacro gnus-atomic-progn (&rest forms)
745 "Evaluate FORMS atomically, which means to protect the evaluation
746 from being interrupted by the user. An error from the forms themselves
747 will return without finishing the operation. Since interrupts from
748 the user are disabled, it is recommended that only the most minimal
749 operations are performed by FORMS. If you wish to assign many
750 complicated values atomically, compute the results into temporary
751 variables and then do only the assignment atomically."
752 `(let ((inhibit-quit gnus-atomic-be-safe))
755 (put 'gnus-atomic-progn 'lisp-indent-function 0)
757 (defmacro gnus-atomic-progn-assign (protect &rest forms)
758 "Evaluate FORMS, but insure that the variables listed in PROTECT
759 are not changed if anything in FORMS signals an error or otherwise
760 non-locally exits. The variables listed in PROTECT are updated atomically.
761 It is safe to use gnus-atomic-progn-assign with long computations.
763 Note that if any of the symbols in PROTECT were unbound, they will be
764 set to nil on a sucessful assignment. In case of an error or other
765 non-local exit, it will still be unbound."
766 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
767 (concat (symbol-name x)
771 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
773 (temp-sym-let (mapcar (lambda (x) (list (car x)
774 `(and (boundp ',(cadr x))
777 (sym-temp-let sym-temp-map)
778 (temp-sym-assign (apply 'append temp-sym-map))
779 (sym-temp-assign (apply 'append sym-temp-map))
780 (result (make-symbol "result-tmp")))
781 `(let (,@temp-sym-let
784 (setq ,result (progn ,@forms))
785 (setq ,@temp-sym-assign))
786 (let ((inhibit-quit gnus-atomic-be-safe))
787 (setq ,@sym-temp-assign))
790 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
791 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
793 (defmacro gnus-atomic-setq (&rest pairs)
794 "Similar to setq, except that the real symbols are only assigned when
795 there are no errors. And when the real symbols are assigned, they are
796 done so atomically. If other variables might be changed via side-effect,
797 see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
798 with potentially long computations."
802 (push (car tpairs) syms)
803 (setq tpairs (cddr tpairs)))
804 `(gnus-atomic-progn-assign ,syms
807 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
810 ;;; Functions for saving to babyl/mail files.
812 (defvar rmail-default-rmail-file)
813 (defun gnus-output-to-rmail (filename &optional ask)
814 "Append the current article to an Rmail file named FILENAME."
816 ;; Most of these codes are borrowed from rmailout.el.
817 (setq filename (expand-file-name filename))
818 (setq rmail-default-rmail-file filename)
819 (let ((artbuf (current-buffer))
820 (tmpbuf (get-buffer-create " *Gnus-output*")))
822 (or (get-file-buffer filename)
823 (file-exists-p filename)
826 (concat "\"" filename "\" does not exist, create it? ")))
827 (let ((file-buffer (create-file-buffer filename)))
829 (set-buffer file-buffer)
830 (rmail-insert-rmail-file-header)
831 (let ((require-final-newline nil))
832 (gnus-write-buffer-as-coding-system
833 nnheader-text-coding-system filename)))
834 (kill-buffer file-buffer))
835 (error "Output file does not exist")))
838 (insert-buffer-substring artbuf)
839 (gnus-convert-article-to-rmail)
840 ;; Decide whether to append to a file or to an Emacs buffer.
841 (let ((outbuf (get-file-buffer filename)))
843 (let ((file-name-coding-system nnmail-pathname-coding-system)
844 (pathname-coding-system nnmail-pathname-coding-system))
845 (write-region-as-binary (point-min) (point-max)
847 ;; File has been visited, in buffer OUTBUF.
849 (let ((buffer-read-only nil)
850 (msg (and (boundp 'rmail-current-message)
851 (symbol-value 'rmail-current-message))))
852 ;; If MSG is non-nil, buffer is in RMAIL mode.
855 (narrow-to-region (point-max) (point-max)))
856 (insert-buffer-substring tmpbuf)
858 (goto-char (point-min))
860 (search-backward "\n\^_")
861 (narrow-to-region (point) (point-max))
862 (rmail-count-new-messages t)
863 (when (rmail-summary-exists)
864 (rmail-select-summary
865 (rmail-update-summary)))
866 (rmail-count-new-messages t)
867 (rmail-show-message msg))
869 (kill-buffer tmpbuf)))
871 (defun gnus-output-to-mail (filename &optional ask)
872 "Append the current article to a mail file named FILENAME."
873 (setq filename (expand-file-name filename))
874 (let ((artbuf (current-buffer))
875 (tmpbuf (get-buffer-create " *Gnus-output*")))
877 ;; Create the file, if it doesn't exist.
878 (when (and (not (get-file-buffer filename))
879 (not (file-exists-p filename)))
882 (concat "\"" filename "\" does not exist, create it? ")))
883 (let ((file-buffer (create-file-buffer filename)))
885 (set-buffer file-buffer)
886 (let ((require-final-newline nil))
887 (gnus-write-buffer-as-coding-system
888 nnheader-text-coding-system filename)))
889 (kill-buffer file-buffer))
890 (error "Output file does not exist")))
893 (insert-buffer-substring artbuf)
894 (goto-char (point-min))
895 (if (looking-at "From ")
897 (insert "From nobody " (current-time-string) "\n"))
898 (let (case-fold-search)
899 (while (re-search-forward "^From " nil t)
902 ;; Decide whether to append to a file or to an Emacs buffer.
903 (let ((outbuf (get-file-buffer filename)))
905 (let ((buffer-read-only nil))
907 (goto-char (point-max))
909 (unless (looking-at "\n\n")
910 (goto-char (point-max))
914 (goto-char (point-max))
915 (let ((file-name-coding-system nnmail-pathname-coding-system)
916 (pathname-coding-system nnmail-pathname-coding-system))
917 (write-region-as-binary (point-min) (point-max)
919 ;; File has been visited, in buffer OUTBUF.
921 (let ((buffer-read-only nil))
922 (goto-char (point-max))
926 (insert-buffer-substring tmpbuf)))))
927 (kill-buffer tmpbuf)))
929 (defun gnus-convert-article-to-rmail ()
930 "Convert article in current buffer to Rmail message format."
931 (let ((buffer-read-only nil))
932 ;; Convert article directly into Babyl format.
933 (goto-char (point-min))
934 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
935 (while (search-forward "\n\^_" nil t) ;single char
936 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
937 (goto-char (point-max))
940 (defun gnus-map-function (funs arg)
941 "Applies the result of the first function in FUNS to the second, and so on.
942 ARG is passed to the first function."
945 (setq arg (funcall (pop myfuns) arg)))
948 (defun gnus-run-hooks (&rest funcs)
949 "Does the same as `run-hooks', but saves excursion."
950 (let ((buf (current-buffer)))
952 (apply 'run-hooks funcs)
957 (defvar gnus-group-buffer) ; Compiler directive
958 (defun gnus-alive-p ()
959 "Say whether Gnus is running or not."
960 (and (boundp 'gnus-group-buffer)
961 (get-buffer gnus-group-buffer)
963 (set-buffer gnus-group-buffer)
964 (eq major-mode 'gnus-group-mode))))
966 (defun gnus-remove-duplicates (list)
967 (let (new (tail list))
969 (or (member (car tail) new)
970 (setq new (cons (car tail) new)))
971 (setq tail (cdr tail)))
974 (defun gnus-delete-if (predicate list)
975 "Delete elements from LIST that satisfy PREDICATE."
978 (unless (funcall predicate (car list))
979 (push (car list) out))
983 (if (fboundp 'assq-delete-all)
984 (defalias 'gnus-delete-alist 'assq-delete-all)
985 (defun gnus-delete-alist (key alist)
986 "Delete from ALIST all elements whose car is KEY.
987 Return the modified alist."
989 (while (setq entry (assq key alist))
990 (setq alist (delq entry alist)))
993 (defmacro gnus-pull (key alist &optional assoc-p)
994 "Modify ALIST to be without KEY."
995 (unless (symbolp alist)
996 (error "Not a symbol: %s" alist))
997 (let ((fun (if assoc-p 'assoc 'assq)))
998 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1000 (defun gnus-globalify-regexp (re)
1001 "Returns a regexp that matches a whole line, iff RE matches a part of it."
1002 (concat (unless (string-match "^\\^" re) "^.*")
1004 (unless (string-match "\\$$" re) ".*$")))
1006 (defun gnus-set-window-start (&optional point)
1007 "Set the window start to POINT, or (point) if nil."
1008 (let ((win (gnus-get-buffer-window (current-buffer) t)))
1010 (set-window-start win (or point (point))))))
1012 (defun gnus-annotation-in-region-p (b e)
1014 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1015 (text-property-any b e 'gnus-undeletable t)))
1017 (defun gnus-or (&rest elems)
1018 "Return non-nil if any of the elements are non-nil."
1022 (throw 'found t)))))
1024 (defun gnus-and (&rest elems)
1025 "Return non-nil if all of the elements are non-nil."
1029 (throw 'found nil)))
1032 (defun gnus-write-active-file (file hashtb &optional full-names)
1033 (let ((output-coding-system nnmail-active-file-coding-system)
1034 (coding-system-for-write nnmail-active-file-coding-system))
1035 (with-temp-file file
1041 (insert (format "%S %d %d y\n"
1044 (intern (gnus-group-real-name (symbol-name sym))))
1045 (or (cdr (symbol-value sym))
1046 (car (symbol-value sym)))
1047 (car (symbol-value sym))))))
1049 (goto-char (point-max))
1050 (while (search-backward "\\." nil t)
1053 (if (fboundp 'union)
1054 (defalias 'gnus-union 'union)
1055 (defun gnus-union (l1 l2)
1056 "Set union of lists L1 and L2."
1057 (cond ((null l1) l2)
1061 (or (>= (length l1) (length l2))
1062 (setq l1 (prog1 l2 (setq l2 l1))))
1064 (or (member (car l2) l1)
1069 (defun gnus-add-text-properties-when
1070 (property value start end properties &optional object)
1071 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1074 (< start end) ;; XEmacs will loop for every when start=end.
1075 (setq point (text-property-not-all start end property value)))
1076 (gnus-add-text-properties start point properties object)
1077 (setq start (text-property-any point end property value)))
1079 (gnus-add-text-properties start end properties object))))
1081 (defun gnus-remove-text-properties-when
1082 (property value start end properties &optional object)
1083 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1087 (setq point (text-property-not-all start end property value)))
1088 (remove-text-properties start point properties object)
1089 (setq start (text-property-any point end property value)))
1091 (remove-text-properties start end properties object))
1094 (defun gnus-string-equal (x y)
1095 "Like `string-equal', except it compares case-insensitively."
1096 (and (= (length x) (length y))
1097 (or (string-equal x y)
1098 (string-equal (downcase x) (downcase y)))))
1100 (defcustom gnus-use-byte-compile t
1101 "If non-nil, byte-compile crucial run-time codes.
1102 Setting it to `nil' has no effect after first time running
1103 `gnus-byte-compile'."
1106 :group 'gnus-various)
1108 (defun gnus-byte-compile (form)
1109 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1110 (if gnus-use-byte-compile
1113 ;; Work around a bug in XEmacs 21.4
1114 (require 'byte-optimize)
1117 (defalias 'gnus-byte-compile 'byte-compile)
1118 (byte-compile form))
1121 (defun gnus-remassoc (key alist)
1122 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1123 The modified LIST is returned. If the first member
1124 of LIST has a car that is `equal' to KEY, there is no way to remove it
1125 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1126 sure of changing the value of `foo'."
1128 (if (equal key (caar alist))
1130 (setcdr alist (gnus-remassoc key (cdr alist)))
1133 (defun gnus-update-alist-soft (key value alist)
1135 (cons (cons key value) (gnus-remassoc key alist))
1136 (gnus-remassoc key alist)))
1138 (defun gnus-create-info-command (node)
1139 "Create a command that will go to info NODE."
1142 ,(concat "Enter the info system at node " node)
1143 (Info-goto-node ,node)
1144 (setq gnus-info-buffer (current-buffer))
1145 (gnus-configure-windows 'info)))
1147 (defun gnus-not-ignore (&rest args)
1150 (defvar gnus-directory-sep-char-regexp "/"
1151 "The regexp of directory separator character.
1152 If you find some problem with the directory separator character, try
1153 \"[/\\\\\]\" for some systems.")
1155 (defun gnus-url-unhex (x)
1162 (defun gnus-url-unhex-string (str &optional allow-newlines)
1163 "Remove %XXX embedded spaces, etc in a url.
1164 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1165 decoding of carriage returns and line feeds in the string, which is normally
1166 forbidden in URL encoding."
1167 (setq str (or (mm-subst-char-in-string ?+ ? str) ""))
1169 (case-fold-search t))
1170 (while (string-match "%[0-9a-f][0-9a-f]" str)
1171 (let* ((start (match-beginning 0))
1172 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1174 (gnus-url-unhex (elt str (+ start 2))))))
1176 tmp (substring str 0 start)
1179 (char-to-string code))
1180 ((or (= code ?\n) (= code ?\r))
1182 (t (char-to-string code))))
1183 str (substring str (match-end 0)))))
1184 (setq tmp (concat tmp str))
1187 (defun gnus-make-predicate (spec)
1188 "Transform SPEC into a function that can be called.
1189 SPEC is a predicate specifier that contains stuff like `or', `and',
1190 `not', lists and functions. The functions all take one parameter."
1191 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1193 (defun gnus-make-predicate-1 (spec)
1198 (if (memq (car spec) '(or and not))
1199 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1200 (error "Invalid predicate specifier: %s" spec)))))
1202 (defun gnus-local-map-property (map)
1203 "Return a list suitable for a text property list specifying keymap MAP."
1207 ((>= emacs-major-version 21)
1210 (list 'local-map map))))
1212 (defun gnus-completing-read (prompt table &optional predicate require-match
1215 (not (boundp history)))
1218 (if (symbol-value history)
1219 (concat prompt " (" (car (symbol-value history)) "): ")
1220 (concat prompt ": "))
1226 (car (symbol-value history))))
1228 (defun gnus-graphic-display-p ()
1229 (or (and (fboundp 'display-graphic-p)
1230 (display-graphic-p))
1231 ;;;!!!This is bogus. Fixme!
1232 (and (featurep 'xemacs)
1235 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1236 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1238 (defmacro gnus-parse-without-error (&rest body)
1239 "Allow continuing onto the next line even if an error occurs."
1240 `(while (not (eobp))
1244 (goto-char (point-max)))
1246 (gnus-error 4 "Invalid data on line %d"
1247 (count-lines (point-min) (point)))
1248 (forward-line 1)))))
1250 (defun gnus-cache-file-contents (file variable function)
1251 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1252 (let ((time (nth 5 (file-attributes file)))
1254 (if (or (null (setq value (symbol-value variable)))
1255 (not (equal (car value) file))
1256 (not (equal (nth 1 value) time)))
1258 (setq contents (funcall function file))
1259 (set variable (list file time contents))
1263 (defun gnus-multiple-choice (prompt choice &optional idx)
1264 "Ask user a multiple choice question.
1265 CHOICE is a list of the choice char and help message at IDX."
1267 (save-window-excursion
1270 (message "%s (%s?): "
1272 (mapconcat (lambda (s) (char-to-string (car s)))
1274 (setq tchar (read-char))
1275 (when (not (assq tchar choice))
1277 (setq buf (get-buffer-create "*Gnus Help*"))
1279 (fundamental-mode) ; for Emacs 20.4+
1280 (buffer-disable-undo)
1282 (insert prompt ":\n\n")
1289 ;; find the longest string to display
1291 (setq n (length (nth idx (car list))))
1294 (setq list (cdr list)))
1295 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1296 (setq n (/ (1- (window-width)) max)) ; items per line
1297 (setq width (/ (1- (window-width)) n)) ; width of each item
1298 ;; insert `n' items, each in a field of width `width'
1303 (delete-char -1) ; the `\n' takes a char
1305 (setq pad (- width 3))
1306 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1307 (insert (format format (caar alist) (nth idx (car alist))))
1308 (setq alist (cdr alist))
1309 (setq i (1+ i))))))))
1310 (if (buffer-live-p buf)
1314 (provide 'gnus-util)
1316 ;;; gnus-util.el ends here