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