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