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