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