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