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