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