1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002
3 ;; Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
8 ;; This file is part of GNU Emacs.
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)
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.
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.
27 ;; Nothing in this file depends on any other parts of Gnus -- all
28 ;; functions and macros in this file are utility functions that are
29 ;; 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))
44 (autoload 'message-fetch-field "message")
45 (autoload 'gnus-get-buffer-window "gnus-win")
46 (autoload 'rmail-insert-rmail-file-header "rmail")
47 (autoload 'rmail-count-new-messages "rmail")
48 (autoload 'rmail-show-message "rmail"))
52 ((fboundp 'replace-in-string)
53 (defalias 'gnus-replace-in-string 'replace-in-string))
54 ((fboundp 'replace-regexp-in-string)
55 (defun gnus-replace-in-string (string regexp newtext &optional literal)
56 (replace-regexp-in-string regexp newtext string nil literal)))
58 (defun gnus-replace-in-string (string regexp newtext &optional literal)
60 (while (string-match regexp string start)
61 (setq tail (- (length string) (match-end 0)))
62 (setq string (replace-match newtext nil literal string))
63 (setq start (- (length string) tail))))
66 ;;; bring in the netrc functions as aliases
67 (defalias 'gnus-netrc-get 'netrc-get)
68 (defalias 'gnus-netrc-machine 'netrc-machine)
69 (defalias 'gnus-parse-netrc 'netrc-parse)
71 (defun gnus-boundp (variable)
72 "Return non-nil if VARIABLE is bound and non-nil."
73 (and (boundp variable)
74 (symbol-value variable)))
76 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
77 "Pop to BUFFER, evaluate FORMS, and then return to the original window."
78 (let ((tempvar (make-symbol "GnusStartBufferWindow"))
80 (buf (make-symbol "buf")))
81 `(let* ((,tempvar (selected-window))
83 (,w (gnus-get-buffer-window ,buf 'visible)))
89 (set-buffer (window-buffer ,w)))
92 (select-window ,tempvar)))))
94 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
95 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
97 (defmacro gnus-intern-safe (string hashtable)
98 "Set hash value. Arguments are STRING, VALUE, and HASHTABLE."
99 `(let ((symbol (intern ,string ,hashtable)))
104 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>. A safe way
105 ;; to limit the length of a string. This function is necessary since
106 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
107 (defsubst gnus-limit-string (str width)
108 (if (> (length str) width)
109 (substring str 0 width)
112 (defsubst gnus-functionp (form)
113 "Return non-nil if FORM is funcallable."
114 (or (and (symbolp form) (fboundp form))
115 (and (listp form) (eq (car form) 'lambda))
116 (byte-code-function-p form)))
118 (defsubst gnus-goto-char (point)
119 (and point (goto-char point)))
121 (defmacro gnus-buffer-exists-p (buffer)
122 `(let ((buffer ,buffer))
124 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
127 (defmacro gnus-kill-buffer (buffer)
128 `(let ((buf ,buffer))
129 (when (gnus-buffer-exists-p buf)
132 (defalias 'gnus-point-at-bol
133 (if (fboundp 'point-at-bol)
135 'line-beginning-position))
137 (defalias 'gnus-point-at-eol
138 (if (fboundp 'point-at-eol)
142 (defun gnus-delete-first (elt list)
143 "Delete by side effect the first occurrence of ELT as a member of LIST."
144 (if (equal (car list) elt)
147 (while (and (cdr list)
148 (not (equal (cadr list) elt)))
149 (setq list (cdr list)))
151 (setcdr list (cddr list)))
154 ;; Delete the current line (and the next N lines).
155 (defmacro gnus-delete-line (&optional n)
156 `(delete-region (progn (beginning-of-line) (point))
157 (progn (forward-line ,(or n 1)) (point))))
159 (defun gnus-byte-code (func)
160 "Return a form that can be `eval'ed based on FUNC."
161 (let ((fval (indirect-function func)))
162 (if (byte-code-function-p fval)
163 (let ((flist (append fval nil)))
164 (setcar flist 'byte-code)
166 (cons 'progn (cddr fval)))))
168 (defun gnus-extract-address-components (from)
170 ;; First find the address - the thing with the @ in it. This may
171 ;; not be accurate in mail addresses, but does the trick most of
172 ;; the time in news messages.
173 (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
174 (setq address (substring from (match-beginning 0) (match-end 0))))
175 ;; Then we check whether the "name <address>" format is used.
177 ;; Linear white space is not required.
178 (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
179 (and (setq name (substring from 0 (match-beginning 0)))
180 ;; Strip any quotes from the name.
181 (string-match "^\".*\"$" name)
182 (setq name (substring name 1 (1- (match-end 0))))))
183 ;; If not, then "address (name)" is used.
185 (and (string-match "(.+)" from)
186 (setq name (substring from (1+ (match-beginning 0))
187 (1- (match-end 0)))))
188 (and (string-match "()" from)
190 ;; XOVER might not support folded From headers.
191 (and (string-match "(.*" from)
192 (setq name (substring from (1+ (match-beginning 0))
194 (list (if (string= name "") nil name) (or address from))))
197 (defun gnus-fetch-field (field)
198 "Return the value of the header FIELD of current article."
201 (let ((case-fold-search t)
202 (inhibit-point-motion-hooks t))
203 (nnheader-narrow-to-headers)
204 (message-fetch-field field)))))
206 (defun gnus-goto-colon ()
208 (let ((eol (gnus-point-at-eol)))
209 (goto-char (or (text-property-any (point) eol 'gnus-position t)
210 (search-forward ":" eol t)
213 (defun gnus-decode-newsgroups (newsgroups group &optional method)
214 (let ((method (or method (gnus-find-method-for-group group))))
215 (mapconcat (lambda (group)
216 (gnus-group-name-decode group (gnus-group-name-charset
218 (message-tokenize-header newsgroups)
221 (defun gnus-remove-text-with-property (prop)
222 "Delete all text in the current buffer with text property PROP."
224 (goto-char (point-min))
226 (while (get-text-property (point) prop)
228 (goto-char (next-single-property-change (point) prop nil (point-max))))))
231 (defun gnus-newsgroup-directory-form (newsgroup)
232 "Make hierarchical directory name from NEWSGROUP name."
233 (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
234 (idx (string-match ":" newsgroup)))
236 (if idx (substring newsgroup 0 idx))
238 (nnheader-replace-chars-in-string
239 (if idx (substring newsgroup (1+ idx)) newsgroup)
242 (defun gnus-newsgroup-savable-name (group)
243 ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
245 (nnheader-replace-chars-in-string group ?/ ?.))
247 (defun gnus-string> (s1 s2)
248 (not (or (string< s1 s2)
253 (defun gnus-file-newer-than (file date)
254 (let ((fdate (nth 5 (file-attributes file))))
255 (or (> (car fdate) (car date))
256 (and (= (car fdate) (car date))
257 (> (nth 1 fdate) (nth 1 date))))))
261 (defmacro gnus-local-set-keys (&rest plist)
262 "Set the keys in PLIST in the current keymap."
263 `(gnus-define-keys-1 (current-local-map) ',plist))
265 (defmacro gnus-define-keys (keymap &rest plist)
266 "Define all keys in PLIST in KEYMAP."
267 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
269 (defmacro gnus-define-keys-safe (keymap &rest plist)
270 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
271 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
273 (put 'gnus-define-keys 'lisp-indent-function 1)
274 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
275 (put 'gnus-local-set-keys 'lisp-indent-function 1)
277 (defmacro gnus-define-keymap (keymap &rest plist)
278 "Define all keys in PLIST in KEYMAP."
279 `(gnus-define-keys-1 ,keymap (quote ,plist)))
281 (put 'gnus-define-keymap 'lisp-indent-function 1)
283 (defun gnus-define-keys-1 (keymap plist &optional safe)
285 (error "Can't set keys in a null keymap"))
286 (cond ((symbolp keymap)
287 (setq keymap (symbol-value keymap)))
290 (set (car keymap) nil)
291 (define-prefix-command (car keymap))
292 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
293 (setq keymap (symbol-value (car keymap)))))
296 (when (symbolp (setq key (pop plist)))
297 (setq key (symbol-value key)))
299 (eq (lookup-key keymap key) 'undefined))
300 (define-key keymap key (pop plist))
303 (defun gnus-completing-read-with-default (default prompt &rest args)
304 ;; Like `completing-read', except that DEFAULT is the default argument.
305 (let* ((prompt (if default
306 (concat prompt " (default " default ") ")
307 (concat prompt " ")))
308 (answer (apply 'completing-read prompt args)))
309 (if (or (null answer) (zerop (length answer)))
313 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
315 (defun gnus-y-or-n-p (prompt)
320 (defun gnus-yes-or-no-p (prompt)
325 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
326 ;; age-depending date representations. (e.g. just the time if it's
327 ;; from today, the day of the week if it's within the last 7 days and
328 ;; the full date if it's older)
329 (defun gnus-seconds-today ()
330 "Returns the number of seconds passed today"
331 (let ((now (decode-time (current-time))))
332 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
334 (defun gnus-seconds-month ()
335 "Returns the number of seconds passed this month"
336 (let ((now (decode-time (current-time))))
337 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
338 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
340 (defun gnus-seconds-year ()
341 "Returns the number of seconds passed this year"
342 (let ((now (decode-time (current-time)))
343 (days (format-time-string "%j" (current-time))))
344 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
345 (* (- (string-to-number days) 1) 3600 24))))
347 (defvar gnus-user-date-format-alist
348 '(((gnus-seconds-today) . "%k:%M")
349 (604800 . "%a %k:%M") ;;that's one week
350 ((gnus-seconds-month) . "%a %d")
351 ((gnus-seconds-year) . "%b %d")
352 (t . "%b %d '%y")) ;;this one is used when no
354 "Specifies date format depending on age of article.
355 This is an alist of items (AGE . FORMAT). AGE can be a number (of
356 seconds) or a Lisp expression evaluating to a number. When the age of
357 the article is less than this number, then use `format-time-string'
358 with the corresponding FORMAT for displaying the date of the article.
359 If AGE is not a number or a Lisp expression evaluating to a
360 non-number, then the corresponding FORMAT is used as a default value.
362 Note that the list is processed from the beginning, so it should be
363 sorted by ascending AGE. Also note that items following the first
364 non-number AGE will be ignored.
366 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
367 and `gnus-seconds-year' in the AGE spec. They return the number of
368 seconds passed since the start of today, of this month, of this year,
371 (defun gnus-user-date (messy-date)
372 "Format the messy-date acording to gnus-user-date-format-alist.
373 Returns \" ? \" if there's bad input or if an other error occurs.
374 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
376 (let* ((messy-date (safe-date-to-time messy-date))
378 ;;If we don't find something suitable we'll use this one
379 (my-format "%b %m '%y")
380 (high (lsh (- (car now) (car messy-date)) 16)))
381 (if (and (> high -1) (= (logand high 65535) 0))
382 ;;overflow and bad input
383 (let* ((difference (+ high (- (car (cdr now))
384 (car (cdr messy-date)))))
385 (templist gnus-user-date-format-alist)
386 (top (eval (caar templist))))
387 (while (if (numberp top) (< top difference) (not top))
389 (setq templist (cdr templist))
390 (setq top (eval (caar templist)))))
391 (if (stringp (cdr (car templist)))
392 (setq my-format (cdr (car templist))))))
393 (format-time-string (eval my-format) messy-date))
395 ;;end of Frank's code
397 (defun gnus-dd-mmm (messy-date)
398 "Return a string like DD-MMM from a big messy string."
400 (format-time-string "%d-%b" (safe-date-to-time messy-date))
403 (defmacro gnus-date-get-time (date)
404 "Convert DATE string to Emacs time.
405 Cache the result as a text property stored in DATE."
406 ;; Either return the cached value...
410 (or (get-text-property 0 'gnus-time d)
411 ;; or compute the value...
412 (let ((time (safe-date-to-time d)))
413 ;; and store it back in the string.
414 (put-text-property 0 1 'gnus-time time d)
417 (defsubst gnus-time-iso8601 (time)
418 "Return a string of TIME in YYYYMMDDTHHMMSS format."
419 (format-time-string "%Y%m%dT%H%M%S" time))
421 (defun gnus-date-iso8601 (date)
422 "Convert the DATE to YYYYMMDDTHHMMSS."
424 (gnus-time-iso8601 (gnus-date-get-time date))
427 (defun gnus-mode-string-quote (string)
428 "Quote all \"%\"'s in STRING."
429 (gnus-replace-in-string string "%" "%%"))
431 ;; Make a hash table (default and minimum size is 256).
432 ;; Optional argument HASHSIZE specifies the table size.
433 (defun gnus-make-hashtable (&optional hashsize)
434 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
436 ;; Make a number that is suitable for hashing; bigger than MIN and
437 ;; equal to some 2^x. Many machines (such as sparcs) do not have a
438 ;; hardware modulo operation, so they implement it in software. On
439 ;; many sparcs over 50% of the time to intern is spent in the modulo.
440 ;; Yes, it's slower than actually computing the hash from the string!
441 ;; So we use powers of 2 so people can optimize the modulo to a mask.
442 (defun gnus-create-hash-size (min)
448 (defcustom gnus-verbose 7
449 "*Integer that says how verbose Gnus should be.
450 The higher the number, the more messages Gnus will flash to say what
451 it's doing. At zero, Gnus will be totally mute; at five, Gnus will
452 display most important messages; and at ten, Gnus will keep on
453 jabbering all the time."
457 ;; Show message if message has a lower level than `gnus-verbose'.
458 ;; Guideline for numbers:
459 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
460 ;; for things that take a long time, 7 - not very important messages
461 ;; on stuff, 9 - messages inside loops.
462 (defun gnus-message (level &rest args)
463 (if (<= level gnus-verbose)
464 (apply 'message args)
465 ;; We have to do this format thingy here even if the result isn't
466 ;; shown - the return value has to be the same as the return value
468 (apply 'format args)))
470 (defun gnus-error (level &rest args)
471 "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
472 (when (<= (floor level) gnus-verbose)
473 (apply 'message args)
476 (when (and (floatp level)
477 (not (zerop (setq duration (* 10 (- level (floor level)))))))
478 (sit-for duration))))
481 (defun gnus-split-references (references)
482 "Return a list of Message-IDs in REFERENCES."
485 (while (string-match "<[^<]+[^< \t]" references beg)
486 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
490 (defsubst gnus-parent-id (references &optional n)
491 "Return the last Message-ID in REFERENCES.
492 If N, return the Nth ancestor instead."
493 (when (and references
494 (not (zerop (length references))))
496 (let ((ids (inline (gnus-split-references references))))
497 (while (nthcdr n ids)
498 (setq ids (cdr ids)))
500 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
501 (match-string 1 references)))))
503 (defun gnus-buffer-live-p (buffer)
504 "Say whether BUFFER is alive or not."
507 (buffer-name (get-buffer buffer))))
509 (defun gnus-horizontal-recenter ()
510 "Recenter the current buffer horizontally."
511 (if (< (current-column) (/ (window-width) 2))
512 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
513 (let* ((orig (point))
514 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
517 ;; Find the longest line currently displayed in the window.
518 (goto-char (window-start))
519 (while (and (not (eobp))
522 (setq max (max max (current-column)))
525 ;; Scroll horizontally to center (sort of) the point.
526 (if (> max (window-width))
528 (gnus-get-buffer-window (current-buffer) t)
529 (min (- (current-column) (/ (window-width) 3))
530 (+ 2 (- max (window-width)))))
531 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
534 (defun gnus-read-event-char ()
535 "Get the next event."
536 (let ((event (read-event)))
537 ;; should be gnus-characterp, but this can't be called in XEmacs anyway
538 (cons (and (numberp event) event) event)))
540 (defun gnus-sortable-date (date)
541 "Make string suitable for sorting from DATE."
542 (gnus-time-iso8601 (date-to-time date)))
544 (defun gnus-copy-file (file &optional to)
547 (list (read-file-name "Copy file: " default-directory)
548 (read-file-name "Copy file to: " default-directory)))
550 (setq to (read-file-name "Copy file to: " default-directory)))
551 (when (file-directory-p to)
552 (setq to (concat (file-name-as-directory to)
553 (file-name-nondirectory file))))
556 (defvar gnus-work-buffer " *gnus work*")
558 (defun gnus-set-work-buffer ()
559 "Put point in the empty Gnus work buffer."
560 (if (get-buffer gnus-work-buffer)
562 (set-buffer gnus-work-buffer)
564 (set-buffer (gnus-get-buffer-create gnus-work-buffer))
565 (kill-all-local-variables)
566 (mm-enable-multibyte)))
568 (defmacro gnus-group-real-name (group)
569 "Find the real name of a foreign newsgroup."
570 `(let ((gname ,group))
571 (if (string-match "^[^:]+:" gname)
572 (substring gname (match-end 0))
575 (defun gnus-make-sort-function (funs)
576 "Return a composite sort condition based on the functions in FUNC."
578 ;; Just a simple function.
579 ((gnus-functionp funs) funs)
580 ;; No functions at all.
582 ;; A list of functions.
587 ,(gnus-make-sort-function-1 (reverse funs)))))
588 ;; A list containing just one function.
592 (defun gnus-make-sort-function-1 (funs)
593 "Return a composite sort condition based on the functions in FUNC."
594 (let ((function (car funs))
597 (when (consp function)
600 ((eq (car function) 'not)
601 (setq function (cadr function)
604 ((gnus-functionp function)
608 (error "Invalid sort spec: %s" function))))
610 `(or (,function ,first ,last)
611 (and (not (,function ,last ,first))
612 ,(gnus-make-sort-function-1 (cdr funs))))
613 `(,function ,first ,last))))
615 (defun gnus-turn-off-edit-menu (type)
616 "Turn off edit menu in `gnus-TYPE-mode-map'."
617 (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
618 [menu-bar edit] 'undefined))
620 (defun gnus-prin1 (form)
621 "Use `prin1' on FORM in the current buffer.
622 Bind `print-quoted' and `print-readably' to t while printing."
623 (let ((print-quoted t)
625 (print-escape-multibyte nil)
626 print-level print-length)
627 (prin1 form (current-buffer))))
629 (defun gnus-prin1-to-string (form)
630 "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
631 (let ((print-quoted t)
633 (prin1-to-string form)))
635 (defun gnus-make-directory (directory)
636 "Make DIRECTORY (and all its parents) if it doesn't exist."
638 (let ((file-name-coding-system nnmail-pathname-coding-system))
640 (not (file-exists-p directory)))
641 (make-directory directory t)))
644 (defun gnus-write-buffer (file)
645 "Write the current buffer's contents to FILE."
646 ;; Make sure the directory exists.
647 (gnus-make-directory (file-name-directory file))
648 (let ((file-name-coding-system nnmail-pathname-coding-system))
650 (write-region (point-min) (point-max) file nil 'quietly)))
652 (defun gnus-delete-file (file)
653 "Delete FILE if it exists."
654 (when (file-exists-p file)
657 (defun gnus-strip-whitespace (string)
658 "Return STRING stripped of all whitespace."
659 (while (string-match "[\r\n\t ]+" string)
660 (setq string (replace-match "" t t string)))
663 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
664 "The same as `put-text-property', but don't put this prop on any newlines in the region."
669 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
670 (gnus-put-text-property beg (match-beginning 0) prop val)
672 (gnus-put-text-property beg (point) prop val)))))
674 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
675 "The same as `put-text-property', but don't put this prop on any newlines in the region."
680 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
682 (gnus-make-overlay beg (match-beginning 0))
685 (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
687 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
689 "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
692 (when (get-text-property b 'gnus-face)
693 (setq b (next-single-property-change b 'gnus-face nil end)))
696 (gnus-put-text-property
697 b (setq b (next-single-property-change b 'gnus-face nil end))
700 ;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
701 ;;; The primary idea here is to try to protect internal datastructures
702 ;;; from becoming corrupted when the user hits C-g, or if a hook or
703 ;;; similar blows up. Often in Gnus multiple tables/lists need to be
704 ;;; updated at the same time, or information can be lost.
706 (defvar gnus-atomic-be-safe t
707 "If t, certain operations will be protected from interruption by C-g.")
709 (defmacro gnus-atomic-progn (&rest forms)
710 "Evaluate FORMS atomically, which means to protect the evaluation
711 from being interrupted by the user. An error from the forms themselves
712 will return without finishing the operation. Since interrupts from
713 the user are disabled, it is recommended that only the most minimal
714 operations are performed by FORMS. If you wish to assign many
715 complicated values atomically, compute the results into temporary
716 variables and then do only the assignment atomically."
717 `(let ((inhibit-quit gnus-atomic-be-safe))
720 (put 'gnus-atomic-progn 'lisp-indent-function 0)
722 (defmacro gnus-atomic-progn-assign (protect &rest forms)
723 "Evaluate FORMS, but insure that the variables listed in PROTECT
724 are not changed if anything in FORMS signals an error or otherwise
725 non-locally exits. The variables listed in PROTECT are updated atomically.
726 It is safe to use gnus-atomic-progn-assign with long computations.
728 Note that if any of the symbols in PROTECT were unbound, they will be
729 set to nil on a sucessful assignment. In case of an error or other
730 non-local exit, it will still be unbound."
731 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
732 (concat (symbol-name x)
736 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
738 (temp-sym-let (mapcar (lambda (x) (list (car x)
739 `(and (boundp ',(cadr x))
742 (sym-temp-let sym-temp-map)
743 (temp-sym-assign (apply 'append temp-sym-map))
744 (sym-temp-assign (apply 'append sym-temp-map))
745 (result (make-symbol "result-tmp")))
746 `(let (,@temp-sym-let
749 (setq ,result (progn ,@forms))
750 (setq ,@temp-sym-assign))
751 (let ((inhibit-quit gnus-atomic-be-safe))
752 (setq ,@sym-temp-assign))
755 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
756 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
758 (defmacro gnus-atomic-setq (&rest pairs)
759 "Similar to setq, except that the real symbols are only assigned when
760 there are no errors. And when the real symbols are assigned, they are
761 done so atomically. If other variables might be changed via side-effect,
762 see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
763 with potentially long computations."
767 (push (car tpairs) syms)
768 (setq tpairs (cddr tpairs)))
769 `(gnus-atomic-progn-assign ,syms
772 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
775 ;;; Functions for saving to babyl/mail files.
777 (defvar rmail-default-rmail-file)
778 (defun gnus-output-to-rmail (filename &optional ask)
779 "Append the current article to an Rmail file named FILENAME."
781 ;; Most of these codes are borrowed from rmailout.el.
782 (setq filename (expand-file-name filename))
783 (setq rmail-default-rmail-file filename)
784 (let ((artbuf (current-buffer))
785 (tmpbuf (get-buffer-create " *Gnus-output*")))
787 (or (get-file-buffer filename)
788 (file-exists-p filename)
791 (concat "\"" filename "\" does not exist, create it? ")))
792 (let ((file-buffer (create-file-buffer filename)))
794 (set-buffer file-buffer)
795 (rmail-insert-rmail-file-header)
796 (let ((require-final-newline nil)
797 (coding-system-for-write mm-text-coding-system))
798 (gnus-write-buffer filename)))
799 (kill-buffer file-buffer))
800 (error "Output file does not exist")))
803 (insert-buffer-substring artbuf)
804 (gnus-convert-article-to-rmail)
805 ;; Decide whether to append to a file or to an Emacs buffer.
806 (let ((outbuf (get-file-buffer filename)))
808 (let ((file-name-coding-system nnmail-pathname-coding-system))
809 (mm-append-to-file (point-min) (point-max) filename))
810 ;; File has been visited, in buffer OUTBUF.
812 (let ((buffer-read-only nil)
813 (msg (and (boundp 'rmail-current-message)
814 (symbol-value 'rmail-current-message))))
815 ;; If MSG is non-nil, buffer is in RMAIL mode.
818 (narrow-to-region (point-max) (point-max)))
819 (insert-buffer-substring tmpbuf)
821 (goto-char (point-min))
823 (search-backward "\n\^_")
824 (narrow-to-region (point) (point-max))
825 (rmail-count-new-messages t)
826 (when (rmail-summary-exists)
827 (rmail-select-summary
828 (rmail-update-summary)))
829 (rmail-count-new-messages t)
830 (rmail-show-message msg))
832 (kill-buffer tmpbuf)))
834 (defun gnus-output-to-mail (filename &optional ask)
835 "Append the current article to a mail file named FILENAME."
836 (setq filename (expand-file-name filename))
837 (let ((artbuf (current-buffer))
838 (tmpbuf (get-buffer-create " *Gnus-output*")))
840 ;; Create the file, if it doesn't exist.
841 (when (and (not (get-file-buffer filename))
842 (not (file-exists-p filename)))
845 (concat "\"" filename "\" does not exist, create it? ")))
846 (let ((file-buffer (create-file-buffer filename)))
848 (set-buffer file-buffer)
849 (let ((require-final-newline nil)
850 (coding-system-for-write mm-text-coding-system))
851 (gnus-write-buffer filename)))
852 (kill-buffer file-buffer))
853 (error "Output file does not exist")))
856 (insert-buffer-substring artbuf)
857 (goto-char (point-min))
858 (if (looking-at "From ")
860 (insert "From nobody " (current-time-string) "\n"))
861 (let (case-fold-search)
862 (while (re-search-forward "^From " nil t)
865 ;; Decide whether to append to a file or to an Emacs buffer.
866 (let ((outbuf (get-file-buffer filename)))
868 (let ((buffer-read-only nil))
870 (goto-char (point-max))
872 (unless (looking-at "\n\n")
873 (goto-char (point-max))
877 (goto-char (point-max))
878 (let ((file-name-coding-system nnmail-pathname-coding-system))
879 (mm-append-to-file (point-min) (point-max) filename))))
880 ;; File has been visited, in buffer OUTBUF.
882 (let ((buffer-read-only nil))
883 (goto-char (point-max))
887 (insert-buffer-substring tmpbuf)))))
888 (kill-buffer tmpbuf)))
890 (defun gnus-convert-article-to-rmail ()
891 "Convert article in current buffer to Rmail message format."
892 (let ((buffer-read-only nil))
893 ;; Convert article directly into Babyl format.
894 (goto-char (point-min))
895 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
896 (while (search-forward "\n\^_" nil t) ;single char
897 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
898 (goto-char (point-max))
901 (defun gnus-map-function (funs arg)
902 "Applies the result of the first function in FUNS to the second, and so on.
903 ARG is passed to the first function."
906 (setq arg (funcall (pop myfuns) arg)))
909 (defun gnus-run-hooks (&rest funcs)
910 "Does the same as `run-hooks', but saves excursion."
911 (let ((buf (current-buffer)))
913 (apply 'run-hooks funcs)
918 (defvar gnus-group-buffer) ; Compiler directive
919 (defun gnus-alive-p ()
920 "Say whether Gnus is running or not."
921 (and (boundp 'gnus-group-buffer)
922 (get-buffer gnus-group-buffer)
924 (set-buffer gnus-group-buffer)
925 (eq major-mode 'gnus-group-mode))))
927 (defun gnus-remove-duplicates (list)
928 (let (new (tail list))
930 (or (member (car tail) new)
931 (setq new (cons (car tail) new)))
932 (setq tail (cdr tail)))
935 (defun gnus-delete-if (predicate list)
936 "Delete elements from LIST that satisfy PREDICATE."
939 (unless (funcall predicate (car list))
940 (push (car list) out))
944 (if (fboundp 'assq-delete-all)
945 (defalias 'gnus-delete-alist 'assq-delete-all)
946 (defun gnus-delete-alist (key alist)
947 "Delete from ALIST all elements whose car is KEY.
948 Return the modified alist."
950 (while (setq entry (assq key alist))
951 (setq alist (delq entry alist)))
954 (defmacro gnus-pull (key alist &optional assoc-p)
955 "Modify ALIST to be without KEY."
956 (unless (symbolp alist)
957 (error "Not a symbol: %s" alist))
958 (let ((fun (if assoc-p 'assoc 'assq)))
959 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
961 (defun gnus-globalify-regexp (re)
962 "Returns a regexp that matches a whole line, iff RE matches a part of it."
963 (concat (unless (string-match "^\\^" re) "^.*")
965 (unless (string-match "\\$$" re) ".*$")))
967 (defun gnus-set-window-start (&optional point)
968 "Set the window start to POINT, or (point) if nil."
969 (let ((win (gnus-get-buffer-window (current-buffer) t)))
971 (set-window-start win (or point (point))))))
973 (defun gnus-annotation-in-region-p (b e)
975 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
976 (text-property-any b e 'gnus-undeletable t)))
978 (defun gnus-or (&rest elems)
979 "Return non-nil if any of the elements are non-nil."
985 (defun gnus-and (&rest elems)
986 "Return non-nil if all of the elements are non-nil."
993 (defun gnus-write-active-file (file hashtb &optional full-names)
994 (let ((coding-system-for-write nnmail-active-file-coding-system))
1001 (insert (format "%S %d %d y\n"
1004 (intern (gnus-group-real-name (symbol-name sym))))
1005 (or (cdr (symbol-value sym))
1006 (car (symbol-value sym)))
1007 (car (symbol-value sym))))))
1009 (goto-char (point-max))
1010 (while (search-backward "\\." nil t)
1013 (if (fboundp 'union)
1014 (defalias 'gnus-union 'union)
1015 (defun gnus-union (l1 l2)
1016 "Set union of lists L1 and L2."
1017 (cond ((null l1) l2)
1021 (or (>= (length l1) (length l2))
1022 (setq l1 (prog1 l2 (setq l2 l1))))
1024 (or (member (car l2) l1)
1029 (defun gnus-add-text-properties-when
1030 (property value start end properties &optional object)
1031 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1034 (< start end) ;; XEmacs will loop for every when start=end.
1035 (setq point (text-property-not-all start end property value)))
1036 (gnus-add-text-properties start point properties object)
1037 (setq start (text-property-any point end property value)))
1039 (gnus-add-text-properties start end properties object))))
1041 (defun gnus-remove-text-properties-when
1042 (property value start end properties &optional object)
1043 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1047 (setq point (text-property-not-all start end property value)))
1048 (remove-text-properties start point properties object)
1049 (setq start (text-property-any point end property value)))
1051 (remove-text-properties start end properties object))
1054 (defun gnus-string-equal (x y)
1055 "Like `string-equal', except it compares case-insensitively."
1056 (and (= (length x) (length y))
1057 (or (string-equal x y)
1058 (string-equal (downcase x) (downcase y)))))
1060 (defcustom gnus-use-byte-compile t
1061 "If non-nil, byte-compile crucial run-time codes.
1062 Setting it to `nil' has no effect after first time running
1063 `gnus-byte-compile'."
1066 :group 'gnus-various)
1068 (defun gnus-byte-compile (form)
1069 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1070 (if gnus-use-byte-compile
1073 ;; Work around a bug in XEmacs 21.4
1074 (require 'byte-optimize)
1077 (defalias 'gnus-byte-compile 'byte-compile)
1078 (byte-compile form))
1081 (defun gnus-remassoc (key alist)
1082 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1083 The modified LIST is returned. If the first member
1084 of LIST has a car that is `equal' to KEY, there is no way to remove it
1085 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1086 sure of changing the value of `foo'."
1088 (if (equal key (caar alist))
1090 (setcdr alist (gnus-remassoc key (cdr alist)))
1093 (defun gnus-update-alist-soft (key value alist)
1095 (cons (cons key value) (gnus-remassoc key alist))
1096 (gnus-remassoc key alist)))
1098 (defun gnus-create-info-command (node)
1099 "Create a command that will go to info NODE."
1102 ,(concat "Enter the info system at node " node)
1103 (Info-goto-node ,node)
1104 (setq gnus-info-buffer (current-buffer))
1105 (gnus-configure-windows 'info)))
1107 (defun gnus-not-ignore (&rest args)
1110 (defvar gnus-directory-sep-char-regexp "/"
1111 "The regexp of directory separator character.
1112 If you find some problem with the directory separator character, try
1113 \"[/\\\\\]\" for some systems.")
1115 (defun gnus-url-unhex (x)
1122 (defun gnus-url-unhex-string (str &optional allow-newlines)
1123 "Remove %XXX embedded spaces, etc in a url.
1124 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1125 decoding of carriage returns and line feeds in the string, which is normally
1126 forbidden in URL encoding."
1127 (setq str (or (mm-subst-char-in-string ?+ ? str) ""))
1129 (case-fold-search t))
1130 (while (string-match "%[0-9a-f][0-9a-f]" str)
1131 (let* ((start (match-beginning 0))
1132 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1134 (gnus-url-unhex (elt str (+ start 2))))))
1136 tmp (substring str 0 start)
1139 (char-to-string code))
1140 ((or (= code ?\n) (= code ?\r))
1142 (t (char-to-string code))))
1143 str (substring str (match-end 0)))))
1144 (setq tmp (concat tmp str))
1147 (defun gnus-make-predicate (spec)
1148 "Transform SPEC into a function that can be called.
1149 SPEC is a predicate specifier that contains stuff like `or', `and',
1150 `not', lists and functions. The functions all take one parameter."
1151 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1153 (defun gnus-make-predicate-1 (spec)
1158 (if (memq (car spec) '(or and not))
1159 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1160 (error "Invalid predicate specifier: %s" spec)))))
1162 (defun gnus-local-map-property (map)
1163 "Return a list suitable for a text property list specifying keymap MAP."
1167 ((>= emacs-major-version 21)
1170 (list 'local-map map))))
1172 (defun gnus-completing-read (prompt table &optional predicate require-match
1175 (not (boundp history)))
1178 (if (symbol-value history)
1179 (concat prompt " (" (car (symbol-value history)) "): ")
1180 (concat prompt ": "))
1186 (car (symbol-value history))))
1188 (defun gnus-graphic-display-p ()
1189 (or (and (fboundp 'display-graphic-p)
1190 (display-graphic-p))
1191 ;;;!!!This is bogus. Fixme!
1192 (and (featurep 'xemacs)
1195 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1196 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1198 (defmacro gnus-parse-without-error (&rest body)
1199 "Allow continuing onto the next line even if an error occurs."
1200 `(while (not (eobp))
1204 (goto-char (point-max)))
1206 (gnus-error 4 "Invalid data on line %d"
1207 (count-lines (point-min) (point)))
1208 (forward-line 1)))))
1210 (defun gnus-cache-file-contents (file variable function)
1211 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1212 (let ((time (nth 5 (file-attributes file)))
1214 (if (or (null (setq value (symbol-value variable)))
1215 (not (equal (car value) file))
1216 (not (equal (nth 1 value) time)))
1218 (setq contents (funcall function file))
1219 (set variable (list file time contents))
1223 (defun gnus-multiple-choice (prompt choice &optional idx)
1224 "Ask user a multiple choice question.
1225 CHOICE is a list of the choice char and help message at IDX."
1227 (save-window-excursion
1230 (message "%s (%s?): "
1232 (mapconcat (lambda (s) (char-to-string (car s)))
1234 (setq tchar (read-char))
1235 (when (not (assq tchar choice))
1237 (setq buf (get-buffer-create "*Gnus Help*"))
1239 (fundamental-mode) ; for Emacs 20.4+
1240 (buffer-disable-undo)
1242 (insert prompt ":\n\n")
1249 ;; find the longest string to display
1251 (setq n (length (nth idx (car list))))
1254 (setq list (cdr list)))
1255 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1256 (setq n (/ (1- (window-width)) max)) ; items per line
1257 (setq width (/ (1- (window-width)) n)) ; width of each item
1258 ;; insert `n' items, each in a field of width `width'
1263 (delete-char -1) ; the `\n' takes a char
1265 (setq pad (- width 3))
1266 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1267 (insert (format format (caar alist) (nth idx (car alist))))
1268 (setq alist (cdr alist))
1269 (setq i (1+ i))))))))
1270 (if (buffer-live-p buf)
1274 (defun gnus-select-frame-set-input-focus (frame)
1275 "Select FRAME, raise it, and set input focus, if possible."
1276 (cond ((featurep 'xemacs)
1278 (select-frame frame)
1279 (focus-frame frame))
1280 ;; The function `select-frame-set-input-focus' won't set
1281 ;; the input focus under Emacs 21.2 and X window system.
1282 ;;((fboundp 'select-frame-set-input-focus)
1283 ;; (defalias 'gnus-select-frame-set-input-focus
1284 ;; 'select-frame-set-input-focus)
1285 ;; (select-frame-set-input-focus frame))
1288 (select-frame frame)
1289 (cond ((and (eq window-system 'x)
1290 (fboundp 'x-focus-frame))
1291 (x-focus-frame frame))
1292 ((eq window-system 'w32)
1293 (w32-focus-frame frame)))
1294 (when focus-follows-mouse
1295 (set-mouse-position frame (1- (frame-width frame)) 0)))))
1297 (defun gnus-frame-or-window-display-name (object)
1298 "Given a frame or window, return the associated display name.
1299 Return nil otherwise."
1300 (if (featurep 'xemacs)
1301 (device-connection (dfw-device object))
1302 (if (or (framep object)
1303 (and (windowp object)
1304 (setq object (window-frame object))))
1305 (let ((display (frame-parameter object 'display)))
1306 (if (and (stringp display)
1307 ;; Exclude invalid display names.
1308 (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1312 (provide 'gnus-util)
1314 ;;; gnus-util.el ends here