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