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