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