1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003
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 ;; Fixme: Why not `truncate-string-to-width'?
108 (defsubst gnus-limit-string (str width)
109 (if (> (length str) width)
110 (substring str 0 width)
113 (defsubst gnus-goto-char (point)
114 (and point (goto-char point)))
116 (defmacro gnus-buffer-exists-p (buffer)
117 `(let ((buffer ,buffer))
119 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
122 (defalias 'gnus-point-at-bol
123 (if (fboundp 'point-at-bol)
125 'line-beginning-position))
127 (defalias 'gnus-point-at-eol
128 (if (fboundp 'point-at-eol)
132 ;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
133 ;; XEmacs. In Emacs we don't need to call `make-local-hook' first.
134 ;; It's harmless, though, so the main purpose of this alias is to shut
135 ;; up the byte compiler.
136 (defalias 'gnus-make-local-hook
137 (if (eq (get 'make-local-hook 'byte-compile)
138 'byte-compile-obsolete)
140 'make-local-hook)) ; XEmacs
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 (gnus-point-at-bol)
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-fetch-original-field (field)
207 "Fetch FIELD from the original version of the current article."
208 (with-current-buffer gnus-original-article-buffer
209 (gnus-fetch-field field)))
212 (defun gnus-goto-colon ()
214 (let ((eol (gnus-point-at-eol)))
215 (goto-char (or (text-property-any (point) eol 'gnus-position t)
216 (search-forward ":" eol t)
219 (defun gnus-decode-newsgroups (newsgroups group &optional method)
220 (let ((method (or method (gnus-find-method-for-group group))))
221 (mapconcat (lambda (group)
222 (gnus-group-name-decode group (gnus-group-name-charset
224 (message-tokenize-header newsgroups)
227 (defun gnus-remove-text-with-property (prop)
228 "Delete all text in the current buffer with text property PROP."
230 (goto-char (point-min))
232 (while (get-text-property (point) prop)
234 (goto-char (next-single-property-change (point) prop nil (point-max))))))
237 (defun gnus-newsgroup-directory-form (newsgroup)
238 "Make hierarchical directory name from NEWSGROUP name."
239 (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
240 (idx (string-match ":" newsgroup)))
242 (if idx (substring newsgroup 0 idx))
244 (nnheader-replace-chars-in-string
245 (if idx (substring newsgroup (1+ idx)) newsgroup)
248 (defun gnus-newsgroup-savable-name (group)
249 ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
251 (nnheader-replace-chars-in-string group ?/ ?.))
253 (defun gnus-string> (s1 s2)
254 (not (or (string< s1 s2)
259 (defun gnus-file-newer-than (file date)
260 (let ((fdate (nth 5 (file-attributes file))))
261 (or (> (car fdate) (car date))
262 (and (= (car fdate) (car date))
263 (> (nth 1 fdate) (nth 1 date))))))
267 (defmacro gnus-local-set-keys (&rest plist)
268 "Set the keys in PLIST in the current keymap."
269 `(gnus-define-keys-1 (current-local-map) ',plist))
271 (defmacro gnus-define-keys (keymap &rest plist)
272 "Define all keys in PLIST in KEYMAP."
273 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
275 (defmacro gnus-define-keys-safe (keymap &rest plist)
276 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
277 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
279 (put 'gnus-define-keys 'lisp-indent-function 1)
280 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
281 (put 'gnus-local-set-keys 'lisp-indent-function 1)
283 (defmacro gnus-define-keymap (keymap &rest plist)
284 "Define all keys in PLIST in KEYMAP."
285 `(gnus-define-keys-1 ,keymap (quote ,plist)))
287 (put 'gnus-define-keymap 'lisp-indent-function 1)
289 (defun gnus-define-keys-1 (keymap plist &optional safe)
291 (error "Can't set keys in a null keymap"))
292 (cond ((symbolp keymap)
293 (setq keymap (symbol-value keymap)))
296 (set (car keymap) nil)
297 (define-prefix-command (car keymap))
298 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
299 (setq keymap (symbol-value (car keymap)))))
302 (when (symbolp (setq key (pop plist)))
303 (setq key (symbol-value key)))
305 (eq (lookup-key keymap key) 'undefined))
306 (define-key keymap key (pop plist))
309 (defun gnus-completing-read-with-default (default prompt &rest args)
310 ;; Like `completing-read', except that DEFAULT is the default argument.
311 (let* ((prompt (if default
312 (concat prompt " (default " default ") ")
313 (concat prompt " ")))
314 (answer (apply 'completing-read prompt args)))
315 (if (or (null answer) (zerop (length answer)))
319 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
321 (defun gnus-y-or-n-p (prompt)
326 (defun gnus-yes-or-no-p (prompt)
331 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
332 ;; age-depending date representations. (e.g. just the time if it's
333 ;; from today, the day of the week if it's within the last 7 days and
334 ;; the full date if it's older)
335 (defun gnus-seconds-today ()
336 "Returns the number of seconds passed today"
337 (let ((now (decode-time (current-time))))
338 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
340 (defun gnus-seconds-month ()
341 "Returns the number of seconds passed this month"
342 (let ((now (decode-time (current-time))))
343 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
344 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
346 (defun gnus-seconds-year ()
347 "Returns the number of seconds passed this year"
348 (let ((now (decode-time (current-time)))
349 (days (format-time-string "%j" (current-time))))
350 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
351 (* (- (string-to-number days) 1) 3600 24))))
353 (defvar gnus-user-date-format-alist
354 '(((gnus-seconds-today) . "%k:%M")
355 (604800 . "%a %k:%M") ;;that's one week
356 ((gnus-seconds-month) . "%a %d")
357 ((gnus-seconds-year) . "%b %d")
358 (t . "%b %d '%y")) ;;this one is used when no
360 "Specifies date format depending on age of article.
361 This is an alist of items (AGE . FORMAT). AGE can be a number (of
362 seconds) or a Lisp expression evaluating to a number. When the age of
363 the article is less than this number, then use `format-time-string'
364 with the corresponding FORMAT for displaying the date of the article.
365 If AGE is not a number or a Lisp expression evaluating to a
366 non-number, then the corresponding FORMAT is used as a default value.
368 Note that the list is processed from the beginning, so it should be
369 sorted by ascending AGE. Also note that items following the first
370 non-number AGE will be ignored.
372 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
373 and `gnus-seconds-year' in the AGE spec. They return the number of
374 seconds passed since the start of today, of this month, of this year,
377 (defun gnus-user-date (messy-date)
378 "Format the messy-date acording to gnus-user-date-format-alist.
379 Returns \" ? \" if there's bad input or if an other error occurs.
380 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
382 (let* ((messy-date (safe-date-to-time messy-date))
384 ;;If we don't find something suitable we'll use this one
385 (my-format "%b %m '%y")
386 (high (lsh (- (car now) (car messy-date)) 16)))
387 (if (and (> high -1) (= (logand high 65535) 0))
388 ;;overflow and bad input
389 (let* ((difference (+ high (- (car (cdr now))
390 (car (cdr messy-date)))))
391 (templist gnus-user-date-format-alist)
392 (top (eval (caar templist))))
393 (while (if (numberp top) (< top difference) (not top))
395 (setq templist (cdr templist))
396 (setq top (eval (caar templist)))))
397 (if (stringp (cdr (car templist)))
398 (setq my-format (cdr (car templist))))))
399 (format-time-string (eval my-format) messy-date))
401 ;;end of Frank's code
403 (defun gnus-dd-mmm (messy-date)
404 "Return a string like DD-MMM from a big messy string."
406 (format-time-string "%d-%b" (safe-date-to-time messy-date))
409 (defmacro gnus-date-get-time (date)
410 "Convert DATE string to Emacs time.
411 Cache the result as a text property stored in DATE."
412 ;; Either return the cached value...
416 (or (get-text-property 0 'gnus-time d)
417 ;; or compute the value...
418 (let ((time (safe-date-to-time d)))
419 ;; and store it back in the string.
420 (put-text-property 0 1 'gnus-time time d)
423 (defsubst gnus-time-iso8601 (time)
424 "Return a string of TIME in YYYYMMDDTHHMMSS format."
425 (format-time-string "%Y%m%dT%H%M%S" time))
427 (defun gnus-date-iso8601 (date)
428 "Convert the DATE to YYYYMMDDTHHMMSS."
430 (gnus-time-iso8601 (gnus-date-get-time date))
433 (defun gnus-mode-string-quote (string)
434 "Quote all \"%\"'s in STRING."
435 (gnus-replace-in-string string "%" "%%"))
437 ;; Make a hash table (default and minimum size is 256).
438 ;; Optional argument HASHSIZE specifies the table size.
439 (defun gnus-make-hashtable (&optional hashsize)
440 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
442 ;; Make a number that is suitable for hashing; bigger than MIN and
443 ;; equal to some 2^x. Many machines (such as sparcs) do not have a
444 ;; hardware modulo operation, so they implement it in software. On
445 ;; many sparcs over 50% of the time to intern is spent in the modulo.
446 ;; Yes, it's slower than actually computing the hash from the string!
447 ;; So we use powers of 2 so people can optimize the modulo to a mask.
448 (defun gnus-create-hash-size (min)
454 (defcustom gnus-verbose 7
455 "*Integer that says how verbose Gnus should be.
456 The higher the number, the more messages Gnus will flash to say what
457 it's doing. At zero, Gnus will be totally mute; at five, Gnus will
458 display most important messages; and at ten, Gnus will keep on
459 jabbering all the time."
463 (defun gnus-message (level &rest args)
464 "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
466 Guideline for numbers:
467 1 - error messages, 3 - non-serious error messages, 5 - messages for things
468 that take a long time, 7 - not very important messages on stuff, 9 - messages
470 (if (<= level gnus-verbose)
471 (apply 'message args)
472 ;; We have to do this format thingy here even if the result isn't
473 ;; shown - the return value has to be the same as the return value
475 (apply 'format args)))
477 (defun gnus-error (level &rest args)
478 "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
479 (when (<= (floor level) gnus-verbose)
480 (apply 'message args)
483 (when (and (floatp level)
484 (not (zerop (setq duration (* 10 (- level (floor level)))))))
485 (sit-for duration))))
488 (defun gnus-split-references (references)
489 "Return a list of Message-IDs in REFERENCES."
492 (while (string-match "<[^<]+[^< \t]" references beg)
493 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
497 (defsubst gnus-parent-id (references &optional n)
498 "Return the last Message-ID in REFERENCES.
499 If N, return the Nth ancestor instead."
500 (when (and references
501 (not (zerop (length references))))
503 (let ((ids (inline (gnus-split-references references))))
504 (while (nthcdr n ids)
505 (setq ids (cdr ids)))
507 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
508 (match-string 1 references)))))
510 (defun gnus-buffer-live-p (buffer)
511 "Say whether BUFFER is alive or not."
514 (buffer-name (get-buffer buffer))))
516 (defun gnus-horizontal-recenter ()
517 "Recenter the current buffer horizontally."
518 (if (< (current-column) (/ (window-width) 2))
519 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
520 (let* ((orig (point))
521 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
524 ;; Find the longest line currently displayed in the window.
525 (goto-char (window-start))
526 (while (and (not (eobp))
529 (setq max (max max (current-column)))
532 ;; Scroll horizontally to center (sort of) the point.
533 (if (> max (window-width))
535 (gnus-get-buffer-window (current-buffer) t)
536 (min (- (current-column) (/ (window-width) 3))
537 (+ 2 (- max (window-width)))))
538 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
541 (defun gnus-read-event-char (&optional prompt)
542 "Get the next event."
543 (let ((event (read-event prompt)))
544 ;; should be gnus-characterp, but this can't be called in XEmacs anyway
545 (cons (and (numberp event) event) event)))
547 (defun gnus-sortable-date (date)
548 "Make string suitable for sorting from DATE."
549 (gnus-time-iso8601 (date-to-time date)))
551 (defun gnus-copy-file (file &optional to)
554 (list (read-file-name "Copy file: " default-directory)
555 (read-file-name "Copy file to: " default-directory)))
557 (setq to (read-file-name "Copy file to: " default-directory)))
558 (when (file-directory-p to)
559 (setq to (concat (file-name-as-directory to)
560 (file-name-nondirectory file))))
563 (defvar gnus-work-buffer " *gnus work*")
565 (defun gnus-set-work-buffer ()
566 "Put point in the empty Gnus work buffer."
567 (if (get-buffer gnus-work-buffer)
569 (set-buffer gnus-work-buffer)
571 (set-buffer (gnus-get-buffer-create gnus-work-buffer))
572 (kill-all-local-variables)
573 (mm-enable-multibyte)))
575 (defmacro gnus-group-real-name (group)
576 "Find the real name of a foreign newsgroup."
577 `(let ((gname ,group))
578 (if (string-match "^[^:]+:" gname)
579 (substring gname (match-end 0))
582 (defun gnus-make-sort-function (funs)
583 "Return a composite sort condition based on the functions in FUNC."
585 ;; Just a simple function.
586 ((functionp funs) funs)
587 ;; No functions at all.
589 ;; A list of functions.
594 ,(gnus-make-sort-function-1 (reverse funs)))))
595 ;; A list containing just one function.
599 (defun gnus-make-sort-function-1 (funs)
600 "Return a composite sort condition based on the functions in FUNC."
601 (let ((function (car funs))
604 (when (consp function)
607 ((eq (car function) 'not)
608 (setq function (cadr function)
611 ((functionp function)
615 (error "Invalid sort spec: %s" function))))
617 `(or (,function ,first ,last)
618 (and (not (,function ,last ,first))
619 ,(gnus-make-sort-function-1 (cdr funs))))
620 `(,function ,first ,last))))
622 (defun gnus-turn-off-edit-menu (type)
623 "Turn off edit menu in `gnus-TYPE-mode-map'."
624 (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
625 [menu-bar edit] 'undefined))
627 (defun gnus-prin1 (form)
628 "Use `prin1' on FORM in the current buffer.
629 Bind `print-quoted' and `print-readably' to t while printing."
630 (let ((print-quoted t)
632 (print-escape-multibyte nil)
633 print-level print-length)
634 (prin1 form (current-buffer))))
636 (defun gnus-prin1-to-string (form)
637 "The same as `prin1'.
638 Bind `print-quoted' and `print-readably' to t, and `print-length'
639 and `print-level' to nil."
640 (let ((print-quoted t)
644 (prin1-to-string form)))
646 (defun gnus-make-directory (directory)
647 "Make DIRECTORY (and all its parents) if it doesn't exist."
649 (let ((file-name-coding-system nnmail-pathname-coding-system))
651 (not (file-exists-p directory)))
652 (make-directory directory t)))
655 (defun gnus-write-buffer (file)
656 "Write the current buffer's contents to FILE."
657 ;; Make sure the directory exists.
658 (gnus-make-directory (file-name-directory file))
659 (let ((file-name-coding-system nnmail-pathname-coding-system))
661 (write-region (point-min) (point-max) file nil 'quietly)))
663 (defun gnus-delete-file (file)
664 "Delete FILE if it exists."
665 (when (file-exists-p file)
668 (defun gnus-strip-whitespace (string)
669 "Return STRING stripped of all whitespace."
670 (while (string-match "[\r\n\t ]+" string)
671 (setq string (replace-match "" t t string)))
674 (defsubst gnus-put-text-property-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)
681 (gnus-put-text-property beg (match-beginning 0) prop val)
683 (gnus-put-text-property beg (point) prop val)))))
685 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
686 "The same as `put-text-property', but don't put this prop on any newlines in the region."
691 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
693 (gnus-make-overlay beg (match-beginning 0))
696 (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
698 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
700 "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
703 (when (get-text-property b 'gnus-face)
704 (setq b (next-single-property-change b 'gnus-face nil end)))
707 (gnus-put-text-property
708 b (setq b (next-single-property-change b 'gnus-face nil end))
711 (defmacro gnus-faces-at (position)
712 "Return a list of faces at POSITION."
713 (if (featurep 'xemacs)
714 `(let ((pos ,position))
715 (mapcar-extents 'extent-face
716 nil (current-buffer) pos pos nil 'face))
717 `(let ((pos ,position))
718 (delq nil (cons (get-text-property pos 'face)
721 (overlay-get overlay 'face))
722 (overlays-at pos)))))))
724 ;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
725 ;;; The primary idea here is to try to protect internal datastructures
726 ;;; from becoming corrupted when the user hits C-g, or if a hook or
727 ;;; similar blows up. Often in Gnus multiple tables/lists need to be
728 ;;; updated at the same time, or information can be lost.
730 (defvar gnus-atomic-be-safe t
731 "If t, certain operations will be protected from interruption by C-g.")
733 (defmacro gnus-atomic-progn (&rest forms)
734 "Evaluate FORMS atomically, which means to protect the evaluation
735 from being interrupted by the user. An error from the forms themselves
736 will return without finishing the operation. Since interrupts from
737 the user are disabled, it is recommended that only the most minimal
738 operations are performed by FORMS. If you wish to assign many
739 complicated values atomically, compute the results into temporary
740 variables and then do only the assignment atomically."
741 `(let ((inhibit-quit gnus-atomic-be-safe))
744 (put 'gnus-atomic-progn 'lisp-indent-function 0)
746 (defmacro gnus-atomic-progn-assign (protect &rest forms)
747 "Evaluate FORMS, but insure that the variables listed in PROTECT
748 are not changed if anything in FORMS signals an error or otherwise
749 non-locally exits. The variables listed in PROTECT are updated atomically.
750 It is safe to use gnus-atomic-progn-assign with long computations.
752 Note that if any of the symbols in PROTECT were unbound, they will be
753 set to nil on a successful assignment. In case of an error or other
754 non-local exit, it will still be unbound."
755 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
756 (concat (symbol-name x)
760 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
762 (temp-sym-let (mapcar (lambda (x) (list (car x)
763 `(and (boundp ',(cadr x))
766 (sym-temp-let sym-temp-map)
767 (temp-sym-assign (apply 'append temp-sym-map))
768 (sym-temp-assign (apply 'append sym-temp-map))
769 (result (make-symbol "result-tmp")))
770 `(let (,@temp-sym-let
773 (setq ,result (progn ,@forms))
774 (setq ,@temp-sym-assign))
775 (let ((inhibit-quit gnus-atomic-be-safe))
776 (setq ,@sym-temp-assign))
779 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
780 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
782 (defmacro gnus-atomic-setq (&rest pairs)
783 "Similar to setq, except that the real symbols are only assigned when
784 there are no errors. And when the real symbols are assigned, they are
785 done so atomically. If other variables might be changed via side-effect,
786 see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
787 with potentially long computations."
791 (push (car tpairs) syms)
792 (setq tpairs (cddr tpairs)))
793 `(gnus-atomic-progn-assign ,syms
796 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
799 ;;; Functions for saving to babyl/mail files.
801 (defvar rmail-default-rmail-file)
802 (defun gnus-output-to-rmail (filename &optional ask)
803 "Append the current article to an Rmail file named FILENAME."
805 ;; Most of these codes are borrowed from rmailout.el.
806 (setq filename (expand-file-name filename))
807 (setq rmail-default-rmail-file filename)
808 (let ((artbuf (current-buffer))
809 (tmpbuf (get-buffer-create " *Gnus-output*")))
811 (or (get-file-buffer filename)
812 (file-exists-p filename)
815 (concat "\"" filename "\" does not exist, create it? ")))
816 (let ((file-buffer (create-file-buffer filename)))
818 (set-buffer file-buffer)
819 (rmail-insert-rmail-file-header)
820 (let ((require-final-newline nil)
821 (coding-system-for-write mm-text-coding-system))
822 (gnus-write-buffer filename)))
823 (kill-buffer file-buffer))
824 (error "Output file does not exist")))
827 (insert-buffer-substring artbuf)
828 (gnus-convert-article-to-rmail)
829 ;; Decide whether to append to a file or to an Emacs buffer.
830 (let ((outbuf (get-file-buffer filename)))
832 (let ((file-name-coding-system nnmail-pathname-coding-system))
833 (mm-append-to-file (point-min) (point-max) filename))
834 ;; File has been visited, in buffer OUTBUF.
836 (let ((buffer-read-only nil)
837 (msg (and (boundp 'rmail-current-message)
838 (symbol-value 'rmail-current-message))))
839 ;; If MSG is non-nil, buffer is in RMAIL mode.
842 (narrow-to-region (point-max) (point-max)))
843 (insert-buffer-substring tmpbuf)
845 (goto-char (point-min))
847 (search-backward "\n\^_")
848 (narrow-to-region (point) (point-max))
849 (rmail-count-new-messages t)
850 (when (rmail-summary-exists)
851 (rmail-select-summary
852 (rmail-update-summary)))
853 (rmail-count-new-messages t)
854 (rmail-show-message msg))
856 (kill-buffer tmpbuf)))
858 (defun gnus-output-to-mail (filename &optional ask)
859 "Append the current article to a mail file named FILENAME."
860 (setq filename (expand-file-name filename))
861 (let ((artbuf (current-buffer))
862 (tmpbuf (get-buffer-create " *Gnus-output*")))
864 ;; Create the file, if it doesn't exist.
865 (when (and (not (get-file-buffer filename))
866 (not (file-exists-p filename)))
869 (concat "\"" filename "\" does not exist, create it? ")))
870 (let ((file-buffer (create-file-buffer filename)))
872 (set-buffer file-buffer)
873 (let ((require-final-newline nil)
874 (coding-system-for-write mm-text-coding-system))
875 (gnus-write-buffer filename)))
876 (kill-buffer file-buffer))
877 (error "Output file does not exist")))
880 (insert-buffer-substring artbuf)
881 (goto-char (point-min))
882 (if (looking-at "From ")
884 (insert "From nobody " (current-time-string) "\n"))
885 (let (case-fold-search)
886 (while (re-search-forward "^From " nil t)
889 ;; Decide whether to append to a file or to an Emacs buffer.
890 (let ((outbuf (get-file-buffer filename)))
892 (let ((buffer-read-only nil))
894 (goto-char (point-max))
896 (unless (looking-at "\n\n")
897 (goto-char (point-max))
901 (goto-char (point-max))
902 (let ((file-name-coding-system nnmail-pathname-coding-system))
903 (mm-append-to-file (point-min) (point-max) filename))))
904 ;; File has been visited, in buffer OUTBUF.
906 (let ((buffer-read-only nil))
907 (goto-char (point-max))
911 (insert-buffer-substring tmpbuf)))))
912 (kill-buffer tmpbuf)))
914 (defun gnus-convert-article-to-rmail ()
915 "Convert article in current buffer to Rmail message format."
916 (let ((buffer-read-only nil))
917 ;; Convert article directly into Babyl format.
918 (goto-char (point-min))
919 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
920 (while (search-forward "\n\^_" nil t) ;single char
921 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
922 (goto-char (point-max))
925 (defun gnus-map-function (funs arg)
926 "Applies the result of the first function in FUNS to the second, and so on.
927 ARG is passed to the first function."
929 (setq arg (funcall (pop funs) arg)))
932 (defun gnus-run-hooks (&rest funcs)
933 "Does the same as `run-hooks', but saves the current buffer."
935 (apply 'run-hooks funcs)))
939 (defvar gnus-group-buffer) ; Compiler directive
940 (defun gnus-alive-p ()
941 "Say whether Gnus is running or not."
942 (and (boundp 'gnus-group-buffer)
943 (get-buffer gnus-group-buffer)
945 (set-buffer gnus-group-buffer)
946 (eq major-mode 'gnus-group-mode))))
948 (defun gnus-remove-duplicates (list)
951 (or (member (car list) new)
952 (setq new (cons (car list) new)))
953 (setq list (cdr list)))
956 (defun gnus-remove-if (predicate list)
957 "Return a copy of LIST with all items satisfying PREDICATE removed."
960 (unless (funcall predicate (car list))
961 (push (car list) out))
962 (setq list (cdr list)))
965 (if (fboundp 'assq-delete-all)
966 (defalias 'gnus-delete-alist 'assq-delete-all)
967 (defun gnus-delete-alist (key alist)
968 "Delete from ALIST all elements whose car is KEY.
969 Return the modified alist."
971 (while (setq entry (assq key alist))
972 (setq alist (delq entry alist)))
975 (defmacro gnus-pull (key alist &optional assoc-p)
976 "Modify ALIST to be without KEY."
977 (unless (symbolp alist)
978 (error "Not a symbol: %s" alist))
979 (let ((fun (if assoc-p 'assoc 'assq)))
980 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
982 (defun gnus-globalify-regexp (re)
983 "Returns a regexp that matches a whole line, iff RE matches a part of it."
984 (concat (unless (string-match "^\\^" re) "^.*")
986 (unless (string-match "\\$$" re) ".*$")))
988 (defun gnus-set-window-start (&optional point)
989 "Set the window start to POINT, or (point) if nil."
990 (let ((win (gnus-get-buffer-window (current-buffer) t)))
992 (set-window-start win (or point (point))))))
994 (defun gnus-annotation-in-region-p (b e)
996 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
997 (text-property-any b e 'gnus-undeletable t)))
999 (defun gnus-or (&rest elems)
1000 "Return non-nil if any of the elements are non-nil."
1004 (throw 'found t)))))
1006 (defun gnus-and (&rest elems)
1007 "Return non-nil if all of the elements are non-nil."
1011 (throw 'found nil)))
1014 (defun gnus-write-active-file (file hashtb &optional full-names)
1015 (let ((coding-system-for-write nnmail-active-file-coding-system))
1016 (with-temp-file file
1022 (insert (format "%S %d %d y\n"
1025 (intern (gnus-group-real-name (symbol-name sym))))
1026 (or (cdr (symbol-value sym))
1027 (car (symbol-value sym)))
1028 (car (symbol-value sym))))))
1030 (goto-char (point-max))
1031 (while (search-backward "\\." nil t)
1034 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1035 (defmacro gnus-with-output-to-file (file &rest body)
1036 (let ((buffer (make-symbol "output-buffer"))
1037 (size (make-symbol "output-buffer-size"))
1038 (leng (make-symbol "output-buffer-length"))
1039 (append (make-symbol "output-buffer-append")))
1040 `(let* ((,size 131072)
1041 (,buffer (make-string ,size 0))
1046 (aset ,buffer ,leng c)
1048 (if (= ,size (setq ,leng (1+ ,leng)))
1049 (progn (write-region ,buffer nil ,file ,append 'no-msg)
1054 (let ((coding-system-for-write 'no-conversion))
1055 (write-region (substring ,buffer 0 ,leng) nil ,file
1056 ,append 'no-msg))))))
1058 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1059 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1061 (if (fboundp 'union)
1062 (defalias 'gnus-union 'union)
1063 (defun gnus-union (l1 l2)
1064 "Set union of lists L1 and L2."
1065 (cond ((null l1) l2)
1069 (or (>= (length l1) (length l2))
1070 (setq l1 (prog1 l2 (setq l2 l1))))
1072 (or (member (car l2) l1)
1077 (defun gnus-add-text-properties-when
1078 (property value start end properties &optional object)
1079 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1082 (< start end) ;; XEmacs will loop for every when start=end.
1083 (setq point (text-property-not-all start end property value)))
1084 (gnus-add-text-properties start point properties object)
1085 (setq start (text-property-any point end property value)))
1087 (gnus-add-text-properties start end properties object))))
1089 (defun gnus-remove-text-properties-when
1090 (property value start end properties &optional object)
1091 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1095 (setq point (text-property-not-all start end property value)))
1096 (remove-text-properties start point properties object)
1097 (setq start (text-property-any point end property value)))
1099 (remove-text-properties start end properties object))
1102 ;; This might use `compare-strings' to reduce consing in the
1103 ;; case-insensitive case, but it has to cope with null args.
1104 ;; (`string-equal' uses symbol print names.)
1105 (defun gnus-string-equal (x y)
1106 "Like `string-equal', except it compares case-insensitively."
1107 (and (= (length x) (length y))
1108 (or (string-equal x y)
1109 (string-equal (downcase x) (downcase y)))))
1111 (defcustom gnus-use-byte-compile t
1112 "If non-nil, byte-compile crucial run-time code.
1113 Setting it to nil has no effect after the first time `gnus-byte-compile'
1117 :group 'gnus-various)
1119 (defun gnus-byte-compile (form)
1120 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1121 (if gnus-use-byte-compile
1124 ;; Work around a bug in XEmacs 21.4
1125 (require 'byte-optimize)
1128 (defalias 'gnus-byte-compile
1130 (let ((byte-compile-warnings '(unresolved callargs redefine)))
1131 (byte-compile form))))
1132 (gnus-byte-compile form))
1135 (defun gnus-remassoc (key alist)
1136 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1137 The modified LIST is returned. If the first member
1138 of LIST has a car that is `equal' to KEY, there is no way to remove it
1139 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1140 sure of changing the value of `foo'."
1142 (if (equal key (caar alist))
1144 (setcdr alist (gnus-remassoc key (cdr alist)))
1147 (defun gnus-update-alist-soft (key value alist)
1149 (cons (cons key value) (gnus-remassoc key alist))
1150 (gnus-remassoc key alist)))
1152 (defun gnus-create-info-command (node)
1153 "Create a command that will go to info NODE."
1156 ,(concat "Enter the info system at node " node)
1157 (Info-goto-node ,node)
1158 (setq gnus-info-buffer (current-buffer))
1159 (gnus-configure-windows 'info)))
1161 (defun gnus-not-ignore (&rest args)
1164 (defvar gnus-directory-sep-char-regexp "/"
1165 "The regexp of directory separator character.
1166 If you find some problem with the directory separator character, try
1167 \"[/\\\\\]\" for some systems.")
1169 (defun gnus-url-unhex (x)
1176 (defun gnus-url-unhex-string (str &optional allow-newlines)
1177 "Remove %XX, embedded spaces, etc in a url.
1178 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1179 decoding of carriage returns and line feeds in the string, which is normally
1180 forbidden in URL encoding."
1181 (setq str (or (mm-subst-char-in-string ?+ ? str) ""))
1183 (case-fold-search t))
1184 (while (string-match "%[0-9a-f][0-9a-f]" str)
1185 (let* ((start (match-beginning 0))
1186 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1188 (gnus-url-unhex (elt str (+ start 2))))))
1190 tmp (substring str 0 start)
1193 (char-to-string code))
1194 ((or (= code ?\n) (= code ?\r))
1196 (t (char-to-string code))))
1197 str (substring str (match-end 0)))))
1198 (setq tmp (concat tmp str))
1201 (defun gnus-make-predicate (spec)
1202 "Transform SPEC into a function that can be called.
1203 SPEC is a predicate specifier that contains stuff like `or', `and',
1204 `not', lists and functions. The functions all take one parameter."
1205 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1207 (defun gnus-make-predicate-1 (spec)
1212 (if (memq (car spec) '(or and not))
1213 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1214 (error "Invalid predicate specifier: %s" spec)))))
1216 (defun gnus-local-map-property (map)
1217 "Return a list suitable for a text property list specifying keymap MAP."
1221 ((>= emacs-major-version 21)
1224 (list 'local-map map))))
1226 (defun gnus-completing-read (prompt table &optional predicate require-match
1229 (not (boundp history)))
1232 (if (symbol-value history)
1233 (concat prompt " (" (car (symbol-value history)) "): ")
1234 (concat prompt ": "))
1240 (car (symbol-value history))))
1242 (defun gnus-graphic-display-p ()
1243 (or (and (fboundp 'display-graphic-p)
1244 (display-graphic-p))
1245 ;;;!!!This is bogus. Fixme!
1246 (and (featurep 'xemacs)
1249 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1250 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1252 (defmacro gnus-parse-without-error (&rest body)
1253 "Allow continuing onto the next line even if an error occurs."
1254 `(while (not (eobp))
1258 (goto-char (point-max)))
1260 (gnus-error 4 "Invalid data on line %d"
1261 (count-lines (point-min) (point)))
1262 (forward-line 1)))))
1264 (defun gnus-cache-file-contents (file variable function)
1265 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1266 (let ((time (nth 5 (file-attributes file)))
1268 (if (or (null (setq value (symbol-value variable)))
1269 (not (equal (car value) file))
1270 (not (equal (nth 1 value) time)))
1272 (setq contents (funcall function file))
1273 (set variable (list file time contents))
1277 (defun gnus-multiple-choice (prompt choice &optional idx)
1278 "Ask user a multiple choice question.
1279 CHOICE is a list of the choice char and help message at IDX."
1281 (save-window-excursion
1284 (message "%s (%s): "
1286 (mapconcat (lambda (s) (char-to-string (car s)))
1288 (setq tchar (read-char))
1289 (when (not (assq tchar choice))
1291 (setq buf (get-buffer-create "*Gnus Help*"))
1293 (fundamental-mode) ; for Emacs 20.4+
1294 (buffer-disable-undo)
1296 (insert prompt ":\n\n")
1303 ;; find the longest string to display
1305 (setq n (length (nth idx (car list))))
1308 (setq list (cdr list)))
1309 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1310 (setq n (/ (1- (window-width)) max)) ; items per line
1311 (setq width (/ (1- (window-width)) n)) ; width of each item
1312 ;; insert `n' items, each in a field of width `width'
1317 (delete-char -1) ; the `\n' takes a char
1319 (setq pad (- width 3))
1320 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1321 (insert (format format (caar alist) (nth idx (car alist))))
1322 (setq alist (cdr alist))
1323 (setq i (1+ i))))))))
1324 (if (buffer-live-p buf)
1328 (defun gnus-select-frame-set-input-focus (frame)
1329 "Select FRAME, raise it, and set input focus, if possible."
1330 (cond ((featurep 'xemacs)
1332 (select-frame frame)
1333 (focus-frame frame))
1334 ;; The function `select-frame-set-input-focus' won't set
1335 ;; the input focus under Emacs 21.2 and X window system.
1336 ;;((fboundp 'select-frame-set-input-focus)
1337 ;; (defalias 'gnus-select-frame-set-input-focus
1338 ;; 'select-frame-set-input-focus)
1339 ;; (select-frame-set-input-focus frame))
1342 (select-frame frame)
1343 (cond ((and (eq window-system 'x)
1344 (fboundp 'x-focus-frame))
1345 (x-focus-frame frame))
1346 ((eq window-system 'w32)
1347 (w32-focus-frame frame)))
1348 (when focus-follows-mouse
1349 (set-mouse-position frame (1- (frame-width frame)) 0)))))
1351 (defun gnus-frame-or-window-display-name (object)
1352 "Given a frame or window, return the associated display name.
1353 Return nil otherwise."
1354 (if (featurep 'xemacs)
1355 (device-connection (dfw-device object))
1356 (if (or (framep object)
1357 (and (windowp object)
1358 (setq object (window-frame object))))
1359 (let ((display (frame-parameter object 'display)))
1360 (if (and (stringp display)
1361 ;; Exclude invalid display names.
1362 (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1366 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1367 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1368 "Apply FUNCTION to each element of the sequences, and make a list of the results.
1369 If there are several sequences, FUNCTION is called with that many arguments,
1370 and mapping stops as soon as the shortest sequence runs out. With just one
1371 sequence, this is like `mapcar'. With several, it is like the Common Lisp
1372 `mapcar' function extended to arbitrary sequence types."
1375 (let* ((seqs (cons seq1 seqs2_n))
1377 (heads (mapcar (lambda (seq)
1378 (make-symbol (concat "head"
1380 (setq cnt (1+ cnt))))))
1382 (result (make-symbol "result"))
1383 (result-tail (make-symbol "result-tail")))
1384 `(let* ,(let* ((bindings (cons nil nil))
1386 (nconc bindings (list (list result '(cons nil nil))))
1387 (nconc bindings (list (list result-tail result)))
1389 (nconc bindings (list (list (pop heads) (pop seqs)))))
1391 (while (and ,@heads)
1392 (setcdr ,result-tail (cons (funcall ,function
1393 ,@(mapcar (lambda (h) (list 'car h))
1396 (setq ,result-tail (cdr ,result-tail)
1397 ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1399 `(mapcar ,function ,seq1)))
1401 (if (fboundp 'merge)
1402 (defalias 'gnus-merge 'merge)
1403 ;; Adapted from cl-seq.el
1404 (defun gnus-merge (type list1 list2 pred)
1405 "Destructively merge lists LIST1 and LIST2 to produce a new list.
1406 Argument TYPE is for compatibility and ignored.
1407 Ordering of the elements is preserved according to PRED, a `less-than'
1408 predicate on the elements."
1410 (while (and list1 list2)
1411 (if (funcall pred (car list2) (car list1))
1412 (push (pop list2) res)
1413 (push (pop list1) res)))
1414 (nconc (nreverse res) list1 list2))))
1416 (provide 'gnus-util)
1418 ;;; gnus-util.el ends here