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