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