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