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