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