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