Make sure that the error message doesn't error out.
[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, 2008, 2009, 2010 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 of the License, or
14 ;; (at your option) 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.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; Nothing in this file depends on any other parts of Gnus -- all
27 ;; functions and macros in this file are utility functions that are
28 ;; used by Gnus and may be used by any other package without loading
29 ;; Gnus first.
30
31 ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
32 ;; autoloads and defvars below...]
33
34 ;;; Code:
35
36 ;; For Emacs < 22.2.
37 (eval-and-compile
38   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
39 (eval-when-compile
40   (require 'cl))
41
42 (eval-when-compile
43   (unless (fboundp 'with-no-warnings)
44     (defmacro with-no-warnings (&rest body)
45       `(progn ,@body))))
46
47 ;; Fixme: this should be a gnus variable, not nnmail-.
48 (defvar nnmail-pathname-coding-system)
49 (defvar nnmail-active-file-coding-system)
50
51 ;; Inappropriate references to other parts of Gnus.
52 (defvar gnus-emphasize-whitespace-regexp)
53 (defvar gnus-original-article-buffer)
54 (defvar gnus-user-agent)
55
56 (autoload 'gnus-get-buffer-window "gnus-win")
57 (autoload 'nnheader-narrow-to-headers "nnheader")
58 (autoload 'nnheader-replace-chars-in-string "nnheader")
59 (autoload 'mail-header-remove-comments "mail-parse")
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 latter 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 (defun gnus-extract-address-component-name (from)
196   "Extract name from a From header.
197 Uses `gnus-extract-address-components'."
198   (nth 0 (gnus-extract-address-components from)))
199
200 (defun gnus-extract-address-component-email (from)
201   "Extract e-mail address from a From header.
202 Uses `gnus-extract-address-components'."
203   (nth 1 (gnus-extract-address-components from)))
204
205 (declare-function message-fetch-field "message" (header &optional not-all))
206
207 (defun gnus-fetch-field (field)
208   "Return the value of the header FIELD of current article."
209   (require 'message)
210   (save-excursion
211     (save-restriction
212       (let ((inhibit-point-motion-hooks t))
213         (nnheader-narrow-to-headers)
214         (message-fetch-field field)))))
215
216 (defun gnus-fetch-original-field (field)
217   "Fetch FIELD from the original version of the current article."
218   (with-current-buffer gnus-original-article-buffer
219     (gnus-fetch-field field)))
220
221
222 (defun gnus-goto-colon ()
223   (beginning-of-line)
224   (let ((eol (point-at-eol)))
225     (goto-char (or (text-property-any (point) eol 'gnus-position t)
226                    (search-forward ":" eol t)
227                    (point)))))
228
229 (declare-function gnus-find-method-for-group "gnus" (group &optional info))
230 (declare-function gnus-group-name-decode "gnus-group" (string charset))
231 (declare-function gnus-group-name-charset "gnus-group" (method group))
232 ;; gnus-group requires gnus-int which requires message.
233 (declare-function message-tokenize-header "message"
234                   (header &optional separator))
235
236 (defun gnus-decode-newsgroups (newsgroups group &optional method)
237   (require 'gnus-group)
238   (let ((method (or method (gnus-find-method-for-group group))))
239     (mapconcat (lambda (group)
240                  (gnus-group-name-decode group (gnus-group-name-charset
241                                                 method group)))
242                (message-tokenize-header newsgroups)
243                ",")))
244
245 (defun gnus-remove-text-with-property (prop)
246   "Delete all text in the current buffer with text property PROP."
247   (let ((start (point-min))
248         end)
249     (unless (get-text-property start prop)
250       (setq start (next-single-property-change start prop)))
251     (while start
252       (setq end (text-property-any start (point-max) prop nil))
253       (delete-region start (or end (point-max)))
254       (setq start (when end
255                     (next-single-property-change start prop))))))
256
257 (defun gnus-newsgroup-directory-form (newsgroup)
258   "Make hierarchical directory name from NEWSGROUP name."
259   (let* ((newsgroup (gnus-newsgroup-savable-name newsgroup))
260          (idx (string-match ":" newsgroup)))
261     (concat
262      (if idx (substring newsgroup 0 idx))
263      (if idx "/")
264      (nnheader-replace-chars-in-string
265       (if idx (substring newsgroup (1+ idx)) newsgroup)
266       ?. ?/))))
267
268 (defun gnus-newsgroup-savable-name (group)
269   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
270   ;; with dots.
271   (nnheader-replace-chars-in-string group ?/ ?.))
272
273 (defun gnus-string> (s1 s2)
274   (not (or (string< s1 s2)
275            (string= s1 s2))))
276
277 (defun gnus-string< (s1 s2)
278   "Return t if first arg string is less than second in lexicographic order.
279 Case is significant if and only if `case-fold-search' is nil.
280 Symbols are also allowed; their print names are used instead."
281   (if case-fold-search
282       (string-lessp (downcase (if (symbolp s1) (symbol-name s1) s1))
283                     (downcase (if (symbolp s2) (symbol-name s2) s2)))
284     (string-lessp s1 s2)))
285
286 ;;; Time functions.
287
288 (defun gnus-file-newer-than (file date)
289   (let ((fdate (nth 5 (file-attributes file))))
290     (or (> (car fdate) (car date))
291         (and (= (car fdate) (car date))
292              (> (nth 1 fdate) (nth 1 date))))))
293
294 (eval-and-compile
295   (if (and (fboundp 'float-time)
296            (subrp (symbol-function 'float-time)))
297       (defalias 'gnus-float-time 'float-time)
298     (defun gnus-float-time (&optional time)
299       "Convert time value TIME to a floating point number.
300 TIME defaults to the current time."
301       (with-no-warnings (time-to-seconds (or time (current-time)))))))
302
303 ;;; Keymap macros.
304
305 (defmacro gnus-local-set-keys (&rest plist)
306   "Set the keys in PLIST in the current keymap."
307   `(gnus-define-keys-1 (current-local-map) ',plist))
308
309 (defmacro gnus-define-keys (keymap &rest plist)
310   "Define all keys in PLIST in KEYMAP."
311   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
312
313 (defmacro gnus-define-keys-safe (keymap &rest plist)
314   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
315   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
316
317 (put 'gnus-define-keys 'lisp-indent-function 1)
318 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
319 (put 'gnus-local-set-keys 'lisp-indent-function 1)
320
321 (defmacro gnus-define-keymap (keymap &rest plist)
322   "Define all keys in PLIST in KEYMAP."
323   `(gnus-define-keys-1 ,keymap (quote ,plist)))
324
325 (put 'gnus-define-keymap 'lisp-indent-function 1)
326
327 (defun gnus-define-keys-1 (keymap plist &optional safe)
328   (when (null keymap)
329     (error "Can't set keys in a null keymap"))
330   (cond ((symbolp keymap)
331          (setq keymap (symbol-value keymap)))
332         ((keymapp keymap))
333         ((listp keymap)
334          (set (car keymap) nil)
335          (define-prefix-command (car keymap))
336          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
337          (setq keymap (symbol-value (car keymap)))))
338   (let (key)
339     (while plist
340       (when (symbolp (setq key (pop plist)))
341         (setq key (symbol-value key)))
342       (if (or (not safe)
343               (eq (lookup-key keymap key) 'undefined))
344           (define-key keymap key (pop plist))
345         (pop plist)))))
346
347 (defun gnus-completing-read-with-default (default prompt &rest args)
348   ;; Like `completing-read', except that DEFAULT is the default argument.
349   (let* ((prompt (if default
350                      (concat prompt " (default " default "): ")
351                    (concat prompt ": ")))
352          (answer (apply 'completing-read prompt args)))
353     (if (or (null answer) (zerop (length answer)))
354         default
355       answer)))
356
357 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
358 ;; the echo area.
359 ;;
360 ;; Do we really need these functions?  Workarounds for bugs in the corresponding
361 ;; Emacs functions?  Maybe these bugs are no longer present in any supported
362 ;; (X)Emacs version?  Alias them to the original functions and see if anyone
363 ;; reports a problem.  If not, replace with original functions.  --rsteib,
364 ;; 2007-12-14
365 ;;
366 ;; All supported Emacsen clear the echo area after `yes-or-no-p', so we can
367 ;; remove `yes-or-no-p'.  RMS says that not clearing after `y-or-n-p' is
368 ;; intentional (see below), so we could remove `gnus-y-or-n-p' too.
369 ;; Objections?  --rsteib, 2008-02-16
370 ;;
371 ;; ,----[ http://thread.gmane.org/gmane.emacs.gnus.general/65099/focus=66070 ]
372 ;; | From: Richard Stallman
373 ;; | Subject: Re: Do we need gnus-yes-or-no-p and gnus-y-or-n-p?
374 ;; | To: Katsumi Yamaoka [...]
375 ;; | Cc: emacs-devel@[...], xemacs-beta@[...], ding@[...]
376 ;; | Date: Mon, 07 Jan 2008 12:16:05 -0500
377 ;; | Message-ID: <E1JBva1-000528-VY@fencepost.gnu.org>
378 ;; |
379 ;; |     The behavior of `y-or-n-p' that it doesn't clear the question
380 ;; |     and the answer is not serious of course, but I feel it is not
381 ;; |     cool.
382 ;; |
383 ;; | It is intentional.
384 ;; |
385 ;; |     Currently, it is commented out in the trunk by Reiner Steib.  He
386 ;; |     also wrote the benefit of leaving the question and the answer in
387 ;; |     the echo area as follows:
388 ;; |
389 ;; |     (http://article.gmane.org/gmane.emacs.gnus.general/66061)
390 ;; |     > In contrast to yes-or-no-p it is much easier to type y, n,
391 ;; |     > SPC, DEL, etc accidentally, so it might be useful for the user
392 ;; |     > to see what he has typed.
393 ;; |
394 ;; | Yes, that is the reason.
395 ;; `----
396
397 ;; (defun gnus-y-or-n-p (prompt)
398 ;;   (prog1
399 ;;       (y-or-n-p prompt)
400 ;;     (message "")))
401 ;; (defun gnus-yes-or-no-p (prompt)
402 ;;   (prog1
403 ;;       (yes-or-no-p prompt)
404 ;;     (message "")))
405
406 (defalias 'gnus-y-or-n-p 'y-or-n-p)
407 (defalias 'gnus-yes-or-no-p 'yes-or-no-p)
408
409 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
410 ;; age-depending date representations. (e.g. just the time if it's
411 ;; from today, the day of the week if it's within the last 7 days and
412 ;; the full date if it's older)
413
414 (defun gnus-seconds-today ()
415   "Return the number of seconds passed today."
416   (let ((now (decode-time (current-time))))
417     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
418
419 (defun gnus-seconds-month ()
420   "Return the number of seconds passed this month."
421   (let ((now (decode-time (current-time))))
422     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
423        (* (- (car (nthcdr 3 now)) 1) 3600 24))))
424
425 (defun gnus-seconds-year ()
426   "Return the number of seconds passed this year."
427   (let ((now (decode-time (current-time)))
428         (days (format-time-string "%j" (current-time))))
429     (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
430        (* (- (string-to-number days) 1) 3600 24))))
431
432 (defmacro gnus-date-get-time (date)
433   "Convert DATE string to Emacs time.
434 Cache the result as a text property stored in DATE."
435   ;; Either return the cached value...
436   `(let ((d ,date))
437      (if (equal "" d)
438          '(0 0)
439        (or (get-text-property 0 'gnus-time d)
440            ;; or compute the value...
441            (let ((time (safe-date-to-time d)))
442              ;; and store it back in the string.
443              (put-text-property 0 1 'gnus-time time d)
444              time)))))
445
446 (defvar gnus-user-date-format-alist
447   '(((gnus-seconds-today) . "%k:%M")
448     (604800 . "%a %k:%M")                   ;;that's one week
449     ((gnus-seconds-month) . "%a %d")
450     ((gnus-seconds-year) . "%b %d")
451     (t . "%b %d '%y"))                      ;;this one is used when no
452                                             ;;other does match
453   "Specifies date format depending on age of article.
454 This is an alist of items (AGE . FORMAT).  AGE can be a number (of
455 seconds) or a Lisp expression evaluating to a number.  When the age of
456 the article is less than this number, then use `format-time-string'
457 with the corresponding FORMAT for displaying the date of the article.
458 If AGE is not a number or a Lisp expression evaluating to a
459 non-number, then the corresponding FORMAT is used as a default value.
460
461 Note that the list is processed from the beginning, so it should be
462 sorted by ascending AGE.  Also note that items following the first
463 non-number AGE will be ignored.
464
465 You can use the functions `gnus-seconds-today', `gnus-seconds-month'
466 and `gnus-seconds-year' in the AGE spec.  They return the number of
467 seconds passed since the start of today, of this month, of this year,
468 respectively.")
469
470 (defun gnus-user-date (messy-date)
471   "Format the messy-date according to gnus-user-date-format-alist.
472 Returns \"  ?  \" if there's bad input or if another error occurs.
473 Input should look like this: \"Sun, 14 Oct 2001 13:34:39 +0200\"."
474   (condition-case ()
475       (let* ((messy-date (gnus-float-time (gnus-date-get-time messy-date)))
476              (now (gnus-float-time))
477              ;;If we don't find something suitable we'll use this one
478              (my-format "%b %d '%y"))
479         (let* ((difference (- now messy-date))
480                (templist gnus-user-date-format-alist)
481                (top (eval (caar templist))))
482           (while (if (numberp top) (< top difference) (not top))
483             (progn
484               (setq templist (cdr templist))
485               (setq top (eval (caar templist)))))
486           (if (stringp (cdr (car templist)))
487               (setq my-format (cdr (car templist)))))
488         (format-time-string (eval my-format) (seconds-to-time messy-date)))
489     (error "  ?   ")))
490
491 (defun gnus-dd-mmm (messy-date)
492   "Return a string like DD-MMM from a big messy string."
493   (condition-case ()
494       (format-time-string "%d-%b" (gnus-date-get-time messy-date))
495     (error "  -   ")))
496
497 (defsubst gnus-time-iso8601 (time)
498   "Return a string of TIME in YYYYMMDDTHHMMSS format."
499   (format-time-string "%Y%m%dT%H%M%S" time))
500
501 (defun gnus-date-iso8601 (date)
502   "Convert the DATE to YYYYMMDDTHHMMSS."
503   (condition-case ()
504       (gnus-time-iso8601 (gnus-date-get-time date))
505     (error "")))
506
507 (defun gnus-mode-string-quote (string)
508   "Quote all \"%\"'s in STRING."
509   (gnus-replace-in-string string "%" "%%"))
510
511 ;; Make a hash table (default and minimum size is 256).
512 ;; Optional argument HASHSIZE specifies the table size.
513 (defun gnus-make-hashtable (&optional hashsize)
514   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
515
516 ;; Make a number that is suitable for hashing; bigger than MIN and
517 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
518 ;; hardware modulo operation, so they implement it in software.  On
519 ;; many sparcs over 50% of the time to intern is spent in the modulo.
520 ;; Yes, it's slower than actually computing the hash from the string!
521 ;; So we use powers of 2 so people can optimize the modulo to a mask.
522 (defun gnus-create-hash-size (min)
523   (let ((i 1))
524     (while (< i min)
525       (setq i (* 2 i)))
526     i))
527
528 (defcustom gnus-verbose 7
529   "*Integer that says how verbose Gnus should be.
530 The higher the number, the more messages Gnus will flash to say what
531 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
532 display most important messages; and at ten, Gnus will keep on
533 jabbering all the time."
534   :group 'gnus-start
535   :type 'integer)
536
537 (defcustom gnus-add-timestamp-to-message nil
538   "Non-nil means add timestamps to messages that Gnus issues.
539 If it is `log', add timestamps to only the messages that go into the
540 \"*Messages*\" buffer (in XEmacs, it is the \" *Message-Log*\" buffer).
541 If it is neither nil nor `log', add timestamps not only to log messages
542 but also to the ones displayed in the echo area."
543   :version "23.1" ;; No Gnus
544   :group  'gnus-various
545   :type '(choice :format "%{%t%}:\n %[Value Menu%] %v"
546                  (const :tag "Logged messages only" log)
547                  (sexp :tag "All messages"
548                        :match (lambda (widget value) value)
549                        :value t)
550                  (const :tag "No timestamp" nil)))
551
552 (eval-when-compile
553   (defmacro gnus-message-with-timestamp-1 (format-string args)
554     (let ((timestamp '((format-time-string "%Y%m%dT%H%M%S" time)
555                        "." (format "%03d" (/ (nth 2 time) 1000)) "> ")))
556       (if (featurep 'xemacs)
557           `(let (str time)
558              (if (or (and (null ,format-string) (null ,args))
559                      (progn
560                        (setq str (apply 'format ,format-string ,args))
561                        (zerop (length str))))
562                  (prog1
563                      (and ,format-string str)
564                    (clear-message nil))
565                (cond ((eq gnus-add-timestamp-to-message 'log)
566                       (setq time (current-time))
567                       (display-message 'no-log str)
568                       (log-message 'message (concat ,@timestamp str)))
569                      (gnus-add-timestamp-to-message
570                       (setq time (current-time))
571                       (display-message 'message (concat ,@timestamp str)))
572                      (t
573                       (display-message 'message str))))
574              str)
575         `(let (str time)
576            (cond ((eq gnus-add-timestamp-to-message 'log)
577                   (setq str (let (message-log-max)
578                               (apply 'message ,format-string ,args)))
579                   (when (and message-log-max
580                              (> message-log-max 0)
581                              (/= (length str) 0))
582                     (setq time (current-time))
583                     (with-current-buffer (get-buffer-create "*Messages*")
584                       (goto-char (point-max))
585                       (insert ,@timestamp str "\n")
586                       (forward-line (- message-log-max))
587                       (delete-region (point-min) (point))
588                       (goto-char (point-max))))
589                   str)
590                  (gnus-add-timestamp-to-message
591                   (if (or (and (null ,format-string) (null ,args))
592                           (progn
593                             (setq str (apply 'format ,format-string ,args))
594                             (zerop (length str))))
595                       (prog1
596                           (and ,format-string str)
597                         (message nil))
598                     (setq time (current-time))
599                     (message "%s" (concat ,@timestamp str))
600                     str))
601                  (t
602                   (apply 'message ,format-string ,args))))))))
603
604 (defun gnus-message-with-timestamp (format-string &rest args)
605   "Display message with timestamp.  Arguments are the same as `message'.
606 The `gnus-add-timestamp-to-message' variable controls how to add
607 timestamp to message."
608   (gnus-message-with-timestamp-1 format-string args))
609
610 (defun gnus-message (level &rest args)
611   "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
612
613 Guideline for numbers:
614 1 - error messages, 3 - non-serious error messages, 5 - messages for things
615 that take a long time, 7 - not very important messages on stuff, 9 - messages
616 inside loops."
617   (if (<= level gnus-verbose)
618       (if gnus-add-timestamp-to-message
619           (apply 'gnus-message-with-timestamp args)
620         (apply 'message args))
621     ;; We have to do this format thingy here even if the result isn't
622     ;; shown - the return value has to be the same as the return value
623     ;; from `message'.
624     (apply 'format args)))
625
626 (defun gnus-error (level &rest args)
627   "Beep an error if LEVEL is equal to or less than `gnus-verbose'.
628 ARGS are passed to `message'."
629   (when (<= (floor level) gnus-verbose)
630     (apply 'message args)
631     (ding)
632     (let (duration)
633       (when (and (floatp level)
634                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
635         (sit-for duration))))
636   nil)
637
638 (defun gnus-split-references (references)
639   "Return a list of Message-IDs in REFERENCES."
640   (let ((beg 0)
641         (references (mail-header-remove-comments (or references "")))
642         ids)
643     (while (string-match "<[^<]+[^< \t]" references beg)
644       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
645             ids))
646     (nreverse ids)))
647
648 (defun gnus-extract-references (references)
649   "Return a list of Message-IDs in REFERENCES (in In-Reply-To
650   format), trimmed to only contain the Message-IDs."
651   (let ((ids (gnus-split-references references))
652         refs)
653     (dolist (id ids)
654       (when (string-match "<[^<>]+>" id)
655         (push (match-string 0 id) refs)))
656     refs))
657
658 (defsubst gnus-parent-id (references &optional n)
659   "Return the last Message-ID in REFERENCES.
660 If N, return the Nth ancestor instead."
661   (when (and references
662              (not (zerop (length references))))
663     (if n
664         (let ((ids (inline (gnus-split-references references))))
665           (while (nthcdr n ids)
666             (setq ids (cdr ids)))
667           (car ids))
668       (let ((references (mail-header-remove-comments references)))
669         (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
670           (match-string 1 references))))))
671
672 (defun gnus-buffer-live-p (buffer)
673   "Say whether BUFFER is alive or not."
674   (and buffer
675        (get-buffer buffer)
676        (buffer-name (get-buffer buffer))))
677
678 (defun gnus-horizontal-recenter ()
679   "Recenter the current buffer horizontally."
680   (if (< (current-column) (/ (window-width) 2))
681       (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
682     (let* ((orig (point))
683            (end (window-end (gnus-get-buffer-window (current-buffer) t)))
684            (max 0))
685       (when end
686         ;; Find the longest line currently displayed in the window.
687         (goto-char (window-start))
688         (while (and (not (eobp))
689                     (< (point) end))
690           (end-of-line)
691           (setq max (max max (current-column)))
692           (forward-line 1))
693         (goto-char orig)
694         ;; Scroll horizontally to center (sort of) the point.
695         (if (> max (window-width))
696             (set-window-hscroll
697              (gnus-get-buffer-window (current-buffer) t)
698              (min (- (current-column) (/ (window-width) 3))
699                   (+ 2 (- max (window-width)))))
700           (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
701         max))))
702
703 (defun gnus-read-event-char (&optional prompt)
704   "Get the next event."
705   (let ((event (read-event prompt)))
706     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
707     (cons (and (numberp event) event) event)))
708
709 (defun gnus-sortable-date (date)
710   "Make string suitable for sorting from DATE."
711   (gnus-time-iso8601 (date-to-time date)))
712
713 (defun gnus-copy-file (file &optional to)
714   "Copy FILE to TO."
715   (interactive
716    (list (read-file-name "Copy file: " default-directory)
717          (read-file-name "Copy file to: " default-directory)))
718   (unless to
719     (setq to (read-file-name "Copy file to: " default-directory)))
720   (when (file-directory-p to)
721     (setq to (concat (file-name-as-directory to)
722                      (file-name-nondirectory file))))
723   (copy-file file to))
724
725 (defvar gnus-work-buffer " *gnus work*")
726
727 (declare-function gnus-get-buffer-create "gnus" (name))
728 ;; gnus.el requires mm-util.
729 (declare-function mm-enable-multibyte "mm-util")
730
731 (defun gnus-set-work-buffer ()
732   "Put point in the empty Gnus work buffer."
733   (if (get-buffer gnus-work-buffer)
734       (progn
735         (set-buffer gnus-work-buffer)
736         (erase-buffer))
737     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
738     (kill-all-local-variables)
739     (mm-enable-multibyte)))
740
741 (defmacro gnus-group-real-name (group)
742   "Find the real name of a foreign newsgroup."
743   `(let ((gname ,group))
744      (if (string-match "^[^:]+:" gname)
745          (substring gname (match-end 0))
746        gname)))
747
748 (defmacro gnus-group-server (group)
749   "Find the server name of a foreign newsgroup.
750 For example, (gnus-group-server \"nnimap+yxa:INBOX.foo\") would
751 yield \"nnimap:yxa\"."
752   `(let ((gname ,group))
753      (if (string-match "^\\([^:+]+\\)\\(?:\\+\\([^:]*\\)\\)?:" gname)
754          (format "%s:%s" (match-string 1 gname) (or
755                                                  (match-string 2 gname)
756                                                  ""))
757        (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
758
759 (defun gnus-make-sort-function (funs)
760   "Return a composite sort condition based on the functions in FUNS."
761   (cond
762    ;; Just a simple function.
763    ((functionp funs) funs)
764    ;; No functions at all.
765    ((null funs) funs)
766    ;; A list of functions.
767    ((or (cdr funs)
768         (listp (car funs)))
769     (gnus-byte-compile
770      `(lambda (t1 t2)
771         ,(gnus-make-sort-function-1 (reverse funs)))))
772    ;; A list containing just one function.
773    (t
774     (car funs))))
775
776 (defun gnus-make-sort-function-1 (funs)
777   "Return a composite sort condition based on the functions in FUNS."
778   (let ((function (car funs))
779         (first 't1)
780         (last 't2))
781     (when (consp function)
782       (cond
783        ;; Reversed spec.
784        ((eq (car function) 'not)
785         (setq function (cadr function)