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