Revision: miles@gnu.org--gnu-2005/emacs--cvs-trunk--0--patch-492
[emacs.git] / lisp / gnus / gnus-util.el
blob363b9c2f4a030935ef6570e864a1c01b90226983
1 ;;; gnus-util.el --- utility functions for Gnus
2 ;; Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005
3 ;; Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news
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)
13 ;; any later version.
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., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
25 ;;; Commentary:
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
30 ;; Gnus first.
32 ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
33 ;; autoloads below...]
35 ;;; Code:
37 (require 'custom)
38 (eval-when-compile
39 (require 'cl)
40 ;; Fixme: this should be a gnus variable, not nnmail-.
41 (defvar nnmail-pathname-coding-system)
43 ;; Inappropriate references to other parts of Gnus.
44 (defvar gnus-emphasize-whitespace-regexp)
46 (require 'time-date)
47 (require 'netrc)
49 (eval-and-compile
50 (autoload 'message-fetch-field "message")
51 (autoload 'gnus-get-buffer-window "gnus-win")
52 (autoload 'rmail-insert-rmail-file-header "rmail")
53 (autoload 'rmail-count-new-messages "rmail")
54 (autoload 'rmail-show-message "rmail")
55 (autoload 'nnheader-narrow-to-headers "nnheader")
56 (autoload 'nnheader-replace-chars-in-string "nnheader"))
58 (eval-and-compile
59 (cond
60 ((fboundp 'replace-in-string)
61 (defalias 'gnus-replace-in-string 'replace-in-string))
62 ((fboundp 'replace-regexp-in-string)
63 (defun gnus-replace-in-string (string regexp newtext &optional literal)
64 "Replace all matches for REGEXP with NEWTEXT in STRING.
65 If LITERAL is non-nil, insert NEWTEXT literally. Return a new
66 string containing the replacements.
68 This is a compatibility function for different Emacsen."
69 (replace-regexp-in-string regexp newtext string nil literal)))
71 (defun gnus-replace-in-string (string regexp newtext &optional literal)
72 "Replace all matches for REGEXP with NEWTEXT in STRING.
73 If LITERAL is non-nil, insert NEWTEXT literally. Return a new
74 string containing the replacements.
76 This is a compatibility function for different Emacsen."
77 (let ((start 0) tail)
78 (while (string-match regexp string start)
79 (setq tail (- (length string) (match-end 0)))
80 (setq string (replace-match newtext nil literal string))
81 (setq start (- (length string) tail))))
82 string))))
84 ;;; bring in the netrc functions as aliases
85 (defalias 'gnus-netrc-get 'netrc-get)
86 (defalias 'gnus-netrc-machine 'netrc-machine)
87 (defalias 'gnus-parse-netrc 'netrc-parse)
89 (defun gnus-boundp (variable)
90 "Return non-nil if VARIABLE is bound and non-nil."
91 (and (boundp variable)
92 (symbol-value variable)))
94 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
95 "Pop to BUFFER, evaluate FORMS, and then return to the original window."
96 (let ((tempvar (make-symbol "GnusStartBufferWindow"))
97 (w (make-symbol "w"))
98 (buf (make-symbol "buf")))
99 `(let* ((,tempvar (selected-window))
100 (,buf ,buffer)
101 (,w (gnus-get-buffer-window ,buf 'visible)))
102 (unwind-protect
103 (progn
104 (if ,w
105 (progn
106 (select-window ,w)
107 (set-buffer (window-buffer ,w)))
108 (pop-to-buffer ,buf))
109 ,@forms)
110 (select-window ,tempvar)))))
112 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
113 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
115 (defmacro gnus-intern-safe (string hashtable)
116 "Set hash value. Arguments are STRING, VALUE, and HASHTABLE."
117 `(let ((symbol (intern ,string ,hashtable)))
118 (or (boundp symbol)
119 (set symbol nil))
120 symbol))
122 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>. A safe way
123 ;; to limit the length of a string. This function is necessary since
124 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
125 ;; Fixme: Why not `truncate-string-to-width'?
126 (defsubst gnus-limit-string (str width)
127 (if (> (length str) width)
128 (substring str 0 width)
129 str))
131 (defsubst gnus-goto-char (point)
132 (and point (goto-char point)))
134 (defmacro gnus-buffer-exists-p (buffer)
135 `(let ((buffer ,buffer))
136 (when buffer
137 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
138 buffer))))
140 (defalias 'gnus-point-at-bol
141 (if (fboundp 'point-at-bol)
142 'point-at-bol
143 'line-beginning-position))
145 (defalias 'gnus-point-at-eol
146 (if (fboundp 'point-at-eol)
147 'point-at-eol
148 'line-end-position))
150 ;; The LOCAL arg to `add-hook' is interpreted differently in Emacs and
151 ;; XEmacs. In Emacs we don't need to call `make-local-hook' first.
152 ;; It's harmless, though, so the main purpose of this alias is to shut
153 ;; up the byte compiler.
154 (defalias 'gnus-make-local-hook
155 (if (eq (get 'make-local-hook 'byte-compile)
156 'byte-compile-obsolete)
157 'ignore ; Emacs
158 'make-local-hook)) ; XEmacs
160 (defun gnus-delete-first (elt list)
161 "Delete by side effect the first occurrence of ELT as a member of LIST."
162 (if (equal (car list) elt)
163 (cdr list)
164 (let ((total list))
165 (while (and (cdr list)
166 (not (equal (cadr list) elt)))
167 (setq list (cdr list)))
168 (when (cdr list)
169 (setcdr list (cddr list)))
170 total)))
172 ;; Delete the current line (and the next N lines).
173 (defmacro gnus-delete-line (&optional n)
174 `(delete-region (gnus-point-at-bol)
175 (progn (forward-line ,(or n 1)) (point))))
177 (defun gnus-byte-code (func)
178 "Return a form that can be `eval'ed based on FUNC."
179 (let ((fval (indirect-function func)))
180 (if (byte-code-function-p fval)
181 (let ((flist (append fval nil)))
182 (setcar flist 'byte-code)
183 flist)
184 (cons 'progn (cddr fval)))))
186 (defun gnus-extract-address-components (from)
187 "Extract address components from a From header.
188 Given an RFC-822 address FROM, extract full name and canonical address.
189 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS). Much more simple
190 solution than `mail-extract-address-components', which works much better, but
191 is slower."
192 (let (name address)
193 ;; First find the address - the thing with the @ in it. This may
194 ;; not be accurate in mail addresses, but does the trick most of
195 ;; the time in news messages.
196 (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
197 (setq address (substring from (match-beginning 0) (match-end 0))))
198 ;; Then we check whether the "name <address>" format is used.
199 (and address
200 ;; Linear white space is not required.
201 (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
202 (and (setq name (substring from 0 (match-beginning 0)))
203 ;; Strip any quotes from the name.
204 (string-match "^\".*\"$" name)
205 (setq name (substring name 1 (1- (match-end 0))))))
206 ;; If not, then "address (name)" is used.
207 (or name
208 (and (string-match "(.+)" from)
209 (setq name (substring from (1+ (match-beginning 0))
210 (1- (match-end 0)))))
211 (and (string-match "()" from)
212 (setq name address))
213 ;; XOVER might not support folded From headers.
214 (and (string-match "(.*" from)
215 (setq name (substring from (1+ (match-beginning 0))
216 (match-end 0)))))
217 (list (if (string= name "") nil name) (or address from))))
220 (defun gnus-fetch-field (field)
221 "Return the value of the header FIELD of current article."
222 (save-excursion
223 (save-restriction
224 (let ((case-fold-search t)
225 (inhibit-point-motion-hooks t))
226 (nnheader-narrow-to-headers)
227 (message-fetch-field field)))))
229 (defun gnus-fetch-original-field (field)
230 "Fetch FIELD from the original version of the current article."
231 (with-current-buffer gnus-original-article-buffer
232 (gnus-fetch-field field)))
235 (defun gnus-goto-colon ()
236 (beginning-of-line)
237 (let ((eol (gnus-point-at-eol)))
238 (goto-char (or (text-property-any (point) eol 'gnus-position t)
239 (search-forward ":" eol t)
240 (point)))))
242 (defun gnus-decode-newsgroups (newsgroups group &optional method)
243 (let ((method (or method (gnus-find-method-for-group group))))
244 (mapconcat (lambda (group)
245 (gnus-group-name-decode group (gnus-group-name-charset
246 method group)))
247 (message-tokenize-header newsgroups)
248 ",")))
250 (defun gnus-remove-text-with-property (prop)
251 "Delete all text in the current buffer with text property PROP."
252 (save-excursion
253 (goto-char (point-min))
254 (while (not (eobp))
255 (while (get-text-property (point) prop)
256 (delete-char 1))
257 (goto-char (next-single-property-change (point) prop nil (point-max))))))
259 (defun gnus-newsgroup-directory-form (newsgroup)
260 "Make hierarchical directory name from NEWSGROUP name."
261 (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
262 (idx (string-match ":" newsgroup)))
263 (concat
264 (if idx (substring newsgroup 0 idx))
265 (if idx "/")
266 (nnheader-replace-chars-in-string
267 (if idx (substring newsgroup (1+ idx)) newsgroup)
268 ?. ?/))))
270 (defun gnus-newsgroup-savable-name (group)
271 ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
272 ;; with dots.
273 (nnheader-replace-chars-in-string group ?/ ?.))
275 (defun gnus-string> (s1 s2)
276 (not (or (string< s1 s2)
277 (string= s1 s2))))
279 ;;; Time functions.
281 (defun gnus-file-newer-than (file date)
282 (let ((fdate (nth 5 (file-attributes file))))
283 (or (> (car fdate) (car date))
284 (and (= (car fdate) (car date))
285 (> (nth 1 fdate) (nth 1 date))))))
287 ;;; Keymap macros.
289 (defmacro gnus-local-set-keys (&rest plist)
290 "Set the keys in PLIST in the current keymap."
291 `(gnus-define-keys-1 (current-local-map) ',plist))
293 (defmacro gnus-define-keys (keymap &rest plist)
294 "Define all keys in PLIST in KEYMAP."
295 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
297 (defmacro gnus-define-keys-safe (keymap &rest plist)
298 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
299 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
301 (put 'gnus-define-keys 'lisp-indent-function 1)
302 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
303 (put 'gnus-local-set-keys 'lisp-indent-function 1)
305 (defmacro gnus-define-keymap (keymap &rest plist)
306 "Define all keys in PLIST in KEYMAP."
307 `(gnus-define-keys-1 ,keymap (quote ,plist)))
309 (put 'gnus-define-keymap 'lisp-indent-function 1)
311 (defun gnus-define-keys-1 (keymap plist &optional safe)
312 (when (null keymap)
313 (error "Can't set keys in a null keymap"))
314 (cond ((symbolp keymap)
315 (setq keymap (symbol-value keymap)))
316 ((keymapp keymap))
317 ((listp keymap)
318 (set (car keymap) nil)
319 (define-prefix-command (car keymap))
320 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
321 (setq keymap (symbol-value (car keymap)))))
322 (let (key)
323 (while plist
324 (when (symbolp (setq key (pop plist)))
325 (setq key (symbol-value key)))
326 (if (or (not safe)
327 (eq (lookup-key keymap key) 'undefined))
328 (define-key keymap key (pop plist))
329 (pop plist)))))
331 (defun gnus-completing-read-with-default (default prompt &rest args)
332 ;; Like `completing-read', except that DEFAULT is the default argument.
333 (let* ((prompt (if default
334 (concat prompt " (default " default ") ")
335 (concat prompt " ")))
336 (answer (apply 'completing-read prompt args)))
337 (if (or (null answer) (zerop (length answer)))
338 default
339 answer)))
341 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
342 ;; the echo area.
343 (defun gnus-y-or-n-p (prompt)
344 (prog1
345 (y-or-n-p prompt)
346 (message "")))
348 (defun gnus-yes-or-no-p (prompt)
349 (prog1
350 (yes-or-no-p prompt)
351 (message "")))
353 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
354 ;; age-depending date representations. (e.g. just the time if it's
355 ;; from today, the day of the week if it's within the last 7 days and
356 ;; the full date if it's older)
358 (defun gnus-seconds-today ()
359 "Return the number of seconds passed today."
360 (let ((now (decode-time (current-time))))
361 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
363 (defun gnus-seconds-month ()
364 "Return the number of seconds passed this month."
365 (let ((now (decode-time (current-time))))
366 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
367 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
369 (defun gnus-seconds-year ()
370 "Return the number of seconds passed this year."
371 (let ((now (decode-time (current-time)))
372 (days (format-time-string "%j" (current-time))))
373 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
374 (* (- (string-to-number days) 1) 3600 24))))
376 (defvar gnus-user-date-format-alist
377 '(((gnus-seconds-today) . "%k:%M")
378 (604800 . "%a %k:%M") ;;that's one week
379 ((gnus-seconds-month) . "%a %d")
380 ((gnus-seconds-year) . "%b %d")
381 (t . "%b %d '%y")) ;;this one is used when no
382 ;;other does match
383 "Specifies date format depending on age of article.
384 This is an alist of items (AGE . FORMAT). AGE can be a number (of
385 seconds) or a Lisp expression evaluating to a number. When the age of
386 the article is less than this number, then use `format-time-string'
387 with the corresponding FORMAT for displaying the date of the article.
388 If AGE is not a number or a Lisp expression evaluating to a
389 non-number, then the corresponding FORMAT is used as a default value.
391 Note that the list is processed from the beginning, so it should be
392 sorted by ascending AGE. Also note that items following the first
393 non-number AGE will be ignored.
395 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
396 and `gnus-seconds-year' in the AGE spec. They return the number of
397 seconds passed since the start of today, of this month, of this year,
398 respectively.")
400 (defun gnus-user-date (messy-date)
401 "Format the messy-date according to gnus-user-date-format-alist.
402 Returns \" ? \" if there's bad input or if an other error occurs.
403 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
404 (condition-case ()
405 (let* ((messy-date (time-to-seconds (safe-date-to-time messy-date)))
406 (now (time-to-seconds (current-time)))
407 ;;If we don't find something suitable we'll use this one
408 (my-format "%b %d '%y"))
409 (let* ((difference (- now messy-date))
410 (templist gnus-user-date-format-alist)
411 (top (eval (caar templist))))
412 (while (if (numberp top) (< top difference) (not top))
413 (progn
414 (setq templist (cdr templist))
415 (setq top (eval (caar templist)))))
416 (if (stringp (cdr (car templist)))
417 (setq my-format (cdr (car templist)))))
418 (format-time-string (eval my-format) (seconds-to-time messy-date)))
419 (error " ? ")))
421 (defun gnus-dd-mmm (messy-date)
422 "Return a string like DD-MMM from a big messy string."
423 (condition-case ()
424 (format-time-string "%d-%b" (safe-date-to-time messy-date))
425 (error " - ")))
427 (defmacro gnus-date-get-time (date)
428 "Convert DATE string to Emacs time.
429 Cache the result as a text property stored in DATE."
430 ;; Either return the cached value...
431 `(let ((d ,date))
432 (if (equal "" d)
433 '(0 0)
434 (or (get-text-property 0 'gnus-time d)
435 ;; or compute the value...
436 (let ((time (safe-date-to-time d)))
437 ;; and store it back in the string.
438 (put-text-property 0 1 'gnus-time time d)
439 time)))))
441 (defsubst gnus-time-iso8601 (time)
442 "Return a string of TIME in YYYYMMDDTHHMMSS format."
443 (format-time-string "%Y%m%dT%H%M%S" time))
445 (defun gnus-date-iso8601 (date)
446 "Convert the DATE to YYYYMMDDTHHMMSS."
447 (condition-case ()
448 (gnus-time-iso8601 (gnus-date-get-time date))
449 (error "")))
451 (defun gnus-mode-string-quote (string)
452 "Quote all \"%\"'s in STRING."
453 (gnus-replace-in-string string "%" "%%"))
455 ;; Make a hash table (default and minimum size is 256).
456 ;; Optional argument HASHSIZE specifies the table size.
457 (defun gnus-make-hashtable (&optional hashsize)
458 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
460 ;; Make a number that is suitable for hashing; bigger than MIN and
461 ;; equal to some 2^x. Many machines (such as sparcs) do not have a
462 ;; hardware modulo operation, so they implement it in software. On
463 ;; many sparcs over 50% of the time to intern is spent in the modulo.
464 ;; Yes, it's slower than actually computing the hash from the string!
465 ;; So we use powers of 2 so people can optimize the modulo to a mask.
466 (defun gnus-create-hash-size (min)
467 (let ((i 1))
468 (while (< i min)
469 (setq i (* 2 i)))
472 (defcustom gnus-verbose 7
473 "*Integer that says how verbose Gnus should be.
474 The higher the number, the more messages Gnus will flash to say what
475 it's doing. At zero, Gnus will be totally mute; at five, Gnus will
476 display most important messages; and at ten, Gnus will keep on
477 jabbering all the time."
478 :group 'gnus-start
479 :type 'integer)
481 (defun gnus-message (level &rest args)
482 "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
484 Guideline for numbers:
485 1 - error messages, 3 - non-serious error messages, 5 - messages for things
486 that take a long time, 7 - not very important messages on stuff, 9 - messages
487 inside loops."
488 (if (<= level gnus-verbose)
489 (apply 'message args)
490 ;; We have to do this format thingy here even if the result isn't
491 ;; shown - the return value has to be the same as the return value
492 ;; from `message'.
493 (apply 'format args)))
495 (defun gnus-error (level &rest args)
496 "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
497 (when (<= (floor level) gnus-verbose)
498 (apply 'message args)
499 (ding)
500 (let (duration)
501 (when (and (floatp level)
502 (not (zerop (setq duration (* 10 (- level (floor level)))))))
503 (sit-for duration))))
504 nil)
506 (defun gnus-split-references (references)
507 "Return a list of Message-IDs in REFERENCES."
508 (let ((beg 0)
509 ids)
510 (while (string-match "<[^<]+[^< \t]" references beg)
511 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
512 ids))
513 (nreverse ids)))
515 (defsubst gnus-parent-id (references &optional n)
516 "Return the last Message-ID in REFERENCES.
517 If N, return the Nth ancestor instead."
518 (when (and references
519 (not (zerop (length references))))
520 (if n
521 (let ((ids (inline (gnus-split-references references))))
522 (while (nthcdr n ids)
523 (setq ids (cdr ids)))
524 (car ids))
525 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
526 (match-string 1 references)))))
528 (defun gnus-buffer-live-p (buffer)
529 "Say whether BUFFER is alive or not."
530 (and buffer
531 (get-buffer buffer)
532 (buffer-name (get-buffer buffer))))
534 (defun gnus-horizontal-recenter ()
535 "Recenter the current buffer horizontally."
536 (if (< (current-column) (/ (window-width) 2))
537 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
538 (let* ((orig (point))
539 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
540 (max 0))
541 (when end
542 ;; Find the longest line currently displayed in the window.
543 (goto-char (window-start))
544 (while (and (not (eobp))
545 (< (point) end))
546 (end-of-line)
547 (setq max (max max (current-column)))
548 (forward-line 1))
549 (goto-char orig)
550 ;; Scroll horizontally to center (sort of) the point.
551 (if (> max (window-width))
552 (set-window-hscroll
553 (gnus-get-buffer-window (current-buffer) t)
554 (min (- (current-column) (/ (window-width) 3))
555 (+ 2 (- max (window-width)))))
556 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
557 max))))
559 (defun gnus-read-event-char (&optional prompt)
560 "Get the next event."
561 (let ((event (read-event prompt)))
562 ;; should be gnus-characterp, but this can't be called in XEmacs anyway
563 (cons (and (numberp event) event) event)))
565 (defun gnus-sortable-date (date)
566 "Make string suitable for sorting from DATE."
567 (gnus-time-iso8601 (date-to-time date)))
569 (defun gnus-copy-file (file &optional to)
570 "Copy FILE to TO."
571 (interactive
572 (list (read-file-name "Copy file: " default-directory)
573 (read-file-name "Copy file to: " default-directory)))
574 (unless to
575 (setq to (read-file-name "Copy file to: " default-directory)))
576 (when (file-directory-p to)
577 (setq to (concat (file-name-as-directory to)
578 (file-name-nondirectory file))))
579 (copy-file file to))
581 (defvar gnus-work-buffer " *gnus work*")
583 (defun gnus-set-work-buffer ()
584 "Put point in the empty Gnus work buffer."
585 (if (get-buffer gnus-work-buffer)
586 (progn
587 (set-buffer gnus-work-buffer)
588 (erase-buffer))
589 (set-buffer (gnus-get-buffer-create gnus-work-buffer))
590 (kill-all-local-variables)
591 (mm-enable-multibyte)))
593 (defmacro gnus-group-real-name (group)
594 "Find the real name of a foreign newsgroup."
595 `(let ((gname ,group))
596 (if (string-match "^[^:]+:" gname)
597 (substring gname (match-end 0))
598 gname)))
600 (defun gnus-make-sort-function (funs)
601 "Return a composite sort condition based on the functions in FUNS."
602 (cond
603 ;; Just a simple function.
604 ((functionp funs) funs)
605 ;; No functions at all.
606 ((null funs) funs)
607 ;; A list of functions.
608 ((or (cdr funs)
609 (listp (car funs)))
610 (gnus-byte-compile
611 `(lambda (t1 t2)
612 ,(gnus-make-sort-function-1 (reverse funs)))))
613 ;; A list containing just one function.
615 (car funs))))
617 (defun gnus-make-sort-function-1 (funs)
618 "Return a composite sort condition based on the functions in FUNS."
619 (let ((function (car funs))
620 (first 't1)
621 (last 't2))
622 (when (consp function)
623 (cond
624 ;; Reversed spec.
625 ((eq (car function) 'not)
626 (setq function (cadr function)
627 first 't2
628 last 't1))
629 ((functionp function)
630 ;; Do nothing.
633 (error "Invalid sort spec: %s" function))))
634 (if (cdr funs)
635 `(or (,function ,first ,last)
636 (and (not (,function ,last ,first))
637 ,(gnus-make-sort-function-1 (cdr funs))))
638 `(,function ,first ,last))))
640 (defun gnus-turn-off-edit-menu (type)
641 "Turn off edit menu in `gnus-TYPE-mode-map'."
642 (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
643 [menu-bar edit] 'undefined))
645 (defmacro gnus-bind-print-variables (&rest forms)
646 "Bind print-* variables and evaluate FORMS.
647 This macro is used with `prin1', `pp', etc. in order to ensure printed
648 Lisp objects are loadable. Bind `print-quoted' and `print-readably'
649 to t, and `print-escape-multibyte', `print-escape-newlines',
650 `print-escape-nonascii', `print-length', `print-level' and
651 `print-string-length' to nil."
652 `(let ((print-quoted t)
653 (print-readably t)
654 ;;print-circle
655 ;;print-continuous-numbering
656 print-escape-multibyte
657 print-escape-newlines
658 print-escape-nonascii
659 ;;print-gensym
660 print-length
661 print-level
662 print-string-length)
663 ,@forms))
665 (defun gnus-prin1 (form)
666 "Use `prin1' on FORM in the current buffer.
667 Bind `print-quoted' and `print-readably' to t, and `print-length' and
668 `print-level' to nil. See also `gnus-bind-print-variables'."
669 (gnus-bind-print-variables (prin1 form (current-buffer))))
671 (defun gnus-prin1-to-string (form)
672 "The same as `prin1'.
673 Bind `print-quoted' and `print-readably' to t, and `print-length' and
674 `print-level' to nil. See also `gnus-bind-print-variables'."
675 (gnus-bind-print-variables (prin1-to-string form)))
677 (defun gnus-pp (form)
678 "Use `pp' on FORM in the current buffer.
679 Bind `print-quoted' and `print-readably' to t, and `print-length' and
680 `print-level' to nil. See also `gnus-bind-print-variables'."
681 (gnus-bind-print-variables (pp form (current-buffer))))
683 (defun gnus-pp-to-string (form)
684 "The same as `pp-to-string'.
685 Bind `print-quoted' and `print-readably' to t, and `print-length' and
686 `print-level' to nil. See also `gnus-bind-print-variables'."
687 (gnus-bind-print-variables (pp-to-string form)))
689 (defun gnus-make-directory (directory)
690 "Make DIRECTORY (and all its parents) if it doesn't exist."
691 (require 'nnmail)
692 (let ((file-name-coding-system nnmail-pathname-coding-system))
693 (when (and directory
694 (not (file-exists-p directory)))
695 (make-directory directory t)))
698 (defun gnus-write-buffer (file)
699 "Write the current buffer's contents to FILE."
700 ;; Make sure the directory exists.
701 (gnus-make-directory (file-name-directory file))
702 (let ((file-name-coding-system nnmail-pathname-coding-system))
703 ;; Write the buffer.
704 (write-region (point-min) (point-max) file nil 'quietly)))
706 (defun gnus-delete-file (file)
707 "Delete FILE if it exists."
708 (when (file-exists-p file)
709 (delete-file file)))
711 (defun gnus-delete-directory (directory)
712 "Delete files in DIRECTORY. Subdirectories remain.
713 If there's no subdirectory, delete DIRECTORY as well."
714 (when (file-directory-p directory)
715 (let ((files (directory-files
716 directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
717 file dir)
718 (while files
719 (setq file (pop files))
720 (if (eq t (car (file-attributes file)))
721 ;; `file' is a subdirectory.
722 (setq dir t)
723 ;; `file' is a file or a symlink.
724 (delete-file file)))
725 (unless dir
726 (delete-directory directory)))))
728 (defun gnus-strip-whitespace (string)
729 "Return STRING stripped of all whitespace."
730 (while (string-match "[\r\n\t ]+" string)
731 (setq string (replace-match "" t t string)))
732 string)
734 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
735 "The same as `put-text-property', but don't put this prop on any newlines in the region."
736 (save-match-data
737 (save-excursion
738 (save-restriction
739 (goto-char beg)
740 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
741 (gnus-put-text-property beg (match-beginning 0) prop val)
742 (setq beg (point)))
743 (gnus-put-text-property beg (point) prop val)))))
745 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
746 "The same as `put-text-property', but don't put this prop on any newlines in the region."
747 (save-match-data
748 (save-excursion
749 (save-restriction
750 (goto-char beg)
751 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
752 (gnus-overlay-put
753 (gnus-make-overlay beg (match-beginning 0))
754 prop val)
755 (setq beg (point)))
756 (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
758 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
759 prop val)
760 "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
761 (let ((b beg))
762 (while (/= b end)
763 (when (get-text-property b 'gnus-face)
764 (setq b (next-single-property-change b 'gnus-face nil end)))
765 (when (/= b end)
766 (inline
767 (gnus-put-text-property
768 b (setq b (next-single-property-change b 'gnus-face nil end))
769 prop val))))))
771 (defmacro gnus-faces-at (position)
772 "Return a list of faces at POSITION."
773 (if (featurep 'xemacs)
774 `(let ((pos ,position))
775 (mapcar-extents 'extent-face
776 nil (current-buffer) pos pos nil 'face))
777 `(let ((pos ,position))
778 (delq nil (cons (get-text-property pos 'face)
779 (mapcar
780 (lambda (overlay)
781 (overlay-get overlay 'face))
782 (overlays-at pos)))))))
784 ;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
785 ;;; The primary idea here is to try to protect internal datastructures
786 ;;; from becoming corrupted when the user hits C-g, or if a hook or
787 ;;; similar blows up. Often in Gnus multiple tables/lists need to be
788 ;;; updated at the same time, or information can be lost.
790 (defvar gnus-atomic-be-safe t
791 "If t, certain operations will be protected from interruption by C-g.")
793 (defmacro gnus-atomic-progn (&rest forms)
794 "Evaluate FORMS atomically, which means to protect the evaluation
795 from being interrupted by the user. An error from the forms themselves
796 will return without finishing the operation. Since interrupts from
797 the user are disabled, it is recommended that only the most minimal
798 operations are performed by FORMS. If you wish to assign many
799 complicated values atomically, compute the results into temporary
800 variables and then do only the assignment atomically."
801 `(let ((inhibit-quit gnus-atomic-be-safe))
802 ,@forms))
804 (put 'gnus-atomic-progn 'lisp-indent-function 0)
806 (defmacro gnus-atomic-progn-assign (protect &rest forms)
807 "Evaluate FORMS, but insure that the variables listed in PROTECT
808 are not changed if anything in FORMS signals an error or otherwise
809 non-locally exits. The variables listed in PROTECT are updated atomically.
810 It is safe to use gnus-atomic-progn-assign with long computations.
812 Note that if any of the symbols in PROTECT were unbound, they will be
813 set to nil on a successful assignment. In case of an error or other
814 non-local exit, it will still be unbound."
815 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
816 (concat (symbol-name x)
817 "-tmp"))
819 protect))
820 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
821 temp-sym-map))
822 (temp-sym-let (mapcar (lambda (x) (list (car x)
823 `(and (boundp ',(cadr x))
824 ,(cadr x))))
825 temp-sym-map))
826 (sym-temp-let sym-temp-map)
827 (temp-sym-assign (apply 'append temp-sym-map))
828 (sym-temp-assign (apply 'append sym-temp-map))
829 (result (make-symbol "result-tmp")))
830 `(let (,@temp-sym-let
831 ,result)
832 (let ,sym-temp-let
833 (setq ,result (progn ,@forms))
834 (setq ,@temp-sym-assign))
835 (let ((inhibit-quit gnus-atomic-be-safe))
836 (setq ,@sym-temp-assign))
837 ,result)))
839 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
840 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
842 (defmacro gnus-atomic-setq (&rest pairs)
843 "Similar to setq, except that the real symbols are only assigned when
844 there are no errors. And when the real symbols are assigned, they are
845 done so atomically. If other variables might be changed via side-effect,
846 see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
847 with potentially long computations."
848 (let ((tpairs pairs)
849 syms)
850 (while tpairs
851 (push (car tpairs) syms)
852 (setq tpairs (cddr tpairs)))
853 `(gnus-atomic-progn-assign ,syms
854 (setq ,@pairs))))
856 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
859 ;;; Functions for saving to babyl/mail files.
861 (eval-when-compile
862 (condition-case nil
863 (progn
864 (require 'rmail)
865 (autoload 'rmail-update-summary "rmailsum"))
866 (error
867 (define-compiler-macro rmail-select-summary (&rest body)
868 ;; Rmail of the XEmacs version is supplied by the package, and
869 ;; requires tm and apel packages. However, there may be those
870 ;; who haven't installed those packages. This macro helps such
871 ;; people even if they install those packages later.
872 `(eval '(rmail-select-summary ,@body)))
873 ;; If there's rmail but there's no tm (or there's apel of the
874 ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
875 ;; version fails halfway, however it provides the rmail-select-summary
876 ;; macro which uses the following functions:
877 (autoload 'rmail-summary-displayed "rmail")
878 (autoload 'rmail-maybe-display-summary "rmail")))
879 (defvar rmail-default-rmail-file)
880 (defvar mm-text-coding-system))
882 (defun gnus-output-to-rmail (filename &optional ask)
883 "Append the current article to an Rmail file named FILENAME."
884 (require 'rmail)
885 (require 'mm-util)
886 ;; Most of these codes are borrowed from rmailout.el.
887 (setq filename (expand-file-name filename))
888 (setq rmail-default-rmail-file filename)
889 (let ((artbuf (current-buffer))
890 (tmpbuf (get-buffer-create " *Gnus-output*")))
891 (save-excursion
892 (or (get-file-buffer filename)
893 (file-exists-p filename)
894 (if (or (not ask)
895 (gnus-yes-or-no-p
896 (concat "\"" filename "\" does not exist, create it? ")))
897 (let ((file-buffer (create-file-buffer filename)))
898 (save-excursion
899 (set-buffer file-buffer)
900 (rmail-insert-rmail-file-header)
901 (let ((require-final-newline nil)
902 (coding-system-for-write mm-text-coding-system))
903 (gnus-write-buffer filename)))
904 (kill-buffer file-buffer))
905 (error "Output file does not exist")))
906 (set-buffer tmpbuf)
907 (erase-buffer)
908 (insert-buffer-substring artbuf)
909 (gnus-convert-article-to-rmail)
910 ;; Decide whether to append to a file or to an Emacs buffer.
911 (let ((outbuf (get-file-buffer filename)))
912 (if (not outbuf)
913 (let ((file-name-coding-system nnmail-pathname-coding-system))
914 (mm-append-to-file (point-min) (point-max) filename))
915 ;; File has been visited, in buffer OUTBUF.
916 (set-buffer outbuf)
917 (let ((buffer-read-only nil)
918 (msg (and (boundp 'rmail-current-message)
919 (symbol-value 'rmail-current-message))))
920 ;; If MSG is non-nil, buffer is in RMAIL mode.
921 (when msg
922 (widen)
923 (narrow-to-region (point-max) (point-max)))
924 (insert-buffer-substring tmpbuf)
925 (when msg
926 (goto-char (point-min))
927 (widen)
928 (search-backward "\n\^_")
929 (narrow-to-region (point) (point-max))
930 (rmail-count-new-messages t)
931 (when (rmail-summary-exists)
932 (rmail-select-summary
933 (rmail-update-summary)))
934 (rmail-count-new-messages t)
935 (rmail-show-message msg))
936 (save-buffer)))))
937 (kill-buffer tmpbuf)))
939 (defun gnus-output-to-mail (filename &optional ask)
940 "Append the current article to a mail file named FILENAME."
941 (setq filename (expand-file-name filename))
942 (let ((artbuf (current-buffer))
943 (tmpbuf (get-buffer-create " *Gnus-output*")))
944 (save-excursion
945 ;; Create the file, if it doesn't exist.
946 (when (and (not (get-file-buffer filename))
947 (not (file-exists-p filename)))
948 (if (or (not ask)
949 (gnus-y-or-n-p
950 (concat "\"" filename "\" does not exist, create it? ")))
951 (let ((file-buffer (create-file-buffer filename)))
952 (save-excursion
953 (set-buffer file-buffer)
954 (let ((require-final-newline nil)
955 (coding-system-for-write mm-text-coding-system))
956 (gnus-write-buffer filename)))
957 (kill-buffer file-buffer))
958 (error "Output file does not exist")))
959 (set-buffer tmpbuf)
960 (erase-buffer)
961 (insert-buffer-substring artbuf)
962 (goto-char (point-min))
963 (if (looking-at "From ")
964 (forward-line 1)
965 (insert "From nobody " (current-time-string) "\n"))
966 (let (case-fold-search)
967 (while (re-search-forward "^From " nil t)
968 (beginning-of-line)
969 (insert ">")))
970 ;; Decide whether to append to a file or to an Emacs buffer.
971 (let ((outbuf (get-file-buffer filename)))
972 (if (not outbuf)
973 (let ((buffer-read-only nil))
974 (save-excursion
975 (goto-char (point-max))
976 (forward-char -2)
977 (unless (looking-at "\n\n")
978 (goto-char (point-max))
979 (unless (bolp)
980 (insert "\n"))
981 (insert "\n"))
982 (goto-char (point-max))
983 (let ((file-name-coding-system nnmail-pathname-coding-system))
984 (mm-append-to-file (point-min) (point-max) filename))))
985 ;; File has been visited, in buffer OUTBUF.
986 (set-buffer outbuf)
987 (let ((buffer-read-only nil))
988 (goto-char (point-max))
989 (unless (eobp)
990 (insert "\n"))
991 (insert "\n")
992 (insert-buffer-substring tmpbuf)))))
993 (kill-buffer tmpbuf)))
995 (defun gnus-convert-article-to-rmail ()
996 "Convert article in current buffer to Rmail message format."
997 (let ((buffer-read-only nil))
998 ;; Convert article directly into Babyl format.
999 (goto-char (point-min))
1000 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1001 (while (search-forward "\n\^_" nil t) ;single char
1002 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
1003 (goto-char (point-max))
1004 (insert "\^_")))
1006 (defun gnus-map-function (funs arg)
1007 "Apply the result of the first function in FUNS to the second, and so on.
1008 ARG is passed to the first function."
1009 (while funs
1010 (setq arg (funcall (pop funs) arg)))
1011 arg)
1013 (defun gnus-run-hooks (&rest funcs)
1014 "Does the same as `run-hooks', but saves the current buffer."
1015 (save-current-buffer
1016 (apply 'run-hooks funcs)))
1018 (defun gnus-run-mode-hooks (&rest funcs)
1019 "Run `run-mode-hooks' if it is available, otherwise `run-hooks'.
1020 This function saves the current buffer."
1021 (if (fboundp 'run-mode-hooks)
1022 (save-current-buffer (apply 'run-mode-hooks funcs))
1023 (save-current-buffer (apply 'run-hooks funcs))))
1025 ;;; Various
1027 (defvar gnus-group-buffer) ; Compiler directive
1028 (defun gnus-alive-p ()
1029 "Say whether Gnus is running or not."
1030 (and (boundp 'gnus-group-buffer)
1031 (get-buffer gnus-group-buffer)
1032 (save-excursion
1033 (set-buffer gnus-group-buffer)
1034 (eq major-mode 'gnus-group-mode))))
1036 (defun gnus-remove-duplicates (list)
1037 (let (new)
1038 (while list
1039 (or (member (car list) new)
1040 (setq new (cons (car list) new)))
1041 (setq list (cdr list)))
1042 (nreverse new)))
1044 (defun gnus-remove-if (predicate list)
1045 "Return a copy of LIST with all items satisfying PREDICATE removed."
1046 (let (out)
1047 (while list
1048 (unless (funcall predicate (car list))
1049 (push (car list) out))
1050 (setq list (cdr list)))
1051 (nreverse out)))
1053 (if (fboundp 'assq-delete-all)
1054 (defalias 'gnus-delete-alist 'assq-delete-all)
1055 (defun gnus-delete-alist (key alist)
1056 "Delete from ALIST all elements whose car is KEY.
1057 Return the modified alist."
1058 (let (entry)
1059 (while (setq entry (assq key alist))
1060 (setq alist (delq entry alist)))
1061 alist)))
1063 (defmacro gnus-pull (key alist &optional assoc-p)
1064 "Modify ALIST to be without KEY."
1065 (unless (symbolp alist)
1066 (error "Not a symbol: %s" alist))
1067 (let ((fun (if assoc-p 'assoc 'assq)))
1068 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1070 (defun gnus-globalify-regexp (re)
1071 "Return a regexp that matches a whole line, iff RE matches a part of it."
1072 (concat (unless (string-match "^\\^" re) "^.*")
1074 (unless (string-match "\\$$" re) ".*$")))
1076 (defun gnus-set-window-start (&optional point)
1077 "Set the window start to POINT, or (point) if nil."
1078 (let ((win (gnus-get-buffer-window (current-buffer) t)))
1079 (when win
1080 (set-window-start win (or point (point))))))
1082 (defun gnus-annotation-in-region-p (b e)
1083 (if (= b e)
1084 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1085 (text-property-any b e 'gnus-undeletable t)))
1087 (defun gnus-or (&rest elems)
1088 "Return non-nil if any of the elements are non-nil."
1089 (catch 'found
1090 (while elems
1091 (when (pop elems)
1092 (throw 'found t)))))
1094 (defun gnus-and (&rest elems)
1095 "Return non-nil if all of the elements are non-nil."
1096 (catch 'found
1097 (while elems
1098 (unless (pop elems)
1099 (throw 'found nil)))
1102 (defun gnus-write-active-file (file hashtb &optional full-names)
1103 (let ((coding-system-for-write nnmail-active-file-coding-system))
1104 (with-temp-file file
1105 (mapatoms
1106 (lambda (sym)
1107 (when (and sym
1108 (boundp sym)
1109 (symbol-value sym))
1110 (insert (format "%S %d %d y\n"
1111 (if full-names
1113 (intern (gnus-group-real-name (symbol-name sym))))
1114 (or (cdr (symbol-value sym))
1115 (car (symbol-value sym)))
1116 (car (symbol-value sym))))))
1117 hashtb)
1118 (goto-char (point-max))
1119 (while (search-backward "\\." nil t)
1120 (delete-char 1)))))
1122 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1123 (defmacro gnus-with-output-to-file (file &rest body)
1124 (let ((buffer (make-symbol "output-buffer"))
1125 (size (make-symbol "output-buffer-size"))
1126 (leng (make-symbol "output-buffer-length"))
1127 (append (make-symbol "output-buffer-append")))
1128 `(let* ((,size 131072)
1129 (,buffer (make-string ,size 0))
1130 (,leng 0)
1131 (,append nil)
1132 (standard-output
1133 (lambda (c)
1134 (aset ,buffer ,leng c)
1136 (if (= ,size (setq ,leng (1+ ,leng)))
1137 (progn (write-region ,buffer nil ,file ,append 'no-msg)
1138 (setq ,leng 0
1139 ,append t))))))
1140 ,@body
1141 (when (> ,leng 0)
1142 (let ((coding-system-for-write 'no-conversion))
1143 (write-region (substring ,buffer 0 ,leng) nil ,file
1144 ,append 'no-msg))))))
1146 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1147 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1149 (if (fboundp 'union)
1150 (defalias 'gnus-union 'union)
1151 (defun gnus-union (l1 l2)
1152 "Set union of lists L1 and L2."
1153 (cond ((null l1) l2)
1154 ((null l2) l1)
1155 ((equal l1 l2) l1)
1157 (or (>= (length l1) (length l2))
1158 (setq l1 (prog1 l2 (setq l2 l1))))
1159 (while l2
1160 (or (member (car l2) l1)
1161 (push (car l2) l1))
1162 (pop l2))
1163 l1))))
1165 (defun gnus-add-text-properties-when
1166 (property value start end properties &optional object)
1167 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1168 (let (point)
1169 (while (and start
1170 (< start end) ;; XEmacs will loop for every when start=end.
1171 (setq point (text-property-not-all start end property value)))
1172 (gnus-add-text-properties start point properties object)
1173 (setq start (text-property-any point end property value)))
1174 (if start
1175 (gnus-add-text-properties start end properties object))))
1177 (defun gnus-remove-text-properties-when
1178 (property value start end properties &optional object)
1179 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1180 (let (point)
1181 (while (and start
1182 (< start end)
1183 (setq point (text-property-not-all start end property value)))
1184 (remove-text-properties start point properties object)
1185 (setq start (text-property-any point end property value)))
1186 (if start
1187 (remove-text-properties start end properties object))
1190 ;; This might use `compare-strings' to reduce consing in the
1191 ;; case-insensitive case, but it has to cope with null args.
1192 ;; (`string-equal' uses symbol print names.)
1193 (defun gnus-string-equal (x y)
1194 "Like `string-equal', except it compares case-insensitively."
1195 (and (= (length x) (length y))
1196 (or (string-equal x y)
1197 (string-equal (downcase x) (downcase y)))))
1199 (defcustom gnus-use-byte-compile t
1200 "If non-nil, byte-compile crucial run-time code.
1201 Setting it to nil has no effect after the first time `gnus-byte-compile'
1202 is run."
1203 :type 'boolean
1204 :version "22.1"
1205 :group 'gnus-various)
1207 (defun gnus-byte-compile (form)
1208 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1209 (if gnus-use-byte-compile
1210 (progn
1211 (condition-case nil
1212 ;; Work around a bug in XEmacs 21.4
1213 (require 'byte-optimize)
1214 (error))
1215 (require 'bytecomp)
1216 (defalias 'gnus-byte-compile
1217 (lambda (form)
1218 (let ((byte-compile-warnings '(unresolved callargs redefine)))
1219 (byte-compile form))))
1220 (gnus-byte-compile form))
1221 form))
1223 (defun gnus-remassoc (key alist)
1224 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1225 The modified LIST is returned. If the first member
1226 of LIST has a car that is `equal' to KEY, there is no way to remove it
1227 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1228 sure of changing the value of `foo'."
1229 (when alist
1230 (if (equal key (caar alist))
1231 (cdr alist)
1232 (setcdr alist (gnus-remassoc key (cdr alist)))
1233 alist)))
1235 (defun gnus-update-alist-soft (key value alist)
1236 (if value
1237 (cons (cons key value) (gnus-remassoc key alist))
1238 (gnus-remassoc key alist)))
1240 (defun gnus-create-info-command (node)
1241 "Create a command that will go to info NODE."
1242 `(lambda ()
1243 (interactive)
1244 ,(concat "Enter the info system at node " node)
1245 (Info-goto-node ,node)
1246 (setq gnus-info-buffer (current-buffer))
1247 (gnus-configure-windows 'info)))
1249 (defun gnus-not-ignore (&rest args)
1252 (defvar gnus-directory-sep-char-regexp "/"
1253 "The regexp of directory separator character.
1254 If you find some problem with the directory separator character, try
1255 \"[/\\\\\]\" for some systems.")
1257 (defun gnus-url-unhex (x)
1258 (if (> x ?9)
1259 (if (>= x ?a)
1260 (+ 10 (- x ?a))
1261 (+ 10 (- x ?A)))
1262 (- x ?0)))
1264 ;; Fixme: Do it like QP.
1265 (defun gnus-url-unhex-string (str &optional allow-newlines)
1266 "Remove %XX, embedded spaces, etc in a url.
1267 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1268 decoding of carriage returns and line feeds in the string, which is normally
1269 forbidden in URL encoding."
1270 (let ((tmp "")
1271 (case-fold-search t))
1272 (while (string-match "%[0-9a-f][0-9a-f]" str)
1273 (let* ((start (match-beginning 0))
1274 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1275 (code (+ (* 16 ch1)
1276 (gnus-url-unhex (elt str (+ start 2))))))
1277 (setq tmp (concat
1278 tmp (substring str 0 start)
1279 (cond
1280 (allow-newlines
1281 (char-to-string code))
1282 ((or (= code ?\n) (= code ?\r))
1283 " ")
1284 (t (char-to-string code))))
1285 str (substring str (match-end 0)))))
1286 (setq tmp (concat tmp str))
1287 tmp))
1289 (defun gnus-make-predicate (spec)
1290 "Transform SPEC into a function that can be called.
1291 SPEC is a predicate specifier that contains stuff like `or', `and',
1292 `not', lists and functions. The functions all take one parameter."
1293 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1295 (defun gnus-make-predicate-1 (spec)
1296 (cond
1297 ((symbolp spec)
1298 `(,spec elem))
1299 ((listp spec)
1300 (if (memq (car spec) '(or and not))
1301 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1302 (error "Invalid predicate specifier: %s" spec)))))
1304 (defun gnus-local-map-property (map)
1305 "Return a list suitable for a text property list specifying keymap MAP."
1306 (cond
1307 ((featurep 'xemacs)
1308 (list 'keymap map))
1309 ((>= emacs-major-version 21)
1310 (list 'keymap map))
1312 (list 'local-map map))))
1314 (defmacro gnus-completing-read-maybe-default (prompt table &optional predicate
1315 require-match initial-contents
1316 history default)
1317 "Like `completing-read', allowing for non-existent 7th arg in older XEmacsen."
1318 `(completing-read ,prompt ,table ,predicate ,require-match
1319 ,initial-contents ,history
1320 ,@(if (and (featurep 'xemacs) (< emacs-minor-version 2))
1322 (list default))))
1324 (defun gnus-completing-read (prompt table &optional predicate require-match
1325 history)
1326 (when (and history
1327 (not (boundp history)))
1328 (set history nil))
1329 (gnus-completing-read-maybe-default
1330 (if (symbol-value history)
1331 (concat prompt " (" (car (symbol-value history)) "): ")
1332 (concat prompt ": "))
1333 table
1334 predicate
1335 require-match
1337 history
1338 (car (symbol-value history))))
1340 (defun gnus-graphic-display-p ()
1341 (or (and (fboundp 'display-graphic-p)
1342 (display-graphic-p))
1343 ;;;!!!This is bogus. Fixme!
1344 (and (featurep 'xemacs)
1345 t)))
1347 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1348 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1350 (defmacro gnus-parse-without-error (&rest body)
1351 "Allow continuing onto the next line even if an error occurs."
1352 `(while (not (eobp))
1353 (condition-case ()
1354 (progn
1355 ,@body
1356 (goto-char (point-max)))
1357 (error
1358 (gnus-error 4 "Invalid data on line %d"
1359 (count-lines (point-min) (point)))
1360 (forward-line 1)))))
1362 (defun gnus-cache-file-contents (file variable function)
1363 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1364 (let ((time (nth 5 (file-attributes file)))
1365 contents value)
1366 (if (or (null (setq value (symbol-value variable)))
1367 (not (equal (car value) file))
1368 (not (equal (nth 1 value) time)))
1369 (progn
1370 (setq contents (funcall function file))
1371 (set variable (list file time contents))
1372 contents)
1373 (nth 2 value))))
1375 (defun gnus-multiple-choice (prompt choice &optional idx)
1376 "Ask user a multiple choice question.
1377 CHOICE is a list of the choice char and help message at IDX."
1378 (let (tchar buf)
1379 (save-window-excursion
1380 (save-excursion
1381 (while (not tchar)
1382 (message "%s (%s): "
1383 prompt
1384 (concat
1385 (mapconcat (lambda (s) (char-to-string (car s)))
1386 choice ", ") ", ?"))
1387 (setq tchar (read-char))
1388 (when (not (assq tchar choice))
1389 (setq tchar nil)
1390 (setq buf (get-buffer-create "*Gnus Help*"))
1391 (pop-to-buffer buf)
1392 (fundamental-mode) ; for Emacs 20.4+
1393 (buffer-disable-undo)
1394 (erase-buffer)
1395 (insert prompt ":\n\n")
1396 (let ((max -1)
1397 (list choice)
1398 (alist choice)
1399 (idx (or idx 1))
1400 (i 0)
1401 n width pad format)
1402 ;; find the longest string to display
1403 (while list
1404 (setq n (length (nth idx (car list))))
1405 (unless (> max n)
1406 (setq max n))
1407 (setq list (cdr list)))
1408 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1409 (setq n (/ (1- (window-width)) max)) ; items per line
1410 (setq width (/ (1- (window-width)) n)) ; width of each item
1411 ;; insert `n' items, each in a field of width `width'
1412 (while alist
1413 (if (< i n)
1415 (setq i 0)
1416 (delete-char -1) ; the `\n' takes a char
1417 (insert "\n"))
1418 (setq pad (- width 3))
1419 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1420 (insert (format format (caar alist) (nth idx (car alist))))
1421 (setq alist (cdr alist))
1422 (setq i (1+ i))))))))
1423 (if (buffer-live-p buf)
1424 (kill-buffer buf))
1425 tchar))
1427 (defun gnus-select-frame-set-input-focus (frame)
1428 "Select FRAME, raise it, and set input focus, if possible."
1429 (cond ((featurep 'xemacs)
1430 (raise-frame frame)
1431 (select-frame frame)
1432 (focus-frame frame))
1433 ;; The function `select-frame-set-input-focus' won't set
1434 ;; the input focus under Emacs 21.2 and X window system.
1435 ;;((fboundp 'select-frame-set-input-focus)
1436 ;; (defalias 'gnus-select-frame-set-input-focus
1437 ;; 'select-frame-set-input-focus)
1438 ;; (select-frame-set-input-focus frame))
1440 (raise-frame frame)
1441 (select-frame frame)
1442 (cond ((and (eq window-system 'x)
1443 (fboundp 'x-focus-frame))
1444 (x-focus-frame frame))
1445 ((eq window-system 'w32)
1446 (w32-focus-frame frame)))
1447 (when focus-follows-mouse
1448 (set-mouse-position frame (1- (frame-width frame)) 0)))))
1450 (defun gnus-frame-or-window-display-name (object)
1451 "Given a frame or window, return the associated display name.
1452 Return nil otherwise."
1453 (if (featurep 'xemacs)
1454 (device-connection (dfw-device object))
1455 (if (or (framep object)
1456 (and (windowp object)
1457 (setq object (window-frame object))))
1458 (let ((display (frame-parameter object 'display)))
1459 (if (and (stringp display)
1460 ;; Exclude invalid display names.
1461 (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1462 display))
1463 display)))))
1465 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1466 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1467 "Apply FUNCTION to each element of the sequences, and make a list of the results.
1468 If there are several sequences, FUNCTION is called with that many arguments,
1469 and mapping stops as soon as the shortest sequence runs out. With just one
1470 sequence, this is like `mapcar'. With several, it is like the Common Lisp
1471 `mapcar' function extended to arbitrary sequence types."
1473 (if seqs2_n
1474 (let* ((seqs (cons seq1 seqs2_n))
1475 (cnt 0)
1476 (heads (mapcar (lambda (seq)
1477 (make-symbol (concat "head"
1478 (int-to-string
1479 (setq cnt (1+ cnt))))))
1480 seqs))
1481 (result (make-symbol "result"))
1482 (result-tail (make-symbol "result-tail")))
1483 `(let* ,(let* ((bindings (cons nil nil))
1484 (heads heads))
1485 (nconc bindings (list (list result '(cons nil nil))))
1486 (nconc bindings (list (list result-tail result)))
1487 (while heads
1488 (nconc bindings (list (list (pop heads) (pop seqs)))))
1489 (cdr bindings))
1490 (while (and ,@heads)
1491 (setcdr ,result-tail (cons (funcall ,function
1492 ,@(mapcar (lambda (h) (list 'car h))
1493 heads))
1494 nil))
1495 (setq ,result-tail (cdr ,result-tail)
1496 ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1497 (cdr ,result)))
1498 `(mapcar ,function ,seq1)))
1500 (if (fboundp 'merge)
1501 (defalias 'gnus-merge 'merge)
1502 ;; Adapted from cl-seq.el
1503 (defun gnus-merge (type list1 list2 pred)
1504 "Destructively merge lists LIST1 and LIST2 to produce a new list.
1505 Argument TYPE is for compatibility and ignored.
1506 Ordering of the elements is preserved according to PRED, a `less-than'
1507 predicate on the elements."
1508 (let ((res nil))
1509 (while (and list1 list2)
1510 (if (funcall pred (car list2) (car list1))
1511 (push (pop list2) res)
1512 (push (pop list1) res)))
1513 (nconc (nreverse res) list1 list2))))
1515 (eval-when-compile
1516 (defvar xemacs-codename))
1518 (defun gnus-emacs-version ()
1519 "Stringified Emacs version."
1520 (let ((system-v
1521 (cond
1522 ((eq gnus-user-agent 'emacs-gnus-config)
1523 system-configuration)
1524 ((eq gnus-user-agent 'emacs-gnus-type)
1525 (symbol-name system-type))
1526 (t nil))))
1527 (cond
1528 ((eq gnus-user-agent 'gnus)
1529 nil)
1530 ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1531 (concat "Emacs/" (match-string 1 emacs-version)
1532 (if system-v
1533 (concat " (" system-v ")")
1534 "")))
1535 ((string-match
1536 "\\([A-Z]*[Mm][Aa][Cc][Ss]\\)[^(]*\\(\\((beta.*)\\|'\\)\\)?"
1537 emacs-version)
1538 (concat
1539 (match-string 1 emacs-version)
1540 (format "/%d.%d" emacs-major-version emacs-minor-version)
1541 (if (match-beginning 3)
1542 (match-string 3 emacs-version)
1544 (if (boundp 'xemacs-codename)
1545 (concat
1546 " (" xemacs-codename
1547 (if system-v
1548 (concat ", " system-v ")")
1549 ")"))
1550 "")))
1551 (t emacs-version))))
1553 (defun gnus-rename-file (old-path new-path &optional trim)
1554 "Rename OLD-PATH as NEW-PATH. If TRIM, recursively delete
1555 empty directories from OLD-PATH."
1556 (when (file-exists-p old-path)
1557 (let* ((old-dir (file-name-directory old-path))
1558 (old-name (file-name-nondirectory old-path))
1559 (new-dir (file-name-directory new-path))
1560 (new-name (file-name-nondirectory new-path))
1561 temp)
1562 (gnus-make-directory new-dir)
1563 (rename-file old-path new-path t)
1564 (when trim
1565 (while (progn (setq temp (directory-files old-dir))
1566 (while (member (car temp) '("." ".."))
1567 (setq temp (cdr temp)))
1568 (= (length temp) 0))
1569 (delete-directory old-dir)
1570 (setq old-dir (file-name-as-directory
1571 (file-truename
1572 (concat old-dir "..")))))))))
1574 (if (fboundp 'set-process-query-on-exit-flag)
1575 (defalias 'gnus-set-process-query-on-exit-flag
1576 'set-process-query-on-exit-flag)
1577 (defalias 'gnus-set-process-query-on-exit-flag
1578 'process-kill-without-query))
1580 (defun gnus-beginning-of-window ()
1581 "Move point to the beginning of the window."
1582 (move-to-window-line
1583 (if (featurep 'xemacs)
1585 (min scroll-margin
1586 (max 1 (- (window-height)
1587 (if mode-line-format 1 0)
1588 (if (and (boundp 'header-line-format)
1589 (symbol-value 'header-line-format))
1590 1 0)))))))
1592 (defun gnus-end-of-window ()
1593 "Move point to the end of the window."
1594 (move-to-window-line
1595 (if (featurep 'xemacs)
1597 (max (- -1 scroll-margin)
1598 (- -1 (max 1 (- (window-height)
1599 (if mode-line-format 1 0)
1600 (if (and (boundp 'header-line-format)
1601 (symbol-value 'header-line-format))
1602 1 0))))))))
1604 (provide 'gnus-util)
1606 ;;; arch-tag: f94991af-d32b-4c97-8c26-ca12a934de49
1607 ;;; gnus-util.el ends here