Synch to No Gnus 200412081310.
[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
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-strip-whitespace (string)
728   "Return STRING stripped of all whitespace."
729   (while (string-match "[\r\n\t ]+" string)
730     (setq string (replace-match "" t t string)))
731   string)
732
733 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
734   "The same as `put-text-property', but don't put this prop on any newlines in the region."
735   (save-match-data
736     (save-excursion
737       (save-restriction
738         (goto-char beg)
739         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
740           (gnus-put-text-property beg (match-beginning 0) prop val)
741           (setq beg (point)))
742         (gnus-put-text-property beg (point) prop val)))))
743
744 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
745   "The same as `put-text-property', but don't put this prop on any newlines in the region."
746   (save-match-data
747     (save-excursion
748       (save-restriction
749         (goto-char beg)
750         (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
751           (gnus-overlay-put
752            (gnus-make-overlay beg (match-beginning 0))
753            prop val)
754           (setq beg (point)))
755         (gnus-overlay-put (gnus-make-overlay beg (point)) prop val)))))
756
757 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
758                                                                    prop val)
759   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
760   (let ((b beg))
761     (while (/= b end)
762       (when (get-text-property b 'gnus-face)
763         (setq b (next-single-property-change b 'gnus-face nil end)))
764       (when (/= b end)
765         (inline
766           (gnus-put-text-property
767            b (setq b (next-single-property-change b 'gnus-face nil end))
768            prop val))))))
769
770 (defmacro gnus-faces-at (position)
771   "Return a list of faces at POSITION."
772   (if (featurep 'xemacs)
773       `(let ((pos ,position))
774          (mapcar-extents 'extent-face
775                          nil (current-buffer) pos pos nil 'face))
776     `(let ((pos ,position))
777        (delq nil (cons (get-text-property pos 'face)
778                        (mapcar
779                         (lambda (overlay)
780                           (overlay-get overlay 'face))
781                         (overlays-at pos)))))))
782
783 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
784 ;;; The primary idea here is to try to protect internal datastructures
785 ;;; from becoming corrupted when the user hits C-g, or if a hook or
786 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
787 ;;; updated at the same time, or information can be lost.
788
789 (defvar gnus-atomic-be-safe t
790   "If t, certain operations will be protected from interruption by C-g.")
791
792 (defmacro gnus-atomic-progn (&rest forms)
793   "Evaluate FORMS atomically, which means to protect the evaluation
794 from being interrupted by the user.  An error from the forms themselves
795 will return without finishing the operation.  Since interrupts from
796 the user are disabled, it is recommended that only the most minimal
797 operations are performed by FORMS.  If you wish to assign many
798 complicated values atomically, compute the results into temporary
799 variables and then do only the assignment atomically."
800   `(let ((inhibit-quit gnus-atomic-be-safe))
801      ,@forms))
802
803 (put 'gnus-atomic-progn 'lisp-indent-function 0)
804
805 (defmacro gnus-atomic-progn-assign (protect &rest forms)
806   "Evaluate FORMS, but insure that the variables listed in PROTECT
807 are not changed if anything in FORMS signals an error or otherwise
808 non-locally exits.  The variables listed in PROTECT are updated atomically.
809 It is safe to use gnus-atomic-progn-assign with long computations.
810
811 Note that if any of the symbols in PROTECT were unbound, they will be
812 set to nil on a successful assignment.  In case of an error or other
813 non-local exit, it will still be unbound."
814   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
815                                                   (concat (symbol-name x)
816                                                           "-tmp"))
817                                                  x))
818                                protect))
819          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
820                                temp-sym-map))
821          (temp-sym-let (mapcar (lambda (x) (list (car x)
822                                                  `(and (boundp ',(cadr x))
823                                                        ,(cadr x))))
824                                temp-sym-map))
825          (sym-temp-let sym-temp-map)
826          (temp-sym-assign (apply 'append temp-sym-map))
827          (sym-temp-assign (apply 'append sym-temp-map))
828          (result (make-symbol "result-tmp")))
829     `(let (,@temp-sym-let
830            ,result)
831        (let ,sym-temp-let
832          (setq ,result (progn ,@forms))
833          (setq ,@temp-sym-assign))
834        (let ((inhibit-quit gnus-atomic-be-safe))
835          (setq ,@sym-temp-assign))
836        ,result)))
837
838 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
839 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
840
841 (defmacro gnus-atomic-setq (&rest pairs)
842   "Similar to setq, except that the real symbols are only assigned when
843 there are no errors.  And when the real symbols are assigned, they are
844 done so atomically.  If other variables might be changed via side-effect,
845 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
846 with potentially long computations."
847   (let ((tpairs pairs)
848         syms)
849     (while tpairs
850       (push (car tpairs) syms)
851       (setq tpairs (cddr tpairs)))
852     `(gnus-atomic-progn-assign ,syms
853        (setq ,@pairs))))
854
855 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
856
857
858 ;;; Functions for saving to babyl/mail files.
859
860 (eval-when-compile
861   (condition-case nil
862       (progn
863         (require 'rmail)
864         (autoload 'rmail-update-summary "rmailsum"))
865     (error
866      (define-compiler-macro rmail-select-summary (&rest body)
867        ;; Rmail of the XEmacs version is supplied by the package, and
868        ;; requires tm and apel packages.  However, there may be those
869        ;; who haven't installed those packages.  This macro helps such
870        ;; people even if they install those packages later.
871        `(eval '(rmail-select-summary ,@body)))
872      ;; If there's rmail but there's no tm (or there's apel of the
873      ;; mainstream, not the XEmacs version), loading rmail of the XEmacs
874      ;; version fails halfway, however it provides the rmail-select-summary
875      ;; macro which uses the following functions:
876      (autoload 'rmail-summary-displayed "rmail")
877      (autoload 'rmail-maybe-display-summary "rmail")))
878   (defvar rmail-default-rmail-file)
879   (defvar mm-text-coding-system))
880
881 (defun gnus-output-to-rmail (filename &optional ask)
882   "Append the current article to an Rmail file named FILENAME."
883   (require 'rmail)
884   (require 'mm-util)
885   ;; Most of these codes are borrowed from rmailout.el.
886   (setq filename (expand-file-name filename))
887   (setq rmail-default-rmail-file filename)
888   (let ((artbuf (current-buffer))
889         (tmpbuf (get-buffer-create " *Gnus-output*")))
890     (save-excursion
891       (or (get-file-buffer filename)
892           (file-exists-p filename)
893           (if (or (not ask)
894                   (gnus-yes-or-no-p
895                    (concat "\"" filename "\" does not exist, create it? ")))
896               (let ((file-buffer (create-file-buffer filename)))
897                 (save-excursion
898                   (set-buffer file-buffer)
899                   (rmail-insert-rmail-file-header)
900                   (let ((require-final-newline nil))
901                     (gnus-write-buffer-as-coding-system
902                      nnheader-text-coding-system filename)))
903                 (kill-buffer file-buffer))
904             (error "Output file does not exist")))
905       (set-buffer tmpbuf)
906       (erase-buffer)
907       (insert-buffer-substring artbuf)
908       (gnus-convert-article-to-rmail)
909       ;; Decide whether to append to a file or to an Emacs buffer.
910       (let ((outbuf (get-file-buffer filename)))
911         (if (not outbuf)
912             (let ((file-name-coding-system nnmail-pathname-coding-system))
913               (write-region-as-binary (point-min) (point-max)
914                                       filename 'append))
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)))
938
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                   (gnus-write-buffer-as-coding-system
956                    nnheader-text-coding-system 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                   (write-region-as-binary (point-min) (point-max)
985                                           filename 'append))))
986           ;; File has been visited, in buffer OUTBUF.
987           (set-buffer outbuf)
988           (let ((buffer-read-only nil))
989             (goto-char (point-max))
990             (unless (eobp)
991               (insert "\n"))
992             (insert "\n")
993             (insert-buffer-substring tmpbuf)))))
994     (kill-buffer tmpbuf)))
995
996 (defun gnus-convert-article-to-rmail ()
997   "Convert article in current buffer to Rmail message format."
998   (let ((buffer-read-only nil))
999     ;; Convert article directly into Babyl format.
1000     (goto-char (point-min))
1001     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1002     (while (search-forward "\n\^_" nil t) ;single char
1003       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
1004     (goto-char (point-max))
1005     (insert "\^_")))
1006
1007 (defun gnus-map-function (funs arg)
1008   "Apply the result of the first function in FUNS to the second, and so on.
1009 ARG is passed to the first function."
1010   (while funs
1011     (setq arg (funcall (pop funs) arg)))
1012   arg)
1013
1014 (defun gnus-run-hooks (&rest funcs)
1015   "Does the same as `run-hooks', but saves the current buffer."
1016   (save-current-buffer
1017     (apply 'run-hooks funcs)))
1018
1019 ;;; Various
1020
1021 (defvar gnus-group-buffer)              ; Compiler directive
1022 (defun gnus-alive-p ()
1023   "Say whether Gnus is running or not."
1024   (and (boundp 'gnus-group-buffer)
1025        (get-buffer gnus-group-buffer)
1026        (save-excursion
1027          (set-buffer gnus-group-buffer)
1028          (eq major-mode 'gnus-group-mode))))
1029
1030 (defun gnus-remove-duplicates (list)
1031   (let (new)
1032     (while list
1033       (or (member (car list) new)
1034           (setq new (cons (car list) new)))
1035       (setq list (cdr list)))
1036     (nreverse new)))
1037
1038 (defun gnus-remove-if (predicate list)
1039   "Return a copy of LIST with all items satisfying PREDICATE removed."
1040   (let (out)
1041     (while list
1042       (unless (funcall predicate (car list))
1043         (push (car list) out))
1044       (setq list (cdr list)))
1045     (nreverse out)))
1046
1047 (if (fboundp 'assq-delete-all)
1048     (defalias 'gnus-delete-alist 'assq-delete-all)
1049   (defun gnus-delete-alist (key alist)
1050     "Delete from ALIST all elements whose car is KEY.
1051 Return the modified alist."
1052     (let (entry)
1053       (while (setq entry (assq key alist))
1054         (setq alist (delq entry alist)))
1055       alist)))
1056
1057 (defmacro gnus-pull (key alist &optional assoc-p)
1058   "Modify ALIST to be without KEY."
1059   (unless (symbolp alist)
1060     (error "Not a symbol: %s" alist))
1061   (let ((fun (if assoc-p 'assoc 'assq)))
1062     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1063
1064 (defun gnus-globalify-regexp (re)
1065   "Return a regexp that matches a whole line, iff RE matches a part of it."
1066   (concat (unless (string-match "^\\^" re) "^.*")
1067           re
1068           (unless (string-match "\\$$" re) ".*$")))
1069
1070 (defun gnus-set-window-start (&optional point)
1071   "Set the window start to POINT, or (point) if nil."
1072   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1073     (when win
1074       (set-window-start win (or point (point))))))
1075
1076 (defun gnus-annotation-in-region-p (b e)
1077   (if (= b e)
1078       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1079     (text-property-any b e 'gnus-undeletable t)))
1080
1081 (defun gnus-or (&rest elems)
1082   "Return non-nil if any of the elements are non-nil."
1083   (catch 'found
1084     (while elems
1085       (when (pop elems)
1086         (throw 'found t)))))
1087
1088 (defun gnus-and (&rest elems)
1089   "Return non-nil if all of the elements are non-nil."
1090   (catch 'found
1091     (while elems
1092       (unless (pop elems)
1093         (throw 'found nil)))
1094     t))
1095
1096 (defun gnus-write-active-file (file hashtb &optional full-names)
1097   (let ((coding-system-for-write nnmail-active-file-coding-system))
1098     (with-temp-file file
1099       (mapatoms
1100        (lambda (sym)
1101          (when (and sym
1102                     (boundp sym)
1103                     (symbol-value sym))
1104            (insert (format "%S %d %d y\n"
1105                            (if full-names
1106                                sym
1107                              (intern (gnus-group-real-name (symbol-name sym))))
1108                            (or (cdr (symbol-value sym))
1109                                (car (symbol-value sym)))
1110                            (car (symbol-value sym))))))
1111        hashtb)
1112       (goto-char (point-max))
1113       (while (search-backward "\\." nil t)
1114         (delete-char 1)))))
1115
1116 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1117 (defmacro gnus-with-output-to-file (file &rest body)
1118   (let ((buffer (make-symbol "output-buffer"))
1119         (size (make-symbol "output-buffer-size"))
1120         (leng (make-symbol "output-buffer-length"))
1121         (append (make-symbol "output-buffer-append")))
1122     `(let* ((,size 131072)
1123             (,buffer (make-string ,size 0))
1124             (,leng 0)
1125             (,append nil)
1126             (standard-output
1127              (lambda (c)
1128                (aset ,buffer ,leng c)
1129                    
1130                (if (= ,size (setq ,leng (1+ ,leng)))
1131                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1132                           (setq ,leng 0
1133                                 ,append t))))))
1134        ,@body
1135        (when (> ,leng 0)
1136          (let ((coding-system-for-write 'no-conversion))
1137          (write-region (substring ,buffer 0 ,leng) nil ,file
1138                        ,append 'no-msg))))))
1139
1140 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1141 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1142
1143 (if (fboundp 'union)
1144     (defalias 'gnus-union 'union)
1145   (defun gnus-union (l1 l2)
1146     "Set union of lists L1 and L2."
1147     (cond ((null l1) l2)
1148           ((null l2) l1)
1149           ((equal l1 l2) l1)
1150           (t
1151            (or (>= (length l1) (length l2))
1152                (setq l1 (prog1 l2 (setq l2 l1))))
1153            (while l2
1154              (or (member (car l2) l1)
1155                  (push (car l2) l1))
1156              (pop l2))
1157            l1))))
1158
1159 (defun gnus-add-text-properties-when
1160   (property value start end properties &optional object)
1161   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1162   (let (point)
1163     (while (and start
1164                 (< start end) ;; XEmacs will loop for every when start=end.
1165                 (setq point (text-property-not-all start end property value)))
1166       (gnus-add-text-properties start point properties object)
1167       (setq start (text-property-any point end property value)))
1168     (if start
1169         (gnus-add-text-properties start end properties object))))
1170
1171 (defun gnus-remove-text-properties-when
1172   (property value start end properties &optional object)
1173   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1174   (let (point)
1175     (while (and start
1176                 (< start end)
1177                 (setq point (text-property-not-all start end property value)))
1178       (remove-text-properties start point properties object)
1179       (setq start (text-property-any point end property value)))
1180     (if start
1181         (remove-text-properties start end properties object))
1182     t))
1183
1184 ;; This might use `compare-strings' to reduce consing in the
1185 ;; case-insensitive case, but it has to cope with null args.
1186 ;; (`string-equal' uses symbol print names.)
1187 (defun gnus-string-equal (x y)
1188   "Like `string-equal', except it compares case-insensitively."
1189   (and (= (length x) (length y))
1190        (or (string-equal x y)
1191            (string-equal (downcase x) (downcase y)))))
1192
1193 (defcustom gnus-use-byte-compile t
1194   "If non-nil, byte-compile crucial run-time code.
1195 Setting it to nil has no effect after the first time `gnus-byte-compile'
1196 is run."
1197   :type 'boolean
1198   :version "21.4"
1199   :group 'gnus-various)
1200
1201 (defun gnus-byte-compile (form)
1202   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1203   (if gnus-use-byte-compile
1204       (progn
1205         (condition-case nil
1206             ;; Work around a bug in XEmacs 21.4
1207             (require 'byte-optimize)
1208           (error))
1209         (require 'bytecomp)
1210         (defalias 'gnus-byte-compile
1211           (lambda (form)
1212             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1213               (byte-compile form))))
1214         (gnus-byte-compile form))
1215     form))
1216
1217 (defun gnus-remassoc (key alist)
1218   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1219 The modified LIST is returned.  If the first member
1220 of LIST has a car that is `equal' to KEY, there is no way to remove it
1221 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1222 sure of changing the value of `foo'."
1223   (when alist
1224     (if (equal key (caar alist))
1225         (cdr alist)
1226       (setcdr alist (gnus-remassoc key (cdr alist)))
1227       alist)))
1228
1229 (defun gnus-update-alist-soft (key value alist)
1230   (if value
1231       (cons (cons key value) (gnus-remassoc key alist))
1232     (gnus-remassoc key alist)))
1233
1234 (defun gnus-create-info-command (node)
1235   "Create a command that will go to info NODE."
1236   `(lambda ()
1237      (interactive)
1238      ,(concat "Enter the info system at node " node)
1239      (Info-goto-node ,node)
1240      (setq gnus-info-buffer (current-buffer))
1241      (gnus-configure-windows 'info)))
1242
1243 (defun gnus-not-ignore (&rest args)
1244   t)
1245
1246 (defvar gnus-directory-sep-char-regexp "/"
1247   "The regexp of directory separator character.
1248 If you find some problem with the directory separator character, try
1249 \"[/\\\\\]\" for some systems.")
1250
1251 (defun gnus-url-unhex (x)
1252   (if (> x ?9)
1253       (if (>= x ?a)
1254           (+ 10 (- x ?a))
1255         (+ 10 (- x ?A)))
1256     (- x ?0)))
1257
1258 ;; Fixme: Do it like QP.
1259 (defun gnus-url-unhex-string (str &optional allow-newlines)
1260   "Remove %XX, embedded spaces, etc in a url.
1261 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1262 decoding of carriage returns and line feeds in the string, which is normally
1263 forbidden in URL encoding."
1264   (let ((tmp "")
1265         (case-fold-search t))
1266     (while (string-match "%[0-9a-f][0-9a-f]" str)
1267       (let* ((start (match-beginning 0))
1268              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1269              (code (+ (* 16 ch1)
1270                       (gnus-url-unhex (elt str (+ start 2))))))
1271         (setq tmp (concat
1272                    tmp (substring str 0 start)
1273                    (cond
1274                     (allow-newlines
1275                      (char-to-string code))
1276                     ((or (= code ?\n) (= code ?\r))
1277                      " ")
1278                     (t (char-to-string code))))
1279               str (substring str (match-end 0)))))
1280     (setq tmp (concat tmp str))
1281     tmp))
1282
1283 (defun gnus-make-predicate (spec)
1284   "Transform SPEC into a function that can be called.
1285 SPEC is a predicate specifier that contains stuff like `or', `and',
1286 `not', lists and functions.  The functions all take one parameter."
1287   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1288
1289 (defun gnus-make-predicate-1 (spec)
1290   (cond
1291    ((symbolp spec)
1292     `(,spec elem))
1293    ((listp spec)
1294     (if (memq (car spec) '(or and not))
1295         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1296       (error "Invalid predicate specifier: %s" spec)))))
1297
1298 (defun gnus-completing-read (prompt table &optional predicate require-match
1299                                     history)
1300   (when (and history
1301              (not (boundp history)))
1302     (set history nil))
1303   (completing-read
1304    (if (symbol-value history)
1305        (concat prompt " (" (car (symbol-value history)) "): ")
1306      (concat prompt ": "))
1307    table
1308    predicate
1309    require-match
1310    nil
1311    history
1312    (car (symbol-value history))))
1313
1314 (defun gnus-graphic-display-p ()
1315   (or (and (fboundp 'display-graphic-p)
1316            (display-graphic-p))
1317       ;;;!!!This is bogus.  Fixme!
1318       (and (featurep 'xemacs)
1319            t)))
1320
1321 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1322 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1323
1324 (defmacro gnus-parse-without-error (&rest body)
1325   "Allow continuing onto the next line even if an error occurs."
1326   `(while (not (eobp))
1327      (condition-case ()
1328          (progn
1329            ,@body
1330            (goto-char (point-max)))
1331        (error
1332         (gnus-error 4 "Invalid data on line %d"
1333                     (count-lines (point-min) (point)))
1334         (forward-line 1)))))
1335
1336 (defun gnus-cache-file-contents (file variable function)
1337   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1338   (let ((time (nth 5 (file-attributes file)))
1339         contents value)
1340     (if (or (null (setq value (symbol-value variable)))
1341             (not (equal (car value) file))
1342             (not (equal (nth 1 value) time)))
1343         (progn
1344           (setq contents (funcall function file))
1345           (set variable (list file time contents))
1346           contents)
1347       (nth 2 value))))
1348
1349 (defun gnus-multiple-choice (prompt choice &optional idx)
1350   "Ask user a multiple choice question.
1351 CHOICE is a list of the choice char and help message at IDX."
1352   (let (tchar buf)
1353     (save-window-excursion
1354       (save-excursion
1355         (while (not tchar)
1356           (message "%s (%s): "
1357                    prompt
1358                    (concat
1359                     (mapconcat (lambda (s) (char-to-string (car s)))
1360                                choice ", ") ", ?"))
1361           (setq tchar (read-char))
1362           (when (not (assq tchar choice))
1363             (setq tchar nil)
1364             (setq buf (get-buffer-create "*Gnus Help*"))
1365             (pop-to-buffer buf)
1366             (fundamental-mode)          ; for Emacs 20.4+
1367             (buffer-disable-undo)
1368             (erase-buffer)
1369             (insert prompt ":\n\n")
1370             (let ((max -1)
1371                   (list choice)
1372                   (alist choice)
1373                   (idx (or idx 1))
1374                   (i 0)
1375                   n width pad format)
1376               ;; find the longest string to display
1377               (while list
1378                 (setq n (length (nth idx (car list))))
1379                 (unless (> max n)
1380                   (setq max n))
1381                 (setq list (cdr list)))
1382               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1383               (setq n (/ (1- (window-width)) max)) ; items per line
1384               (setq width (/ (1- (window-width)) n)) ; width of each item
1385               ;; insert `n' items, each in a field of width `width'
1386               (while alist
1387                 (if (< i n)
1388                     ()
1389                   (setq i 0)
1390                   (delete-char -1)              ; the `\n' takes a char
1391                   (insert "\n"))
1392                 (setq pad (- width 3))
1393                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1394                 (insert (format format (caar alist) (nth idx (car alist))))
1395                 (setq alist (cdr alist))
1396                 (setq i (1+ i))))))))
1397     (if (buffer-live-p buf)
1398         (kill-buffer buf))
1399     tchar))
1400
1401 (defun gnus-select-frame-set-input-focus (frame)
1402   "Select FRAME, raise it, and set input focus, if possible."
1403   (cond ((featurep 'xemacs)
1404          (raise-frame frame)
1405          (select-frame frame)
1406          (focus-frame frame))
1407         ;; The function `select-frame-set-input-focus' won't set
1408         ;; the input focus under Emacs 21.2 and X window system.
1409         ;;((fboundp 'select-frame-set-input-focus)
1410         ;; (defalias 'gnus-select-frame-set-input-focus
1411         ;;   'select-frame-set-input-focus)
1412         ;; (select-frame-set-input-focus frame))
1413         (t
1414          (raise-frame frame)
1415          (select-frame frame)
1416          (cond ((and (eq window-system 'x)
1417                      (fboundp 'x-focus-frame))
1418                 (x-focus-frame frame))
1419                ((eq window-system 'w32)
1420                 (w32-focus-frame frame)))
1421          (when focus-follows-mouse
1422            (set-mouse-position frame (1- (frame-width frame)) 0)))))
1423
1424 (defun gnus-frame-or-window-display-name (object)
1425   "Given a frame or window, return the associated display name.
1426 Return nil otherwise."
1427   (if (featurep 'xemacs)
1428       (device-connection (dfw-device object))
1429     (if (or (framep object)
1430             (and (windowp object)
1431                  (setq object (window-frame object))))
1432         (let ((display (frame-parameter object 'display)))
1433           (if (and (stringp display)
1434                    ;; Exclude invalid display names.
1435                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1436                                  display))
1437               display)))))
1438
1439 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1440 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1441   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1442 If there are several sequences, FUNCTION is called with that many arguments,
1443 and mapping stops as soon as the shortest sequence runs out.  With just one
1444 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1445 `mapcar' function extended to arbitrary sequence types."
1446
1447   (if seqs2_n
1448       (let* ((seqs (cons seq1 seqs2_n))
1449              (cnt 0)
1450              (heads (mapcar (lambda (seq)
1451                               (make-symbol (concat "head"
1452                                                    (int-to-string
1453                                                     (setq cnt (1+ cnt))))))
1454                             seqs))
1455              (result (make-symbol "result"))
1456              (result-tail (make-symbol "result-tail")))
1457         `(let* ,(let* ((bindings (cons nil nil))
1458                        (heads heads))
1459                   (nconc bindings (list (list result '(cons nil nil))))
1460                   (nconc bindings (list (list result-tail result)))
1461                   (while heads
1462                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1463                   (cdr bindings))
1464            (while (and ,@heads)
1465              (setcdr ,result-tail (cons (funcall ,function
1466                                                  ,@(mapcar (lambda (h) (list 'car h))
1467                                                            heads))
1468                                         nil))
1469              (setq ,result-tail (cdr ,result-tail)
1470                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1471            (cdr ,result)))
1472     `(mapcar ,function ,seq1)))
1473
1474 (if (fboundp 'merge)
1475     (defalias 'gnus-merge 'merge)
1476   ;; Adapted from cl-seq.el
1477   (defun gnus-merge (type list1 list2 pred)
1478     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1479 Argument TYPE is for compatibility and ignored.
1480 Ordering of the elements is preserved according to PRED, a `less-than'
1481 predicate on the elements."
1482     (let ((res nil))
1483       (while (and list1 list2)
1484         (if (funcall pred (car list2) (car list1))
1485             (push (pop list2) res)
1486           (push (pop list1) res)))
1487       (nconc (nreverse res) list1 list2))))
1488
1489 (eval-when-compile
1490   (defvar xemacs-codename))
1491
1492 (defun gnus-emacs-version ()
1493   "Stringified Emacs version."
1494   (let ((system-v
1495          (cond
1496           ((eq gnus-user-agent 'emacs-gnus-config)
1497            system-configuration)
1498           ((eq gnus-user-agent 'emacs-gnus-type)
1499            (symbol-name system-type))
1500           (t nil))))
1501     (cond
1502      ((eq gnus-user-agent 'gnus)
1503       nil)
1504      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1505       (concat "Emacs/" (match-string 1 emacs-version)
1506               (if system-v
1507                   (concat " (" system-v ")")
1508                 "")))
1509      ((string-match
1510        "\\([A-Z]*[Mm][Aa][Cc][Ss]\\)[^(]*\\(\\((beta.*)\\|'\\)\\)?"
1511        emacs-version)
1512       (concat
1513        (match-string 1 emacs-version)
1514        (format "/%d.%d" emacs-major-version emacs-minor-version)
1515        (if (match-beginning 3)
1516            (match-string 3 emacs-version)
1517          "")
1518        (if (boundp 'xemacs-codename)
1519            (concat
1520             " (" xemacs-codename
1521             (if system-v
1522                 (concat ", " system-v ")")
1523               ")"))
1524          "")))
1525      (t emacs-version))))
1526
1527 (defun gnus-rename-file (old-path new-path &optional trim)
1528   "Rename OLD-PATH as NEW-PATH.  If TRIM, recursively delete
1529 empty directories from OLD-PATH."
1530   (when (file-exists-p old-path)
1531     (let* ((old-dir (file-name-directory old-path))
1532            (old-name (file-name-nondirectory old-path))
1533            (new-dir (file-name-directory new-path))
1534            (new-name (file-name-nondirectory new-path))
1535            temp)
1536       (gnus-make-directory new-dir)
1537       (rename-file old-path new-path t)
1538       (when trim
1539         (while (progn (setq temp (directory-files old-dir))
1540                       (while (member (car temp) '("." ".."))
1541                         (setq temp (cdr temp)))
1542                       (= (length temp) 0))
1543           (delete-directory old-dir)
1544           (setq old-dir (file-name-as-directory 
1545                          (file-truename 
1546                           (concat old-dir "..")))))))))
1547
1548 (defun gnus-set-file-modes (filename mode)
1549   "Wrapper for set-file-modes."
1550   (ignore-errors
1551     (set-file-modes filename mode)))
1552
1553 (provide 'gnus-util)
1554
1555 ;;; gnus-util.el ends here