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