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