f111e0c11a175e523f0e6b5a90001119e8972518
[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   (defvar rmail-default-rmail-file)
855   (defvar mm-text-coding-system))
856
857 (defun gnus-output-to-rmail (filename &optional ask)
858   "Append the current article to an Rmail file named FILENAME."
859   (require 'rmail)
860   (require 'mm-util)
861   ;; Most of these codes are borrowed from rmailout.el.
862   (setq filename (expand-file-name filename))
863   (setq rmail-default-rmail-file filename)
864   (let ((artbuf (current-buffer))
865         (tmpbuf (get-buffer-create " *Gnus-output*")))
866     (save-excursion
867       (or (get-file-buffer filename)
868           (file-exists-p filename)
869           (if (or (not ask)
870                   (gnus-yes-or-no-p
871                    (concat "\"" filename "\" does not exist, create it? ")))
872               (let ((file-buffer (create-file-buffer filename)))
873                 (save-excursion
874                   (set-buffer file-buffer)
875                   (rmail-insert-rmail-file-header)
876                   (let ((require-final-newline nil))
877                     (gnus-write-buffer-as-coding-system
878                      nnheader-text-coding-system filename)))
879                 (kill-buffer file-buffer))
880             (error "Output file does not exist")))
881       (set-buffer tmpbuf)
882       (erase-buffer)
883       (insert-buffer-substring artbuf)
884       (gnus-convert-article-to-rmail)
885       ;; Decide whether to append to a file or to an Emacs buffer.
886       (let ((outbuf (get-file-buffer filename)))
887         (if (not outbuf)
888             (let ((file-name-coding-system nnmail-pathname-coding-system)
889                   (pathname-coding-system nnmail-pathname-coding-system))
890               (write-region-as-binary (point-min) (point-max)
891                                       filename 'append))
892           ;; File has been visited, in buffer OUTBUF.
893           (set-buffer outbuf)
894           (let ((buffer-read-only nil)
895                 (msg (and (boundp 'rmail-current-message)
896                           (symbol-value 'rmail-current-message))))
897             ;; If MSG is non-nil, buffer is in RMAIL mode.
898             (when msg
899               (widen)
900               (narrow-to-region (point-max) (point-max)))
901             (insert-buffer-substring tmpbuf)
902             (when msg
903               (goto-char (point-min))
904               (widen)
905               (search-backward "\n\^_")
906               (narrow-to-region (point) (point-max))
907               (rmail-count-new-messages t)
908               (when (rmail-summary-exists)
909                 (rmail-select-summary
910                  (rmail-update-summary)))
911               (rmail-count-new-messages t)
912               (rmail-show-message msg))
913             (save-buffer)))))
914     (kill-buffer tmpbuf)))
915
916 (defun gnus-output-to-mail (filename &optional ask)
917   "Append the current article to a mail file named FILENAME."
918   (setq filename (expand-file-name filename))
919   (let ((artbuf (current-buffer))
920         (tmpbuf (get-buffer-create " *Gnus-output*")))
921     (save-excursion
922       ;; Create the file, if it doesn't exist.
923       (when (and (not (get-file-buffer filename))
924                  (not (file-exists-p filename)))
925         (if (or (not ask)
926                 (gnus-y-or-n-p
927                  (concat "\"" filename "\" does not exist, create it? ")))
928             (let ((file-buffer (create-file-buffer filename)))
929               (save-excursion
930                 (set-buffer file-buffer)
931                 (let ((require-final-newline nil))
932                   (gnus-write-buffer-as-coding-system
933                    nnheader-text-coding-system filename)))
934               (kill-buffer file-buffer))
935           (error "Output file does not exist")))
936       (set-buffer tmpbuf)
937       (erase-buffer)
938       (insert-buffer-substring artbuf)
939       (goto-char (point-min))
940       (if (looking-at "From ")
941           (forward-line 1)
942         (insert "From nobody " (current-time-string) "\n"))
943       (let (case-fold-search)
944         (while (re-search-forward "^From " nil t)
945           (beginning-of-line)
946           (insert ">")))
947       ;; Decide whether to append to a file or to an Emacs buffer.
948       (let ((outbuf (get-file-buffer filename)))
949         (if (not outbuf)
950             (let ((buffer-read-only nil))
951               (save-excursion
952                 (goto-char (point-max))
953                 (forward-char -2)
954                 (unless (looking-at "\n\n")
955                   (goto-char (point-max))
956                   (unless (bolp)
957                     (insert "\n"))
958                   (insert "\n"))
959                 (goto-char (point-max))
960                 (let ((file-name-coding-system nnmail-pathname-coding-system)
961                       (pathname-coding-system nnmail-pathname-coding-system))
962                   (write-region-as-binary (point-min) (point-max)
963                                           filename 'append))))
964           ;; File has been visited, in buffer OUTBUF.
965           (set-buffer outbuf)
966           (let ((buffer-read-only nil))
967             (goto-char (point-max))
968             (unless (eobp)
969               (insert "\n"))
970             (insert "\n")
971             (insert-buffer-substring tmpbuf)))))
972     (kill-buffer tmpbuf)))
973
974 (defun gnus-convert-article-to-rmail ()
975   "Convert article in current buffer to Rmail message format."
976   (let ((buffer-read-only nil))
977     ;; Convert article directly into Babyl format.
978     (goto-char (point-min))
979     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
980     (while (search-forward "\n\^_" nil t) ;single char
981       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
982     (goto-char (point-max))
983     (insert "\^_")))
984
985 (defun gnus-map-function (funs arg)
986   "Apply the result of the first function in FUNS to the second, and so on.
987 ARG is passed to the first function."
988   (while funs
989     (setq arg (funcall (pop funs) arg)))
990   arg)
991
992 (defun gnus-run-hooks (&rest funcs)
993   "Does the same as `run-hooks', but saves the current buffer."
994   (save-current-buffer
995     (apply 'run-hooks funcs)))
996
997 ;;; Various
998
999 (defvar gnus-group-buffer)              ; Compiler directive
1000 (defun gnus-alive-p ()
1001   "Say whether Gnus is running or not."
1002   (and (boundp 'gnus-group-buffer)
1003        (get-buffer gnus-group-buffer)
1004        (save-excursion
1005          (set-buffer gnus-group-buffer)
1006          (eq major-mode 'gnus-group-mode))))
1007
1008 (defun gnus-remove-duplicates (list)
1009   (let (new)
1010     (while list
1011       (or (member (car list) new)
1012           (setq new (cons (car list) new)))
1013       (setq list (cdr list)))
1014     (nreverse new)))
1015
1016 (defun gnus-remove-if (predicate list)
1017   "Return a copy of LIST with all items satisfying PREDICATE removed."
1018   (let (out)
1019     (while list
1020       (unless (funcall predicate (car list))
1021         (push (car list) out))
1022       (setq list (cdr list)))
1023     (nreverse out)))
1024
1025 (if (fboundp 'assq-delete-all)
1026     (defalias 'gnus-delete-alist 'assq-delete-all)
1027   (defun gnus-delete-alist (key alist)
1028     "Delete from ALIST all elements whose car is KEY.
1029 Return the modified alist."
1030     (let (entry)
1031       (while (setq entry (assq key alist))
1032         (setq alist (delq entry alist)))
1033       alist)))
1034
1035 (defmacro gnus-pull (key alist &optional assoc-p)
1036   "Modify ALIST to be without KEY."
1037   (unless (symbolp alist)
1038     (error "Not a symbol: %s" alist))
1039   (let ((fun (if assoc-p 'assoc 'assq)))
1040     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1041
1042 (defun gnus-globalify-regexp (re)
1043   "Return a regexp that matches a whole line, iff RE matches a part of it."
1044   (concat (unless (string-match "^\\^" re) "^.*")
1045           re
1046           (unless (string-match "\\$$" re) ".*$")))
1047
1048 (defun gnus-set-window-start (&optional point)
1049   "Set the window start to POINT, or (point) if nil."
1050   (let ((win (gnus-get-buffer-window (current-buffer) t)))
1051     (when win
1052       (set-window-start win (or point (point))))))
1053
1054 (defun gnus-annotation-in-region-p (b e)
1055   (if (= b e)
1056       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1057     (text-property-any b e 'gnus-undeletable t)))
1058
1059 (defun gnus-or (&rest elems)
1060   "Return non-nil if any of the elements are non-nil."
1061   (catch 'found
1062     (while elems
1063       (when (pop elems)
1064         (throw 'found t)))))
1065
1066 (defun gnus-and (&rest elems)
1067   "Return non-nil if all of the elements are non-nil."
1068   (catch 'found
1069     (while elems
1070       (unless (pop elems)
1071         (throw 'found nil)))
1072     t))
1073
1074 (defun gnus-write-active-file (file hashtb &optional full-names)
1075   (let ((output-coding-system nnmail-active-file-coding-system)
1076         (coding-system-for-write nnmail-active-file-coding-system))
1077     (with-temp-file file
1078       (mapatoms
1079        (lambda (sym)
1080          (when (and sym
1081                     (boundp sym)
1082                     (symbol-value sym))
1083            (insert (format "%S %d %d y\n"
1084                            (if full-names
1085                                sym
1086                              (intern (gnus-group-real-name (symbol-name sym))))
1087                            (or (cdr (symbol-value sym))
1088                                (car (symbol-value sym)))
1089                            (car (symbol-value sym))))))
1090        hashtb)
1091       (goto-char (point-max))
1092       (while (search-backward "\\." nil t)
1093         (delete-char 1)))))
1094
1095 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1096 (defmacro gnus-with-output-to-file (file &rest body)
1097   (let ((buffer (make-symbol "output-buffer"))
1098         (size (make-symbol "output-buffer-size"))
1099         (leng (make-symbol "output-buffer-length"))
1100         (append (make-symbol "output-buffer-append")))
1101     `(let* ((,size 131072)
1102             (,buffer (make-string ,size 0))
1103             (,leng 0)
1104             (,append nil)
1105             (standard-output
1106              (lambda (c)
1107                (aset ,buffer ,leng c)
1108                    
1109                (if (= ,size (setq ,leng (1+ ,leng)))
1110                    (progn (write-region ,buffer nil ,file ,append 'no-msg)
1111                           (setq ,leng 0
1112                                 ,append t))))))
1113        ,@body
1114        (when (> ,leng 0)
1115          (let ((coding-system-for-write 'no-conversion))
1116          (write-region (substring ,buffer 0 ,leng) nil ,file
1117                        ,append 'no-msg))))))
1118
1119 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1120 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1121
1122 (if (fboundp 'union)
1123     (defalias 'gnus-union 'union)
1124   (defun gnus-union (l1 l2)
1125     "Set union of lists L1 and L2."
1126     (cond ((null l1) l2)
1127           ((null l2) l1)
1128           ((equal l1 l2) l1)
1129           (t
1130            (or (>= (length l1) (length l2))
1131                (setq l1 (prog1 l2 (setq l2 l1))))
1132            (while l2
1133              (or (member (car l2) l1)
1134                  (push (car l2) l1))
1135              (pop l2))
1136            l1))))
1137
1138 (defun gnus-add-text-properties-when
1139   (property value start end properties &optional object)
1140   "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1141   (let (point)
1142     (while (and start
1143                 (< start end) ;; XEmacs will loop for every when start=end.
1144                 (setq point (text-property-not-all start end property value)))
1145       (gnus-add-text-properties start point properties object)
1146       (setq start (text-property-any point end property value)))
1147     (if start
1148         (gnus-add-text-properties start end properties object))))
1149
1150 (defun gnus-remove-text-properties-when
1151   (property value start end properties &optional object)
1152   "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1153   (let (point)
1154     (while (and start
1155                 (< start end)
1156                 (setq point (text-property-not-all start end property value)))
1157       (remove-text-properties start point properties object)
1158       (setq start (text-property-any point end property value)))
1159     (if start
1160         (remove-text-properties start end properties object))
1161     t))
1162
1163 ;; This might use `compare-strings' to reduce consing in the
1164 ;; case-insensitive case, but it has to cope with null args.
1165 ;; (`string-equal' uses symbol print names.)
1166 (defun gnus-string-equal (x y)
1167   "Like `string-equal', except it compares case-insensitively."
1168   (and (= (length x) (length y))
1169        (or (string-equal x y)
1170            (string-equal (downcase x) (downcase y)))))
1171
1172 (defcustom gnus-use-byte-compile t
1173   "If non-nil, byte-compile crucial run-time code.
1174 Setting it to nil has no effect after the first time `gnus-byte-compile'
1175 is run."
1176   :type 'boolean
1177   :version "21.1"
1178   :group 'gnus-various)
1179
1180 (defun gnus-byte-compile (form)
1181   "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1182   (if gnus-use-byte-compile
1183       (progn
1184         (condition-case nil
1185             ;; Work around a bug in XEmacs 21.4
1186             (require 'byte-optimize)
1187           (error))
1188         (require 'bytecomp)
1189         (defalias 'gnus-byte-compile
1190           (lambda (form)
1191             (let ((byte-compile-warnings '(unresolved callargs redefine)))
1192               (byte-compile form))))
1193         (gnus-byte-compile form))
1194     form))
1195
1196 (defun gnus-remassoc (key alist)
1197   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1198 The modified LIST is returned.  If the first member
1199 of LIST has a car that is `equal' to KEY, there is no way to remove it
1200 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
1201 sure of changing the value of `foo'."
1202   (when alist
1203     (if (equal key (caar alist))
1204         (cdr alist)
1205       (setcdr alist (gnus-remassoc key (cdr alist)))
1206       alist)))
1207
1208 (defun gnus-update-alist-soft (key value alist)
1209   (if value
1210       (cons (cons key value) (gnus-remassoc key alist))
1211     (gnus-remassoc key alist)))
1212
1213 (defun gnus-create-info-command (node)
1214   "Create a command that will go to info NODE."
1215   `(lambda ()
1216      (interactive)
1217      ,(concat "Enter the info system at node " node)
1218      (Info-goto-node ,node)
1219      (setq gnus-info-buffer (current-buffer))
1220      (gnus-configure-windows 'info)))
1221
1222 (defun gnus-not-ignore (&rest args)
1223   t)
1224
1225 (defvar gnus-directory-sep-char-regexp "/"
1226   "The regexp of directory separator character.
1227 If you find some problem with the directory separator character, try
1228 \"[/\\\\\]\" for some systems.")
1229
1230 (defun gnus-url-unhex (x)
1231   (if (> x ?9)
1232       (if (>= x ?a)
1233           (+ 10 (- x ?a))
1234         (+ 10 (- x ?A)))
1235     (- x ?0)))
1236
1237 ;; Fixme: Do it like QP.
1238 (defun gnus-url-unhex-string (str &optional allow-newlines)
1239   "Remove %XX, embedded spaces, etc in a url.
1240 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1241 decoding of carriage returns and line feeds in the string, which is normally
1242 forbidden in URL encoding."
1243   (let ((tmp "")
1244         (case-fold-search t))
1245     (while (string-match "%[0-9a-f][0-9a-f]" str)
1246       (let* ((start (match-beginning 0))
1247              (ch1 (gnus-url-unhex (elt str (+ start 1))))
1248              (code (+ (* 16 ch1)
1249                       (gnus-url-unhex (elt str (+ start 2))))))
1250         (setq tmp (concat
1251                    tmp (substring str 0 start)
1252                    (cond
1253                     (allow-newlines
1254                      (char-to-string code))
1255                     ((or (= code ?\n) (= code ?\r))
1256                      " ")
1257                     (t (char-to-string code))))
1258               str (substring str (match-end 0)))))
1259     (setq tmp (concat tmp str))
1260     tmp))
1261
1262 (defun gnus-make-predicate (spec)
1263   "Transform SPEC into a function that can be called.
1264 SPEC is a predicate specifier that contains stuff like `or', `and',
1265 `not', lists and functions.  The functions all take one parameter."
1266   `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1267
1268 (defun gnus-make-predicate-1 (spec)
1269   (cond
1270    ((symbolp spec)
1271     `(,spec elem))
1272    ((listp spec)
1273     (if (memq (car spec) '(or and not))
1274         `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1275       (error "Invalid predicate specifier: %s" spec)))))
1276
1277 (defun gnus-local-map-property (map)
1278   "Return a list suitable for a text property list specifying keymap MAP."
1279   (cond
1280    ((featurep 'xemacs)
1281     (list 'keymap map))
1282    ((>= emacs-major-version 21)
1283     (list 'keymap map))
1284    (t
1285     (list 'local-map map))))
1286
1287 (defmacro gnus-completing-read-maybe-default (prompt table &optional predicate
1288                                               require-match initial-contents
1289                                               history default)
1290   "Like `completing-read', allowing for non-existent 7th arg in older XEmacsen."
1291   `(completing-read ,prompt ,table ,predicate ,require-match
1292                     ,initial-contents ,history
1293                     ,@(if (and (featurep 'xemacs) (< emacs-minor-version 2))
1294                           ()
1295                         (list default))))
1296
1297 (defun gnus-completing-read (prompt table &optional predicate require-match
1298                                     history)
1299   (when (and history
1300              (not (boundp history)))
1301     (set history nil))
1302   (gnus-completing-read-maybe-default
1303    (if (symbol-value history)
1304        (concat prompt " (" (car (symbol-value history)) "): ")
1305      (concat prompt ": "))
1306    table
1307    predicate
1308    require-match
1309    nil
1310    history
1311    (car (symbol-value history))))
1312
1313 (defun gnus-graphic-display-p ()
1314   (or (and (fboundp 'display-graphic-p)
1315            (display-graphic-p))
1316       ;;;!!!This is bogus.  Fixme!
1317       (and (featurep 'xemacs)
1318            t)))
1319
1320 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1321 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1322
1323 (defmacro gnus-parse-without-error (&rest body)
1324   "Allow continuing onto the next line even if an error occurs."
1325   `(while (not (eobp))
1326      (condition-case ()
1327          (progn
1328            ,@body
1329            (goto-char (point-max)))
1330        (error
1331         (gnus-error 4 "Invalid data on line %d"
1332                     (count-lines (point-min) (point)))
1333         (forward-line 1)))))
1334
1335 (defun gnus-cache-file-contents (file variable function)
1336   "Cache the contents of FILE in VARIABLE.  The contents come from FUNCTION."
1337   (let ((time (nth 5 (file-attributes file)))
1338         contents value)
1339     (if (or (null (setq value (symbol-value variable)))
1340             (not (equal (car value) file))
1341             (not (equal (nth 1 value) time)))
1342         (progn
1343           (setq contents (funcall function file))
1344           (set variable (list file time contents))
1345           contents)
1346       (nth 2 value))))
1347
1348 (defun gnus-multiple-choice (prompt choice &optional idx)
1349   "Ask user a multiple choice question.
1350 CHOICE is a list of the choice char and help message at IDX."
1351   (let (tchar buf)
1352     (save-window-excursion
1353       (save-excursion
1354         (while (not tchar)
1355           (message "%s (%s): "
1356                    prompt
1357                    (concat
1358                     (mapconcat (lambda (s) (char-to-string (car s)))
1359                                choice ", ") ", ?"))
1360           (setq tchar (read-char))
1361           (when (not (assq tchar choice))
1362             (setq tchar nil)
1363             (setq buf (get-buffer-create "*Gnus Help*"))
1364             (pop-to-buffer buf)
1365             (fundamental-mode)          ; for Emacs 20.4+
1366             (buffer-disable-undo)
1367             (erase-buffer)
1368             (insert prompt ":\n\n")
1369             (let ((max -1)
1370                   (list choice)
1371                   (alist choice)
1372                   (idx (or idx 1))
1373                   (i 0)
1374                   n width pad format)
1375               ;; find the longest string to display
1376               (while list
1377                 (setq n (length (nth idx (car list))))
1378                 (unless (> max n)
1379                   (setq max n))
1380                 (setq list (cdr list)))
1381               (setq max (+ max 4))      ; %c, `:', SPACE, a SPACE at end
1382               (setq n (/ (1- (window-width)) max)) ; items per line
1383               (setq width (/ (1- (window-width)) n)) ; width of each item
1384               ;; insert `n' items, each in a field of width `width'
1385               (while alist
1386                 (if (< i n)
1387                     ()
1388                   (setq i 0)
1389                   (delete-char -1)              ; the `\n' takes a char
1390                   (insert "\n"))
1391                 (setq pad (- width 3))
1392                 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1393                 (insert (format format (caar alist) (nth idx (car alist))))
1394                 (setq alist (cdr alist))
1395                 (setq i (1+ i))))))))
1396     (if (buffer-live-p buf)
1397         (kill-buffer buf))
1398     tchar))
1399
1400 (defun gnus-select-frame-set-input-focus (frame)
1401   "Select FRAME, raise it, and set input focus, if possible."
1402   (cond ((featurep 'xemacs)
1403          (raise-frame frame)
1404          (select-frame frame)
1405          (focus-frame frame))
1406         ;; The function `select-frame-set-input-focus' won't set
1407         ;; the input focus under Emacs 21.2 and X window system.
1408         ;;((fboundp 'select-frame-set-input-focus)
1409         ;; (defalias 'gnus-select-frame-set-input-focus
1410         ;;   'select-frame-set-input-focus)
1411         ;; (select-frame-set-input-focus frame))
1412         (t
1413          (raise-frame frame)
1414          (select-frame frame)
1415          (cond ((and (eq window-system 'x)
1416                      (fboundp 'x-focus-frame))
1417                 (x-focus-frame frame))
1418                ((eq window-system 'w32)
1419                 (w32-focus-frame frame)))
1420          (when (or (not (boundp 'focus-follows-mouse))
1421                    (symbol-value 'focus-follows-mouse))
1422            (set-mouse-position frame (1- (frame-width frame)) 0)))))
1423
1424 (unless (fboundp 'frame-parameter)
1425   (defalias 'frame-parameter
1426     (lambda (frame parameter)
1427       "Return FRAME's value for parameter PARAMETER.
1428 If FRAME is nil, describe the currently selected frame."
1429       (cdr (assq parameter (frame-parameters frame))))))
1430
1431 (defun gnus-frame-or-window-display-name (object)
1432   "Given a frame or window, return the associated display name.
1433 Return nil otherwise."
1434   (if (featurep 'xemacs)
1435       (device-connection (dfw-device object))
1436     (if (or (framep object)
1437             (and (windowp object)
1438                  (setq object (window-frame object))))
1439         (let ((display (frame-parameter object 'display)))
1440           (if (and (stringp display)
1441                    ;; Exclude invalid display names.
1442                    (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1443                                  display))
1444               display)))))
1445
1446 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1447 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1448   "Apply FUNCTION to each element of the sequences, and make a list of the results.
1449 If there are several sequences, FUNCTION is called with that many arguments,
1450 and mapping stops as soon as the shortest sequence runs out.  With just one
1451 sequence, this is like `mapcar'.  With several, it is like the Common Lisp
1452 `mapcar' function extended to arbitrary sequence types."
1453
1454   (if seqs2_n
1455       (let* ((seqs (cons seq1 seqs2_n))
1456              (cnt 0)
1457              (heads (mapcar (lambda (seq)
1458                               (make-symbol (concat "head"
1459                                                    (int-to-string
1460                                                     (setq cnt (1+ cnt))))))
1461                             seqs))
1462              (result (make-symbol "result"))
1463              (result-tail (make-symbol "result-tail")))
1464         `(let* ,(let* ((bindings (cons nil nil))
1465                        (heads heads))
1466                   (nconc bindings (list (list result '(cons nil nil))))
1467                   (nconc bindings (list (list result-tail result)))
1468                   (while heads
1469                     (nconc bindings (list (list (pop heads) (pop seqs)))))
1470                   (cdr bindings))
1471            (while (and ,@heads)
1472              (setcdr ,result-tail (cons (funcall ,function
1473                                                  ,@(mapcar (lambda (h) (list 'car h))
1474                                                            heads))
1475                                         nil))
1476              (setq ,result-tail (cdr ,result-tail)
1477                    ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1478            (cdr ,result)))
1479     `(mapcar ,function ,seq1)))
1480
1481 (if (fboundp 'merge)
1482     (defalias 'gnus-merge 'merge)
1483   ;; Adapted from cl-seq.el
1484   (defun gnus-merge (type list1 list2 pred)
1485     "Destructively merge lists LIST1 and LIST2 to produce a new list.
1486 Argument TYPE is for compatibility and ignored.
1487 Ordering of the elements is preserved according to PRED, a `less-than'
1488 predicate on the elements."
1489     (let ((res nil))
1490       (while (and list1 list2)
1491         (if (funcall pred (car list2) (car list1))
1492             (push (pop list2) res)
1493           (push (pop list1) res)))
1494       (nconc (nreverse res) list1 list2))))
1495
1496 (eval-when-compile
1497   (defvar xemacs-codename))
1498
1499 (defun gnus-emacs-version ()
1500   (let ((system-v
1501          (cond
1502           ((eq gnus-user-agent 'emacs-gnus-config)
1503            system-configuration)
1504           ((eq gnus-user-agent 'emacs-gnus-type)
1505            (symbol-name system-type))
1506           (t nil))))
1507     (cond
1508      ((eq gnus-user-agent 'gnus)
1509       nil)
1510      ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1511       (concat (format (if (boundp 'MULE)
1512                           "Mule/2.3 (based on Emacs %s)"
1513                         "Emacs/%s")
1514                       (match-string 1 emacs-version))
1515               (if system-v
1516                   (concat " (" system-v ")")
1517                 "")))
1518      ((string-match
1519        "\\([A-Z]*[Mm][Aa][Cc][Ss]\\)[^(]*\\(\\((beta.*)\\|'\\)\\)?"
1520        emacs-version)
1521       (concat
1522        (match-string 1 emacs-version)
1523        (format "/%d.%d" emacs-major-version emacs-minor-version)
1524        (if (match-beginning 3)
1525            (match-string 3 emacs-version)
1526          "")
1527        (if (boundp 'xemacs-codename)
1528            (concat
1529             " (" xemacs-codename
1530             (if system-v
1531                 (concat ", " system-v ")")
1532               ")"))
1533          "")))
1534      (t emacs-version))))
1535
1536 (provide 'gnus-util)
1537
1538 ;;; gnus-util.el ends here