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