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