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