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