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