]> code.delx.au - gnu-emacs/blob - lisp/gnus/gnus-util.el
Rewrite gmm-labels usage to use cl-labels
[gnu-emacs] / lisp / gnus / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Gnus
2
3 ;; Copyright (C) 1996-2016 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Keywords: news
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; Nothing in this file depends on any other parts of Gnus -- all
26 ;; functions and macros in this file are utility functions that are
27 ;; used by Gnus and may be used by any other package without loading
28 ;; Gnus first.
29
30 ;; [Unfortunately, it does depend on other parts of Gnus, e.g. the
31 ;; autoloads and defvars below...]
32
33 ;;; Code:
34
35 (eval-when-compile
36 (require 'cl))
37
38 (require 'time-date)
39
40 (defcustom gnus-completing-read-function 'gnus-emacs-completing-read
41 "Function use to do completing read."
42 :version "24.1"
43 :group 'gnus-meta
44 :type `(radio (function-item
45 :doc "Use Emacs standard `completing-read' function."
46 gnus-emacs-completing-read)
47 (function-item
48 :doc "Use `ido-completing-read' function."
49 gnus-ido-completing-read)
50 (function-item
51 :doc "Use iswitchb based completing-read function."
52 gnus-iswitchb-completing-read)))
53
54 (defcustom gnus-completion-styles
55 (if (and (boundp 'completion-styles-alist)
56 (boundp 'completion-styles))
57 (append (when (and (assq 'substring completion-styles-alist)
58 (not (memq 'substring completion-styles)))
59 (list 'substring))
60 completion-styles)
61 nil)
62 "Value of `completion-styles' to use when completing."
63 :version "24.1"
64 :group 'gnus-meta
65 :type '(repeat symbol))
66
67 ;; Fixme: this should be a gnus variable, not nnmail-.
68 (defvar nnmail-pathname-coding-system)
69 (defvar nnmail-active-file-coding-system)
70
71 ;; Inappropriate references to other parts of Gnus.
72 (defvar gnus-emphasize-whitespace-regexp)
73 (defvar gnus-original-article-buffer)
74 (defvar gnus-user-agent)
75
76 (autoload 'gnus-get-buffer-window "gnus-win")
77 (autoload 'nnheader-narrow-to-headers "nnheader")
78 (autoload 'nnheader-replace-chars-in-string "nnheader")
79 (autoload 'mail-header-remove-comments "mail-parse")
80
81 (defun gnus-replace-in-string (string regexp newtext &optional literal)
82 "Replace all matches for REGEXP with NEWTEXT in STRING.
83 If LITERAL is non-nil, insert NEWTEXT literally. Return a new
84 string containing the replacements.
85
86 This is a compatibility function for different Emacsen."
87 (declare (obsolete replace-regexp-in-string "25.2"))
88 (replace-regexp-in-string regexp newtext string nil literal))
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 (defsubst gnus-goto-char (point)
124 (and point (goto-char point)))
125
126 (defmacro gnus-buffer-exists-p (buffer)
127 `(let ((buffer ,buffer))
128 (when buffer
129 (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
130 buffer))))
131
132 (defun gnus-delete-first (elt list)
133 "Delete by side effect the first occurrence of ELT as a member of LIST."
134 (if (equal (car list) elt)
135 (cdr list)
136 (let ((total list))
137 (while (and (cdr list)
138 (not (equal (cadr list) elt)))
139 (setq list (cdr list)))
140 (when (cdr list)
141 (setcdr list (cddr list)))
142 total)))
143
144 ;; Delete the current line (and the next N lines).
145 (defmacro gnus-delete-line (&optional n)
146 `(delete-region (point-at-bol)
147 (progn (forward-line ,(or n 1)) (point))))
148
149 (defun gnus-extract-address-components (from)
150 "Extract address components from a From header.
151 Given an RFC-822 address FROM, extract full name and canonical address.
152 Returns a list of the form (FULL-NAME CANONICAL-ADDRESS). Much more simple
153 solution than `mail-extract-address-components', which works much better, but
154 is slower."
155 (let (name address)
156 ;; First find the address - the thing with the @ in it. This may
157 ;; not be accurate in mail addresses, but does the trick most of
158 ;; the time in news messages.
159 (cond (;; Check ``<foo@bar>'' first in order to handle the quite common
160 ;; form ``"abc@xyz" <foo@bar>'' (i.e. ``@'' as part of a comment)
161 ;; correctly.
162 (string-match "<\\([^@ \t<>]+[!@][^@ \t<>]+\\)>" from)
163 (setq address (substring from (match-beginning 1) (match-end 1))))
164 ((string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
165 (setq address (substring from (match-beginning 0) (match-end 0)))))
166 ;; Then we check whether the "name <address>" format is used.
167 (and address
168 ;; Linear white space is not required.
169 (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
170 (and (setq name (substring from 0 (match-beginning 0)))
171 ;; Strip any quotes from the name.
172 (string-match "^\".*\"$" name)
173 (setq name (substring name 1 (1- (match-end 0))))))
174 ;; If not, then "address (name)" is used.
175 (or name
176 (and (string-match "(.+)" from)
177 (setq name (substring from (1+ (match-beginning 0))
178 (1- (match-end 0)))))
179 (and (string-match "()" from)
180 (setq name address))
181 ;; XOVER might not support folded From headers.
182 (and (string-match "(.*" from)
183 (setq name (substring from (1+ (match-beginning 0))
184 (match-end 0)))))
185 (list (if (string= name "") nil name) (or address from))))
186
187 (declare-function message-fetch-field "message" (header &optional not-all))
188
189 (defun gnus-fetch-field (field)
190 "Return the value of the header FIELD of current article."
191 (require 'message)
192 (save-excursion
193 (save-restriction
194 (let ((inhibit-point-motion-hooks t))
195 (nnheader-narrow-to-headers)
196 (message-fetch-field field)))))
197
198 (defun gnus-fetch-original-field (field)
199 "Fetch FIELD from the original version of the current article."
200 (with-current-buffer gnus-original-article-buffer
201 (gnus-fetch-field field)))
202
203
204 (defun gnus-goto-colon ()
205 (move-beginning-of-line 1)
206 (let ((eol (point-at-eol)))
207 (goto-char (or (text-property-any (point) eol 'gnus-position t)
208 (search-forward ":" eol t)
209 (point)))))
210
211 (declare-function gnus-find-method-for-group "gnus" (group &optional info))
212 (declare-function gnus-group-name-decode "gnus-group" (string charset))
213 (declare-function gnus-group-name-charset "gnus-group" (method group))
214 ;; gnus-group requires gnus-int which requires message.
215 (declare-function message-tokenize-header "message"
216 (header &optional separator))
217
218 (defun gnus-decode-newsgroups (newsgroups group &optional method)
219 (require 'gnus-group)
220 (let ((method (or method (gnus-find-method-for-group group))))
221 (mapconcat (lambda (group)
222 (gnus-group-name-decode group (gnus-group-name-charset
223 method group)))
224 (message-tokenize-header newsgroups)
225 ",")))
226
227 (defun gnus-remove-text-with-property (prop)
228 "Delete all text in the current buffer with text property PROP."
229 (let ((start (point-min))
230 end)
231 (unless (get-text-property start prop)
232 (setq start (next-single-property-change start prop)))
233 (while start
234 (setq end (text-property-any start (point-max) prop nil))
235 (delete-region start (or end (point-max)))
236 (setq start (when end
237 (next-single-property-change start prop))))))
238
239 (defun gnus-find-text-property-region (start end prop)
240 "Return a list of text property regions that has property PROP."
241 (let (regions value)
242 (unless (get-text-property start prop)
243 (setq start (next-single-property-change start prop)))
244 (while start
245 (setq value (get-text-property start prop)
246 end (text-property-not-all start (point-max) prop value))
247 (if (not end)
248 (setq start nil)
249 (when value
250 (push (list (set-marker (make-marker) start)
251 (set-marker (make-marker) end)
252 value)
253 regions))
254 (setq start (next-single-property-change start prop))))
255 (nreverse regions)))
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 (defun gnus-string< (s1 s2)
278 "Return t if first arg string is less than second in lexicographic order.
279 Case is significant if and only if `case-fold-search' is nil.
280 Symbols are also allowed; their print names are used instead."
281 (if case-fold-search
282 (string-lessp (downcase (if (symbolp s1) (symbol-name s1) s1))
283 (downcase (if (symbolp s2) (symbol-name s2) s2)))
284 (string-lessp s1 s2)))
285
286 ;;; Time functions.
287
288 (defun gnus-file-newer-than (file date)
289 (let ((fdate (nth 5 (file-attributes file))))
290 (or (> (car fdate) (car date))
291 (and (= (car fdate) (car date))
292 (> (nth 1 fdate) (nth 1 date))))))
293
294 ;; Every version of Emacs Gnus supports has built-in float-time.
295 ;; The featurep test silences an irritating compiler warning.
296 (defalias 'gnus-float-time
297 (if (or (featurep 'emacs)
298 (fboundp 'float-time))
299 'float-time 'time-to-seconds))
300
301 ;;; Keymap macros.
302
303 (defmacro gnus-local-set-keys (&rest plist)
304 "Set the keys in PLIST in the current keymap."
305 `(gnus-define-keys-1 (current-local-map) ',plist))
306
307 (defmacro gnus-define-keys (keymap &rest plist)
308 "Define all keys in PLIST in KEYMAP."
309 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
310
311 (defmacro gnus-define-keys-safe (keymap &rest plist)
312 "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
313 `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
314
315 (put 'gnus-define-keys 'lisp-indent-function 1)
316 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
317 (put 'gnus-local-set-keys 'lisp-indent-function 1)
318
319 (defmacro gnus-define-keymap (keymap &rest plist)
320 "Define all keys in PLIST in KEYMAP."
321 `(gnus-define-keys-1 ,keymap (quote ,plist)))
322
323 (put 'gnus-define-keymap 'lisp-indent-function 1)
324
325 (defun gnus-define-keys-1 (keymap plist &optional safe)
326 (when (null keymap)
327 (error "Can't set keys in a null keymap"))
328 (cond ((symbolp keymap)
329 (setq keymap (symbol-value keymap)))
330 ((keymapp keymap))
331 ((listp keymap)
332 (set (car keymap) nil)
333 (define-prefix-command (car keymap))
334 (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
335 (setq keymap (symbol-value (car keymap)))))
336 (let (key)
337 (while plist
338 (when (symbolp (setq key (pop plist)))
339 (setq key (symbol-value key)))
340 (if (or (not safe)
341 (eq (lookup-key keymap key) 'undefined))
342 (define-key keymap key (pop plist))
343 (pop plist)))))
344
345 (defun gnus-y-or-n-p (prompt)
346 (prog1
347 (y-or-n-p prompt)
348 (message "")))
349 (defun gnus-yes-or-no-p (prompt)
350 (prog1
351 (yes-or-no-p prompt)
352 (message "")))
353
354 ;; By Frank Schmitt <ich@Frank-Schmitt.net>. Allows to have
355 ;; age-depending date representations. (e.g. just the time if it's
356 ;; from today, the day of the week if it's within the last 7 days and
357 ;; the full date if it's older)
358
359 (defun gnus-seconds-today ()
360 "Return the number of seconds passed today."
361 (let ((now (decode-time)))
362 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600))))
363
364 (defun gnus-seconds-month ()
365 "Return the number of seconds passed this month."
366 (let ((now (decode-time)))
367 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
368 (* (- (car (nthcdr 3 now)) 1) 3600 24))))
369
370 (defun gnus-seconds-year ()
371 "Return the number of seconds passed this year."
372 (let* ((current (current-time))
373 (now (decode-time current))
374 (days (format-time-string "%j" current)))
375 (+ (car now) (* (car (cdr now)) 60) (* (car (nthcdr 2 now)) 3600)
376 (* (- (string-to-number days) 1) 3600 24))))
377
378 (defmacro gnus-date-get-time (date)
379 "Convert DATE string to Emacs time.
380 Cache the result as a text property stored in DATE."
381 ;; Either return the cached value...
382 `(let ((d ,date))
383 (if (equal "" d)
384 '(0 0)
385 (or (get-text-property 0 'gnus-time d)
386 ;; or compute the value...
387 (let ((time (safe-date-to-time d)))
388 ;; and store it back in the string.
389 (put-text-property 0 1 'gnus-time time d)
390 time)))))
391
392 (defun gnus-dd-mmm (messy-date)
393 "Return a string like DD-MMM from a big messy string."
394 (condition-case ()
395 (format-time-string "%d-%b" (gnus-date-get-time messy-date))
396 (error " - ")))
397
398 (defsubst gnus-time-iso8601 (time)
399 "Return a string of TIME in YYYYMMDDTHHMMSS format."
400 (format-time-string "%Y%m%dT%H%M%S" time))
401
402 (defun gnus-date-iso8601 (date)
403 "Convert the DATE to YYYYMMDDTHHMMSS."
404 (condition-case ()
405 (gnus-time-iso8601 (gnus-date-get-time date))
406 (error "")))
407
408 (defun gnus-mode-string-quote (string)
409 "Quote all \"%\"'s in STRING."
410 (replace-regexp-in-string "%" "%%" string))
411
412 ;; Make a hash table (default and minimum size is 256).
413 ;; Optional argument HASHSIZE specifies the table size.
414 (defun gnus-make-hashtable (&optional hashsize)
415 (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
416
417 ;; Make a number that is suitable for hashing; bigger than MIN and
418 ;; equal to some 2^x. Many machines (such as sparcs) do not have a
419 ;; hardware modulo operation, so they implement it in software. On
420 ;; many sparcs over 50% of the time to intern is spent in the modulo.
421 ;; Yes, it's slower than actually computing the hash from the string!
422 ;; So we use powers of 2 so people can optimize the modulo to a mask.
423 (defun gnus-create-hash-size (min)
424 (let ((i 1))
425 (while (< i min)
426 (setq i (* 2 i)))
427 i))
428
429 (defcustom gnus-verbose 6
430 "*Integer that says how verbose Gnus should be.
431 The higher the number, the more messages Gnus will flash to say what
432 it's doing. At zero, Gnus will be totally mute; at five, Gnus will
433 display most important messages; and at ten, Gnus will keep on
434 jabbering all the time."
435 :version "24.1"
436 :group 'gnus-start
437 :type 'integer)
438
439 (defcustom gnus-add-timestamp-to-message nil
440 "Non-nil means add timestamps to messages that Gnus issues.
441 If it is `log', add timestamps to only the messages that go into
442 the \"*Messages*\" buffer. If it is neither nil nor `log', add
443 timestamps not only to log messages but also to the ones
444 displayed in the echo area."
445 :version "23.1" ;; No Gnus
446 :group 'gnus-various
447 :type '(choice :format "%{%t%}:\n %[Value Menu%] %v"
448 (const :tag "Logged messages only" log)
449 (sexp :tag "All messages"
450 :match (lambda (widget value) value)
451 :value t)
452 (const :tag "No timestamp" nil)))
453
454 (eval-when-compile
455 (defmacro gnus-message-with-timestamp-1 (format-string args)
456 (let ((timestamp '(format-time-string "%Y%m%dT%H%M%S.%3N> " time)))
457 `(let (str time)
458 (cond ((eq gnus-add-timestamp-to-message 'log)
459 (setq str (let (message-log-max)
460 (apply 'message ,format-string ,args)))
461 (when (and message-log-max
462 (> message-log-max 0)
463 (/= (length str) 0))
464 (setq time (current-time))
465 (with-current-buffer (if (fboundp 'messages-buffer)
466 (messages-buffer)
467 (get-buffer-create "*Messages*"))
468 (goto-char (point-max))
469 (let ((inhibit-read-only t))
470 (insert ,timestamp str "\n")
471 (forward-line (- message-log-max))
472 (delete-region (point-min) (point)))
473 (goto-char (point-max))))
474 str)
475 (gnus-add-timestamp-to-message
476 (if (or (and (null ,format-string) (null ,args))
477 (progn
478 (setq str (apply 'format ,format-string ,args))
479 (zerop (length str))))
480 (prog1
481 (and ,format-string str)
482 (message nil))
483 (setq time (current-time))
484 (message "%s" (concat ,timestamp str))
485 str))
486 (t
487 (apply 'message ,format-string ,args)))))))
488
489 (defvar gnus-action-message-log nil)
490
491 (defun gnus-message-with-timestamp (format-string &rest args)
492 "Display message with timestamp. Arguments are the same as `message'.
493 The `gnus-add-timestamp-to-message' variable controls how to add
494 timestamp to message."
495 (gnus-message-with-timestamp-1 format-string args))
496
497 (defun gnus-message (level &rest args)
498 "If LEVEL is lower than `gnus-verbose' print ARGS using `message'.
499
500 Guideline for numbers:
501 1 - error messages, 3 - non-serious error messages, 5 - messages for things
502 that take a long time, 7 - not very important messages on stuff, 9 - messages
503 inside loops."
504 (if (<= level gnus-verbose)
505 (let ((message
506 (if gnus-add-timestamp-to-message
507 (apply 'gnus-message-with-timestamp args)
508 (apply 'message args))))
509 (when (and (consp gnus-action-message-log)
510 (<= level 3))
511 (push message gnus-action-message-log))
512 message)
513 ;; We have to do this format thingy here even if the result isn't
514 ;; shown - the return value has to be the same as the return value
515 ;; from `message'.
516 (apply 'format args)))
517
518 (defun gnus-final-warning ()
519 (when (and (consp gnus-action-message-log)
520 (setq gnus-action-message-log
521 (delete nil gnus-action-message-log)))
522 (message "Warning: %s"
523 (mapconcat #'identity gnus-action-message-log "; "))))
524
525 (defun gnus-error (level &rest args)
526 "Beep an error if LEVEL is equal to or less than `gnus-verbose'.
527 ARGS are passed to `message'."
528 (when (<= (floor level) gnus-verbose)
529 (apply 'message args)
530 (ding)
531 (let (duration)
532 (when (and (floatp level)
533 (not (zerop (setq duration (* 10 (- level (floor level)))))))
534 (sit-for duration))))
535 nil)
536
537 (defun gnus-split-references (references)
538 "Return a list of Message-IDs in REFERENCES."
539 (let ((beg 0)
540 (references (mail-header-remove-comments (or references "")))
541 ids)
542 (while (string-match "<[^<]+[^< \t]" references beg)
543 (push (substring references (match-beginning 0) (setq beg (match-end 0)))
544 ids))
545 (nreverse ids)))
546
547 (defun gnus-extract-references (references)
548 "Return a list of Message-IDs in REFERENCES (in In-Reply-To
549 format), trimmed to only contain the Message-IDs."
550 (let ((ids (gnus-split-references references))
551 refs)
552 (dolist (id ids)
553 (when (string-match "<[^<>]+>" id)
554 (push (match-string 0 id) refs)))
555 refs))
556
557 (defsubst gnus-parent-id (references &optional n)
558 "Return the last Message-ID in REFERENCES.
559 If N, return the Nth ancestor instead."
560 (when (and references
561 (not (zerop (length references))))
562 (if n
563 (let ((ids (inline (gnus-split-references references))))
564 (while (nthcdr n ids)
565 (setq ids (cdr ids)))
566 (car ids))
567 (let ((references (mail-header-remove-comments references)))
568 (when (string-match "\\(<[^<]+>\\)[ \t]*\\'" references)
569 (match-string 1 references))))))
570
571 (defsubst gnus-buffer-live-p (buffer)
572 "Say whether BUFFER is alive or not."
573 (and buffer (buffer-live-p (get-buffer buffer))))
574
575 (defun gnus-horizontal-recenter ()
576 "Recenter the current buffer horizontally."
577 (if (< (current-column) (/ (window-width) 2))
578 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0)
579 (let* ((orig (point))
580 (end (window-end (gnus-get-buffer-window (current-buffer) t)))
581 (max 0))
582 (when end
583 ;; Find the longest line currently displayed in the window.
584 (goto-char (window-start))
585 (while (and (not (eobp))
586 (< (point) end))
587 (end-of-line)
588 (setq max (max max (current-column)))
589 (forward-line 1))
590 (goto-char orig)
591 ;; Scroll horizontally to center (sort of) the point.
592 (if (> max (window-width))
593 (set-window-hscroll
594 (gnus-get-buffer-window (current-buffer) t)
595 (min (- (current-column) (/ (window-width) 3))
596 (+ 2 (- max (window-width)))))
597 (set-window-hscroll (gnus-get-buffer-window (current-buffer) t) 0))
598 max))))
599
600 (defun gnus-read-event-char (&optional prompt)
601 "Get the next event."
602 (let ((event (read-event prompt)))
603 (cons (and (numberp event) event) event)))
604
605 (defun gnus-copy-file (file &optional to)
606 "Copy FILE to TO."
607 (interactive
608 (list (read-file-name "Copy file: " default-directory)
609 (read-file-name "Copy file to: " default-directory)))
610 (unless to
611 (setq to (read-file-name "Copy file to: " default-directory)))
612 (when (file-directory-p to)
613 (setq to (concat (file-name-as-directory to)
614 (file-name-nondirectory file))))
615 (copy-file file to))
616
617 (defvar gnus-work-buffer " *gnus work*")
618
619 (declare-function gnus-get-buffer-create "gnus" (name))
620 ;; gnus.el requires mm-util.
621 (declare-function mm-enable-multibyte "mm-util")
622
623 (defun gnus-set-work-buffer ()
624 "Put point in the empty Gnus work buffer."
625 (if (get-buffer gnus-work-buffer)
626 (progn
627 (set-buffer gnus-work-buffer)
628 (erase-buffer))
629 (set-buffer (gnus-get-buffer-create gnus-work-buffer))
630 (kill-all-local-variables)
631 (mm-enable-multibyte)))
632
633 (defmacro gnus-group-real-name (group)
634 "Find the real name of a foreign newsgroup."
635 `(let ((gname ,group))
636 (if (string-match "^[^:]+:" gname)
637 (substring gname (match-end 0))
638 gname)))
639
640 (defmacro gnus-group-server (group)
641 "Find the server name of a foreign newsgroup.
642 For example, (gnus-group-server \"nnimap+yxa:INBOX.foo\") would
643 yield \"nnimap:yxa\"."
644 `(let ((gname ,group))
645 (if (string-match "^\\([^:+]+\\)\\(?:\\+\\([^:]*\\)\\)?:" gname)
646 (format "%s:%s" (match-string 1 gname) (or
647 (match-string 2 gname)
648 ""))
649 (format "%s:%s" (car gnus-select-method) (cadr gnus-select-method)))))
650
651 (defun gnus-make-sort-function (funs)
652 "Return a composite sort condition based on the functions in FUNS."
653 (cond
654 ;; Just a simple function.
655 ((functionp funs) funs)
656 ;; No functions at all.
657 ((null funs) funs)
658 ;; A list of functions.
659 ((or (cdr funs)
660 (listp (car funs)))
661 (gnus-byte-compile
662 `(lambda (t1 t2)
663 ,(gnus-make-sort-function-1 (reverse funs)))))
664 ;; A list containing just one function.
665 (t
666 (car funs))))
667
668 (defun gnus-make-sort-function-1 (funs)
669 "Return a composite sort condition based on the functions in FUNS."
670 (let ((function (car funs))
671 (first 't1)
672 (last 't2))
673 (when (consp function)
674 (cond
675 ;; Reversed spec.
676 ((eq (car function) 'not)
677 (setq function (cadr function)
678 first 't2
679 last 't1))
680 ((functionp function)
681 ;; Do nothing.
682 )
683 (t
684 (error "Invalid sort spec: %s" function))))
685 (if (cdr funs)
686 `(or (,function ,first ,last)
687 (and (not (,function ,last ,first))
688 ,(gnus-make-sort-function-1 (cdr funs))))
689 `(,function ,first ,last))))
690
691 (defun gnus-turn-off-edit-menu (type)
692 "Turn off edit menu in `gnus-TYPE-mode-map'."
693 (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
694 [menu-bar edit] 'undefined))
695
696 (defmacro gnus-bind-print-variables (&rest forms)
697 "Bind print-* variables and evaluate FORMS.
698 This macro is used with `prin1', `pp', etc. in order to ensure printed
699 Lisp objects are loadable. Bind `print-quoted' and `print-readably'
700 to t, and `print-escape-multibyte', `print-escape-newlines',
701 `print-escape-nonascii', `print-length', `print-level' and
702 `print-string-length' to nil."
703 `(let ((print-quoted t)
704 (print-readably t)
705 ;;print-circle
706 ;;print-continuous-numbering
707 print-escape-multibyte
708 print-escape-newlines
709 print-escape-nonascii
710 ;;print-gensym
711 print-length
712 print-level
713 print-string-length)
714 ,@forms))
715
716 (defun gnus-prin1 (form)
717 "Use `prin1' on FORM in the current buffer.
718 Bind `print-quoted' and `print-readably' to t, and `print-length' and
719 `print-level' to nil. See also `gnus-bind-print-variables'."
720 (gnus-bind-print-variables (prin1 form (current-buffer))))
721
722 (defun gnus-prin1-to-string (form)
723 "The same as `prin1'.
724 Bind `print-quoted' and `print-readably' to t, and `print-length' and
725 `print-level' to nil. See also `gnus-bind-print-variables'."
726 (gnus-bind-print-variables (prin1-to-string form)))
727
728 (defun gnus-pp (form &optional stream)
729 "Use `pp' on FORM in the current buffer.
730 Bind `print-quoted' and `print-readably' to t, and `print-length' and
731 `print-level' to nil. See also `gnus-bind-print-variables'."
732 (gnus-bind-print-variables (pp form (or stream (current-buffer)))))
733
734 (defun gnus-pp-to-string (form)
735 "The same as `pp-to-string'.
736 Bind `print-quoted' and `print-readably' to t, and `print-length' and
737 `print-level' to nil. See also `gnus-bind-print-variables'."
738 (gnus-bind-print-variables (pp-to-string form)))
739
740 (defun gnus-make-directory (directory)
741 "Make DIRECTORY (and all its parents) if it doesn't exist."
742 (require 'nnmail)
743 (let ((file-name-coding-system nnmail-pathname-coding-system))
744 (when (and directory
745 (not (file-exists-p directory)))
746 (make-directory directory t)))
747 t)
748
749 (defun gnus-write-buffer (file)
750 "Write the current buffer's contents to FILE."
751 (require 'nnmail)
752 (let ((file-name-coding-system nnmail-pathname-coding-system))
753 ;; Make sure the directory exists.
754 (gnus-make-directory (file-name-directory file))
755 ;; Write the buffer.
756 (write-region (point-min) (point-max) file nil 'quietly)))
757
758 (defun gnus-delete-file (file)
759 "Delete FILE if it exists."
760 (when (file-exists-p file)
761 (delete-file file)))
762
763 (defun gnus-delete-duplicates (list)
764 "Remove duplicate entries from LIST."
765 (let ((result nil))
766 (while list
767 (unless (member (car list) result)
768 (push (car list) result))
769 (pop list))
770 (nreverse result)))
771
772 (defun gnus-delete-directory (directory)
773 "Delete files in DIRECTORY. Subdirectories remain.
774 If there's no subdirectory, delete DIRECTORY as well."
775 (when (file-directory-p directory)
776 (let ((files (directory-files
777 directory t "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
778 file dir)
779 (while files
780 (setq file (pop files))
781 (if (eq t (car (file-attributes file)))
782 ;; `file' is a subdirectory.
783 (setq dir t)
784 ;; `file' is a file or a symlink.
785 (delete-file file)))
786 (unless dir
787 (delete-directory directory)))))
788
789 (defun gnus-strip-whitespace (string)
790 "Return STRING stripped of all whitespace."
791 (while (string-match "[\r\n\t ]+" string)
792 (setq string (replace-match "" t t string)))
793 string)
794
795 (declare-function gnus-put-text-property "gnus"
796 (start end property value &optional object))
797
798 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
799 "The same as `put-text-property', but don't put this prop on any newlines in the region."
800 (save-match-data
801 (save-excursion
802 (save-restriction
803 (goto-char beg)
804 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
805 (gnus-put-text-property beg (match-beginning 0) prop val)
806 (setq beg (point)))
807 (gnus-put-text-property beg (point) prop val)))))
808
809 (defsubst gnus-put-overlay-excluding-newlines (beg end prop val)
810 "The same as `put-text-property', but don't put this prop on any newlines in the region."
811 (save-match-data
812 (save-excursion
813 (save-restriction
814 (goto-char beg)
815 (while (re-search-forward gnus-emphasize-whitespace-regexp end 'move)
816 (overlay-put (make-overlay beg (match-beginning 0)) prop val)
817 (setq beg (point)))
818 (overlay-put (make-overlay beg (point)) prop val)))))
819
820 (defun gnus-put-text-property-excluding-characters-with-faces (beg end prop val)
821 "The same as `put-text-property', except where `gnus-face' is set.
822 If so, and PROP is `face', set the second element of its value to VAL.
823 Otherwise, do nothing."
824 (while (< beg end)
825 ;; Property values are compared with `eq'.
826 (let ((stop (next-single-property-change beg 'face nil end)))
827 (if (get-text-property beg 'gnus-face)
828 (when (eq prop 'face)
829 (setcar (cdr (get-text-property beg 'face)) (or val 'default)))
830 (inline
831 (gnus-put-text-property beg stop prop val)))
832 (setq beg stop))))
833
834 (defun gnus-get-text-property-excluding-characters-with-faces (pos prop)
835 "The same as `get-text-property', except where `gnus-face' is set.
836 If so, and PROP is `face', return the second element of its value.
837 Otherwise, return the value."
838 (let ((val (get-text-property pos prop)))
839 (if (and (get-text-property pos 'gnus-face)
840 (eq prop 'face))
841 (cadr val)
842 (get-text-property pos prop))))
843
844 (defmacro gnus-faces-at (position)
845 "Return a list of faces at POSITION."
846 `(let ((pos ,position))
847 (delq nil (cons (get-text-property pos 'face)
848 (mapcar
849 (lambda (overlay)
850 (overlay-get overlay 'face))
851 (overlays-at pos))))))
852
853 ;;; Protected and atomic operations. dmoore@ucsd.edu 21.11.1996
854 ;; The primary idea here is to try to protect internal data structures
855 ;; from becoming corrupted when the user hits C-g, or if a hook or
856 ;; similar blows up. Often in Gnus multiple tables/lists need to be
857 ;; updated at the same time, or information can be lost.
858
859 (defvar gnus-atomic-be-safe t
860 "If t, certain operations will be protected from interruption by C-g.")
861
862 (defmacro gnus-atomic-progn (&rest forms)
863 "Evaluate FORMS atomically, which means to protect the evaluation
864 from being interrupted by the user. An error from the forms themselves
865 will return without finishing the operation. Since interrupts from
866 the user are disabled, it is recommended that only the most minimal
867 operations are performed by FORMS. If you wish to assign many
868 complicated values atomically, compute the results into temporary
869 variables and then do only the assignment atomically."
870 `(let ((inhibit-quit gnus-atomic-be-safe))
871 ,@forms))
872
873 (put 'gnus-atomic-progn 'lisp-indent-function 0)
874
875 (defmacro gnus-atomic-progn-assign (protect &rest forms)
876 "Evaluate FORMS, but ensure that the variables listed in PROTECT
877 are not changed if anything in FORMS signals an error or otherwise
878 non-locally exits. The variables listed in PROTECT are updated atomically.
879 It is safe to use gnus-atomic-progn-assign with long computations.
880
881 Note that if any of the symbols in PROTECT were unbound, they will be
882 set to nil on a successful assignment. In case of an error or other
883 non-local exit, it will still be unbound."
884 (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
885 (concat (symbol-name x)
886 "-tmp"))
887 x))
888 protect))
889 (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
890 temp-sym-map))
891 (temp-sym-let (mapcar (lambda (x) (list (car x)
892 `(and (boundp ',(cadr x))
893 ,(cadr x))))
894 temp-sym-map))
895 (sym-temp-let sym-temp-map)
896 (temp-sym-assign (apply 'append temp-sym-map))
897 (sym-temp-assign (apply 'append sym-temp-map))
898 (result (make-symbol "result-tmp")))
899 `(let (,@temp-sym-let
900 ,result)
901 (let ,sym-temp-let
902 (setq ,result (progn ,@forms))
903 (setq ,@temp-sym-assign))
904 (let ((inhibit-quit gnus-atomic-be-safe))
905 (setq ,@sym-temp-assign))
906 ,result)))
907
908 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
909 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
910
911 (defmacro gnus-atomic-setq (&rest pairs)
912 "Similar to setq, except that the real symbols are only assigned when
913 there are no errors. And when the real symbols are assigned, they are
914 done so atomically. If other variables might be changed via side-effect,
915 see gnus-atomic-progn-assign. It is safe to use gnus-atomic-setq
916 with potentially long computations."
917 (let ((tpairs pairs)
918 syms)
919 (while tpairs
920 (push (car tpairs) syms)
921 (setq tpairs (cddr tpairs)))
922 `(gnus-atomic-progn-assign ,syms
923 (setq ,@pairs))))
924
925 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
926
927
928 ;;; Functions for saving to babyl/mail files.
929
930 (require 'rmail)
931 (autoload 'rmail-update-summary "rmailsum")
932
933 (defvar mm-text-coding-system)
934
935 (declare-function mm-append-to-file "mm-util"
936 (start end filename &optional codesys inhibit))
937 (declare-function rmail-swap-buffers-maybe "rmail" ())
938 (declare-function rmail-maybe-set-message-counters "rmail" ())
939 (declare-function rmail-count-new-messages "rmail" (&optional nomsg))
940 (declare-function rmail-summary-exists "rmail" ())
941 (declare-function rmail-show-message "rmail" (&optional n no-summary))
942 ;; Macroexpansion of rmail-select-summary:
943 (declare-function rmail-summary-displayed "rmail" ())
944 (declare-function rmail-pop-to-buffer "rmail" (&rest args))
945 (declare-function rmail-maybe-display-summary "rmail" ())
946
947 (defun gnus-output-to-rmail (filename &optional ask)
948 "Append the current article to an Rmail file named FILENAME.
949 In Emacs 22 this writes Babyl format; in Emacs 23 it writes mbox unless
950 FILENAME exists and is Babyl format."
951 (require 'rmail)
952 (require 'mm-util)
953 (require 'nnmail)
954 ;; Some of this codes is borrowed from rmailout.el.
955 (setq filename (expand-file-name filename))
956 ;; FIXME should we really be messing with this defcustom?
957 ;; It is not needed for the operation of this function.
958 (if (boundp 'rmail-default-rmail-file)
959 (setq rmail-default-rmail-file filename) ; 22
960 (setq rmail-default-file filename)) ; 23
961 (let ((artbuf (current-buffer))
962 (tmpbuf (get-buffer-create " *Gnus-output*"))
963 ;; Babyl rmail.el defines this, mbox does not.
964 (babyl (fboundp 'rmail-insert-rmail-file-header)))
965 (save-excursion
966 ;; Note that we ignore the possibility of visiting a Babyl
967 ;; format buffer in Emacs 23, since Rmail no longer supports that.
968 (or (get-file-buffer filename)
969 (progn
970 ;; In case someone wants to write to a Babyl file from Emacs 23.
971 (when (file-exists-p filename)
972 (setq babyl (mail-file-babyl-p filename))
973 t))
974 (if (or (not ask)
975 (gnus-yes-or-no-p
976 (concat "\"" filename "\" does not exist, create it? ")))
977 (let ((file-buffer (create-file-buffer filename)))
978 (with-current-buffer file-buffer
979 (if (fboundp 'rmail-insert-rmail-file-header)
980 (rmail-insert-rmail-file-header))
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 (if babyl
990 (gnus-convert-article-to-rmail)
991 ;; Non-Babyl case copied from gnus-output-to-mail.
992 (goto-char (point-min))
993 (if (looking-at "From ")
994 (forward-line 1)
995 (insert "From nobody " (current-time-string) "\n"))
996 (let (case-fold-search)
997 (while (re-search-forward "^From " nil t)
998 (beginning-of-line)
999 (insert ">"))))
1000 ;; Decide whether to append to a file or to an Emacs buffer.
1001 (let ((outbuf (get-file-buffer filename)))
1002 (if (not outbuf)
1003 (progn
1004 (unless babyl ; from gnus-output-to-mail
1005 (let ((buffer-read-only nil))
1006 (goto-char (point-max))
1007 (forward-char -2)
1008 (unless (looking-at "\n\n")
1009 (goto-char (point-max))
1010 (unless (bolp)
1011 (insert "\n"))
1012 (insert "\n"))))
1013 (let ((file-name-coding-system nnmail-pathname-coding-system))
1014 (mm-append-to-file (point-min) (point-max) filename)))
1015 ;; File has been visited, in buffer OUTBUF.
1016 (set-buffer outbuf)
1017 (let ((buffer-read-only nil)
1018 (msg (and (boundp 'rmail-current-message)
1019 (symbol-value 'rmail-current-message))))
1020 ;; If MSG is non-nil, buffer is in RMAIL mode.
1021 ;; Compare this with rmail-output-to-rmail-buffer in Emacs 23.
1022 (when msg
1023 (unless babyl
1024 (rmail-swap-buffers-maybe)
1025 (rmail-maybe-set-message-counters))
1026 (widen)
1027 (narrow-to-region (point-max) (point-max)))
1028 (insert-buffer-substring tmpbuf)
1029 (when msg
1030 (when babyl
1031 (goto-char (point-min))
1032 (widen)
1033 (search-backward "\n\^_")
1034 (narrow-to-region (point) (point-max)))
1035 (rmail-count-new-messages t)
1036 (when (rmail-summary-exists)
1037 (rmail-select-summary
1038 (rmail-update-summary)))
1039 (rmail-show-message msg))
1040 (save-buffer)))))
1041 (kill-buffer tmpbuf)))
1042
1043 (defun gnus-output-to-mail (filename &optional ask)
1044 "Append the current article to a mail file named FILENAME."
1045 (require 'nnmail)
1046 (setq filename (expand-file-name filename))
1047 (let ((artbuf (current-buffer))
1048 (tmpbuf (get-buffer-create " *Gnus-output*")))
1049 (save-excursion
1050 ;; Create the file, if it doesn't exist.
1051 (when (and (not (get-file-buffer filename))
1052 (not (file-exists-p filename)))
1053 (if (or (not ask)
1054 (gnus-y-or-n-p
1055 (concat "\"" filename "\" does not exist, create it? ")))
1056 (let ((file-buffer (create-file-buffer filename)))
1057 (with-current-buffer file-buffer
1058 (let ((require-final-newline nil)
1059 (coding-system-for-write mm-text-coding-system))
1060 (gnus-write-buffer filename)))
1061 (kill-buffer file-buffer))
1062 (error "Output file does not exist")))
1063 (set-buffer tmpbuf)
1064 (erase-buffer)
1065 (insert-buffer-substring artbuf)
1066 (goto-char (point-min))
1067 (if (looking-at "From ")
1068 (forward-line 1)
1069 (insert "From nobody " (current-time-string) "\n"))
1070 (let (case-fold-search)
1071 (while (re-search-forward "^From " nil t)
1072 (beginning-of-line)
1073 (insert ">")))
1074 ;; Decide whether to append to a file or to an Emacs buffer.
1075 (let ((outbuf (get-file-buffer filename)))
1076 (if (not outbuf)
1077 (let ((buffer-read-only nil))
1078 (save-excursion
1079 (goto-char (point-max))
1080 (forward-char -2)
1081 (unless (looking-at "\n\n")
1082 (goto-char (point-max))
1083 (unless (bolp)
1084 (insert "\n"))
1085 (insert "\n"))
1086 (goto-char (point-max))
1087 (let ((file-name-coding-system nnmail-pathname-coding-system))
1088 (mm-append-to-file (point-min) (point-max) filename))))
1089 ;; File has been visited, in buffer OUTBUF.
1090 (set-buffer outbuf)
1091 (let ((buffer-read-only nil))
1092 (goto-char (point-max))
1093 (unless (eobp)
1094 (insert "\n"))
1095 (insert "\n")
1096 (insert-buffer-substring tmpbuf)))))
1097 (kill-buffer tmpbuf)))
1098
1099 (defun gnus-convert-article-to-rmail ()
1100 "Convert article in current buffer to Rmail message format."
1101 (let ((buffer-read-only nil))
1102 ;; Convert article directly into Babyl format.
1103 (goto-char (point-min))
1104 (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
1105 (while (search-forward "\n\^_" nil t) ;single char
1106 (replace-match "\n^_" t t)) ;2 chars: "^" and "_"
1107 (goto-char (point-max))
1108 (insert "\^_")))
1109
1110 (defun gnus-map-function (funs arg)
1111 "Apply the result of the first function in FUNS to the second, and so on.
1112 ARG is passed to the first function."
1113 (while funs
1114 (setq arg (funcall (pop funs) arg)))
1115 arg)
1116
1117 (defun gnus-run-hooks (&rest funcs)
1118 "Does the same as `run-hooks', but saves the current buffer."
1119 (save-current-buffer
1120 (apply 'run-hooks funcs)))
1121
1122 (defun gnus-run-hook-with-args (hook &rest args)
1123 "Does the same as `run-hook-with-args', but saves the current buffer."
1124 (save-current-buffer
1125 (apply 'run-hook-with-args hook args)))
1126
1127 (defun gnus-run-mode-hooks (&rest funcs)
1128 "Run `run-mode-hooks' if it is available, otherwise `run-hooks'.
1129 This function saves the current buffer."
1130 (if (fboundp 'run-mode-hooks)
1131 (save-current-buffer (apply 'run-mode-hooks funcs))
1132 (save-current-buffer (apply 'run-hooks funcs))))
1133
1134 ;;; Various
1135
1136 (defvar gnus-group-buffer) ; Compiler directive
1137 (defun gnus-alive-p ()
1138 "Say whether Gnus is running or not."
1139 (and (boundp 'gnus-group-buffer)
1140 (get-buffer gnus-group-buffer)
1141 (with-current-buffer gnus-group-buffer
1142 (eq major-mode 'gnus-group-mode))))
1143
1144 (defun gnus-remove-if (predicate sequence &optional hash-table-p)
1145 "Return a copy of SEQUENCE with all items satisfying PREDICATE removed.
1146 SEQUENCE should be a list, a vector, or a string. Returns always a list.
1147 If HASH-TABLE-P is non-nil, regards SEQUENCE as a hash table."
1148 (let (out)
1149 (if hash-table-p
1150 (mapatoms (lambda (symbol)
1151 (unless (funcall predicate symbol)
1152 (push symbol out)))
1153 sequence)
1154 (unless (listp sequence)
1155 (setq sequence (append sequence nil)))
1156 (while sequence
1157 (unless (funcall predicate (car sequence))
1158 (push (car sequence) out))
1159 (setq sequence (cdr sequence))))
1160 (nreverse out)))
1161
1162 (defun gnus-remove-if-not (predicate sequence &optional hash-table-p)
1163 "Return a copy of SEQUENCE with all items not satisfying PREDICATE removed.
1164 SEQUENCE should be a list, a vector, or a string. Returns always a list.
1165 If HASH-TABLE-P is non-nil, regards SEQUENCE as a hash table."
1166 (let (out)
1167 (if hash-table-p
1168 (mapatoms (lambda (symbol)
1169 (when (funcall predicate symbol)
1170 (push symbol out)))
1171 sequence)
1172 (unless (listp sequence)
1173 (setq sequence (append sequence nil)))
1174 (while sequence
1175 (when (funcall predicate (car sequence))
1176 (push (car sequence) out))
1177 (setq sequence (cdr sequence))))
1178 (nreverse out)))
1179
1180 (if (fboundp 'assq-delete-all)
1181 (defalias 'gnus-delete-alist 'assq-delete-all)
1182 (defun gnus-delete-alist (key alist)
1183 "Delete from ALIST all elements whose car is KEY.
1184 Return the modified alist."
1185 (let (entry)
1186 (while (setq entry (assq key alist))
1187 (setq alist (delq entry alist)))
1188 alist)))
1189
1190 (defun gnus-grep-in-list (word list)
1191 "Find if a WORD matches any regular expression in the given LIST."
1192 (when (and word list)
1193 (catch 'found
1194 (dolist (r list)
1195 (when (string-match r word)
1196 (throw 'found r))))))
1197
1198 (defmacro gnus-alist-pull (key alist &optional assoc-p)
1199 "Modify ALIST to be without KEY."
1200 (unless (symbolp alist)
1201 (error "Not a symbol: %s" alist))
1202 (let ((fun (if assoc-p 'assoc 'assq)))
1203 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1204
1205 (defun gnus-globalify-regexp (re)
1206 "Return a regexp that matches a whole line, if RE matches a part of it."
1207 (concat (unless (string-match "^\\^" re) "^.*")
1208 re
1209 (unless (string-match "\\$$" re) ".*$")))
1210
1211 (defun gnus-set-window-start (&optional point)
1212 "Set the window start to POINT, or (point) if nil."
1213 (let ((win (gnus-get-buffer-window (current-buffer) t)))
1214 (when win
1215 (set-window-start win (or point (point))))))
1216
1217 (defun gnus-annotation-in-region-p (b e)
1218 (if (= b e)
1219 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1220 (text-property-any b e 'gnus-undeletable t)))
1221
1222 (defun gnus-or (&rest elems)
1223 "Return non-nil if any of the elements are non-nil."
1224 (catch 'found
1225 (while elems
1226 (when (pop elems)
1227 (throw 'found t)))))
1228
1229 (defun gnus-and (&rest elems)
1230 "Return non-nil if all of the elements are non-nil."
1231 (catch 'found
1232 (while elems
1233 (unless (pop elems)
1234 (throw 'found nil)))
1235 t))
1236
1237 ;; gnus.el requires mm-util.
1238 (declare-function mm-disable-multibyte "mm-util")
1239
1240 (defun gnus-write-active-file (file hashtb &optional full-names)
1241 ;; `coding-system-for-write' should be `raw-text' or equivalent.
1242 (let ((coding-system-for-write nnmail-active-file-coding-system))
1243 (with-temp-file file
1244 ;; The buffer should be in the unibyte mode because group names
1245 ;; are ASCII text or encoded non-ASCII text (i.e., unibyte).
1246 (mm-disable-multibyte)
1247 (mapatoms
1248 (lambda (sym)
1249 (when (and sym
1250 (boundp sym)
1251 (symbol-value sym))
1252 (insert (format "%S %d %d y\n"
1253 (if full-names
1254 sym
1255 (intern (gnus-group-real-name (symbol-name sym))))
1256 (or (cdr (symbol-value sym))
1257 (car (symbol-value sym)))
1258 (car (symbol-value sym))))))
1259 hashtb)
1260 (goto-char (point-max))
1261 (while (search-backward "\\." nil t)
1262 (delete-char 1)))))
1263
1264 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1265 (defmacro gnus-with-output-to-file (file &rest body)
1266 (let ((buffer (make-symbol "output-buffer"))
1267 (size (make-symbol "output-buffer-size"))
1268 (leng (make-symbol "output-buffer-length"))
1269 (append (make-symbol "output-buffer-append")))
1270 `(let* ((,size 131072)
1271 (,buffer (make-string ,size 0))
1272 (,leng 0)
1273 (,append nil)
1274 (standard-output
1275 (lambda (c)
1276 (aset ,buffer ,leng c)
1277
1278 (if (= ,size (setq ,leng (1+ ,leng)))
1279 (progn (write-region ,buffer nil ,file ,append 'no-msg)
1280 (setq ,leng 0
1281 ,append t))))))
1282 ,@body
1283 (when (> ,leng 0)
1284 (let ((coding-system-for-write 'no-conversion))
1285 (write-region (substring ,buffer 0 ,leng) nil ,file
1286 ,append 'no-msg))))))
1287
1288 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1289 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1290
1291 (if (fboundp 'union)
1292 (defalias 'gnus-union 'union)
1293 (defun gnus-union (l1 l2 &rest keys)
1294 "Set union of lists L1 and L2.
1295 If KEYS contains the `:test' and `equal' pair, use `equal' to compare
1296 items in lists, otherwise use `eq'."
1297 (cond ((null l1) l2)
1298 ((null l2) l1)
1299 ((equal l1 l2) l1)
1300 (t
1301 (or (>= (length l1) (length l2))
1302 (setq l1 (prog1 l2 (setq l2 l1))))
1303 (if (eq 'equal (plist-get keys :test))
1304 (while l2
1305 (or (member (car l2) l1)
1306 (push (car l2) l1))
1307 (pop l2))
1308 (while l2
1309 (or (memq (car l2) l1)
1310 (push (car l2) l1))
1311 (pop l2)))
1312 l1))))
1313
1314 (declare-function gnus-add-text-properties "gnus"
1315 (start end properties &optional object))
1316
1317 (defun gnus-add-text-properties-when
1318 (property value start end properties &optional object)
1319 "Like `gnus-add-text-properties', only applied on where PROPERTY is VALUE."
1320 (let (point)
1321 (while (and start
1322 (< start end) ;; XEmacs will loop for every when start=end.
1323 (setq point (text-property-not-all start end property value)))
1324 (gnus-add-text-properties start point properties object)
1325 (setq start (text-property-any point end property value)))
1326 (if start
1327 (gnus-add-text-properties start end properties object))))
1328
1329 (defun gnus-remove-text-properties-when
1330 (property value start end properties &optional object)
1331 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1332 (let (point)
1333 (while (and start
1334 (< start end)
1335 (setq point (text-property-not-all start end property value)))
1336 (remove-text-properties start point properties object)
1337 (setq start (text-property-any point end property value)))
1338 (if start
1339 (remove-text-properties start end properties object))
1340 t))
1341
1342 (defun gnus-string-remove-all-properties (string)
1343 (condition-case ()
1344 (let ((s string))
1345 (set-text-properties 0 (length string) nil string)
1346 s)
1347 (error string)))
1348
1349 ;; This might use `compare-strings' to reduce consing in the
1350 ;; case-insensitive case, but it has to cope with null args.
1351 ;; (`string-equal' uses symbol print names.)
1352 (defun gnus-string-equal (x y)
1353 "Like `string-equal', except it compares case-insensitively."
1354 (and (= (length x) (length y))
1355 (or (string-equal x y)
1356 (string-equal (downcase x) (downcase y)))))
1357
1358 (defcustom gnus-use-byte-compile t
1359 "If non-nil, byte-compile crucial run-time code.
1360 Setting it to nil has no effect after the first time `gnus-byte-compile'
1361 is run."
1362 :type 'boolean
1363 :version "22.1"
1364 :group 'gnus-various)
1365
1366 (defun gnus-byte-compile (form)
1367 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1368 (if gnus-use-byte-compile
1369 (progn
1370 (require 'bytecomp)
1371 (defalias 'gnus-byte-compile
1372 (lambda (form)
1373 (let ((byte-compile-warnings '(unresolved callargs redefine)))
1374 (byte-compile form))))
1375 (gnus-byte-compile form))
1376 form))
1377
1378 (defun gnus-remassoc (key alist)
1379 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1380 The modified LIST is returned. If the first member
1381 of LIST has a car that is `equal' to KEY, there is no way to remove it
1382 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1383 sure of changing the value of `foo'."
1384 (when alist
1385 (if (equal key (caar alist))
1386 (cdr alist)
1387 (setcdr alist (gnus-remassoc key (cdr alist)))
1388 alist)))
1389
1390 (defun gnus-update-alist-soft (key value alist)
1391 (if value
1392 (cons (cons key value) (gnus-remassoc key alist))
1393 (gnus-remassoc key alist)))
1394
1395 (defun gnus-create-info-command (node)
1396 "Create a command that will go to info NODE."
1397 `(lambda ()
1398 (interactive)
1399 ,(concat "Enter the info system at node " node)
1400 (Info-goto-node ,node)
1401 (setq gnus-info-buffer (current-buffer))
1402 (gnus-configure-windows 'info)))
1403
1404 (defun gnus-not-ignore (&rest args)
1405 t)
1406
1407 (defvar gnus-directory-sep-char-regexp "/"
1408 "The regexp of directory separator character.
1409 If you find some problem with the directory separator character, try
1410 \"[/\\\\]\" for some systems.")
1411
1412 (defun gnus-url-unhex (x)
1413 (if (> x ?9)
1414 (if (>= x ?a)
1415 (+ 10 (- x ?a))
1416 (+ 10 (- x ?A)))
1417 (- x ?0)))
1418
1419 ;; Fixme: Do it like QP.
1420 (defun gnus-url-unhex-string (str &optional allow-newlines)
1421 "Remove %XX, embedded spaces, etc in a url.
1422 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1423 decoding of carriage returns and line feeds in the string, which is normally
1424 forbidden in URL encoding."
1425 (let ((tmp "")
1426 (case-fold-search t))
1427 (while (string-match "%[0-9a-f][0-9a-f]" str)
1428 (let* ((start (match-beginning 0))
1429 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1430 (code (+ (* 16 ch1)
1431 (gnus-url-unhex (elt str (+ start 2))))))
1432 (setq tmp (concat
1433 tmp (substring str 0 start)
1434 (cond
1435 (allow-newlines
1436 (char-to-string code))
1437 ((or (= code ?\n) (= code ?\r))
1438 " ")
1439 (t (char-to-string code))))
1440 str (substring str (match-end 0)))))
1441 (setq tmp (concat tmp str))
1442 tmp))
1443
1444 (defun gnus-make-predicate (spec)
1445 "Transform SPEC into a function that can be called.
1446 SPEC is a predicate specifier that contains stuff like `or', `and',
1447 `not', lists and functions. The functions all take one parameter."
1448 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1449
1450 (defun gnus-make-predicate-1 (spec)
1451 (cond
1452 ((symbolp spec)
1453 `(,spec elem))
1454 ((listp spec)
1455 (if (memq (car spec) '(or and not))
1456 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1457 (error "Invalid predicate specifier: %s" spec)))))
1458
1459 (defun gnus-completing-read (prompt collection &optional require-match
1460 initial-input history def)
1461 "Call `gnus-completing-read-function'."
1462 (funcall gnus-completing-read-function
1463 (concat prompt (when def
1464 (concat " (default " def ")"))
1465 ": ")
1466 collection require-match initial-input history def))
1467
1468 (defun gnus-emacs-completing-read (prompt collection &optional require-match
1469 initial-input history def)
1470 "Call standard `completing-read-function'."
1471 (let ((completion-styles gnus-completion-styles))
1472 (completing-read prompt collection
1473 nil require-match initial-input history def)))
1474
1475 (autoload 'ido-completing-read "ido")
1476 (defun gnus-ido-completing-read (prompt collection &optional require-match
1477 initial-input history def)
1478 "Call `ido-completing-read-function'."
1479 (ido-completing-read prompt collection nil require-match
1480 initial-input history def))
1481
1482
1483 (declare-function iswitchb-read-buffer "iswitchb"
1484 (prompt &optional default require-match
1485 _predicate start matches-set))
1486 (defvar iswitchb-temp-buflist)
1487 (defvar iswitchb-mode)
1488
1489 (defun gnus-iswitchb-completing-read (prompt collection &optional require-match
1490 initial-input history def)
1491 "`iswitchb' based completing-read function."
1492 ;; Make sure iswitchb is loaded before we let-bind its variables.
1493 ;; If it is loaded inside the let, variables can become unbound afterwards.
1494 (require 'iswitchb)
1495 (let ((iswitchb-make-buflist-hook
1496 (lambda ()
1497 (setq iswitchb-temp-buflist
1498 (let ((choices (append
1499 (when initial-input (list initial-input))
1500 (symbol-value history) collection))
1501 filtered-choices)
1502 (dolist (x choices)
1503 (setq filtered-choices (adjoin x filtered-choices)))
1504 (nreverse filtered-choices))))))
1505 (unwind-protect
1506 (progn
1507 (or iswitchb-mode
1508 (add-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup))
1509 (iswitchb-read-buffer prompt def require-match))
1510 (or iswitchb-mode
1511 (remove-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup)))))
1512
1513 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1514 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1515
1516 (defmacro gnus-parse-without-error (&rest body)
1517 "Allow continuing onto the next line even if an error occurs."
1518 `(while (not (eobp))
1519 (condition-case ()
1520 (progn
1521 ,@body
1522 (goto-char (point-max)))
1523 (error
1524 (gnus-error 4 "Invalid data on line %d"
1525 (count-lines (point-min) (point)))
1526 (forward-line 1)))))
1527
1528 (defun gnus-cache-file-contents (file variable function)
1529 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1530 (let ((time (nth 5 (file-attributes file)))
1531 contents value)
1532 (if (or (null (setq value (symbol-value variable)))
1533 (not (equal (car value) file))
1534 (not (equal (nth 1 value) time)))
1535 (progn
1536 (setq contents (funcall function file))
1537 (set variable (list file time contents))
1538 contents)
1539 (nth 2 value))))
1540
1541 (defun gnus-multiple-choice (prompt choice &optional idx)
1542 "Ask user a multiple choice question.
1543 CHOICE is a list of the choice char and help message at IDX."
1544 (let (tchar buf)
1545 (save-window-excursion
1546 (save-excursion
1547 (while (not tchar)
1548 (message "%s (%s): "
1549 prompt
1550 (concat
1551 (mapconcat (lambda (s) (char-to-string (car s)))
1552 choice ", ") ", ?"))
1553 (setq tchar (read-char))
1554 (when (not (assq tchar choice))
1555 (setq tchar nil)
1556 (setq buf (get-buffer-create "*Gnus Help*"))
1557 (pop-to-buffer buf)
1558 (fundamental-mode) ; for Emacs 20.4+
1559 (buffer-disable-undo)
1560 (erase-buffer)
1561 (insert prompt ":\n\n")
1562 (let ((max -1)
1563 (list choice)
1564 (alist choice)
1565 (idx (or idx 1))
1566 (i 0)
1567 n width pad format)
1568 ;; find the longest string to display
1569 (while list
1570 (setq n (length (nth idx (car list))))
1571 (unless (> max n)
1572 (setq max n))
1573 (setq list (cdr list)))
1574 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1575 (setq n (/ (1- (window-width)) max)) ; items per line
1576 (setq width (/ (1- (window-width)) n)) ; width of each item
1577 ;; insert `n' items, each in a field of width `width'
1578 (while alist
1579 (if (< i n)
1580 ()
1581 (setq i 0)
1582 (delete-char -1) ; the `\n' takes a char
1583 (insert "\n"))
1584 (setq pad (- width 3))
1585 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1586 (insert (format format (caar alist) (nth idx (car alist))))
1587 (setq alist (cdr alist))
1588 (setq i (1+ i))))))))
1589 (if (buffer-live-p buf)
1590 (kill-buffer buf))
1591 tchar))
1592
1593 (defun gnus-frame-or-window-display-name (object)
1594 "Given a frame or window, return the associated display name.
1595 Return nil otherwise."
1596 (if (or (framep object)
1597 (and (windowp object)
1598 (setq object (window-frame object))))
1599 (let ((display (frame-parameter object 'display)))
1600 (if (and (stringp display)
1601 ;; Exclude invalid display names.
1602 (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1603 display))
1604 display))))
1605
1606 (defvar tool-bar-mode)
1607
1608 (defun gnus-tool-bar-update (&rest ignore)
1609 "Update the tool bar."
1610 (when (and (boundp 'tool-bar-mode)
1611 tool-bar-mode)
1612 (let* ((args nil)
1613 (func (cond ((fboundp 'tool-bar-update)
1614 'tool-bar-update)
1615 ((fboundp 'force-window-update)
1616 'force-window-update)
1617 ((fboundp 'redraw-frame)
1618 (setq args (list (selected-frame)))
1619 'redraw-frame)
1620 (t 'ignore))))
1621 (apply func args))))
1622
1623 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1624 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1625 "Apply FUNCTION to each element of the sequences, and make a list of the results.
1626 If there are several sequences, FUNCTION is called with that many arguments,
1627 and mapping stops as soon as the shortest sequence runs out. With just one
1628 sequence, this is like `mapcar'. With several, it is like the Common Lisp
1629 `mapcar' function extended to arbitrary sequence types."
1630
1631 (if seqs2_n
1632 (let* ((seqs (cons seq1 seqs2_n))
1633 (cnt 0)
1634 (heads (mapcar (lambda (seq)
1635 (make-symbol (concat "head"
1636 (int-to-string
1637 (setq cnt (1+ cnt))))))
1638 seqs))
1639 (result (make-symbol "result"))
1640 (result-tail (make-symbol "result-tail")))
1641 `(let* ,(let* ((bindings (cons nil nil))
1642 (heads heads))
1643 (nconc bindings (list (list result '(cons nil nil))))
1644 (nconc bindings (list (list result-tail result)))
1645 (while heads
1646 (nconc bindings (list (list (pop heads) (pop seqs)))))
1647 (cdr bindings))
1648 (while (and ,@heads)
1649 (setcdr ,result-tail (cons (funcall ,function
1650 ,@(mapcar (lambda (h) (list 'car h))
1651 heads))
1652 nil))
1653 (setq ,result-tail (cdr ,result-tail)
1654 ,@(apply 'nconc (mapcar (lambda (h) (list h (list 'cdr h))) heads))))
1655 (cdr ,result)))
1656 `(mapcar ,function ,seq1)))
1657
1658 (if (fboundp 'merge)
1659 (defalias 'gnus-merge 'merge)
1660 ;; Adapted from cl-seq.el
1661 (defun gnus-merge (type list1 list2 pred)
1662 "Destructively merge lists LIST1 and LIST2 to produce a new list.
1663 Argument TYPE is for compatibility and ignored.
1664 Ordering of the elements is preserved according to PRED, a `less-than'
1665 predicate on the elements."
1666 (let ((res nil))
1667 (while (and list1 list2)
1668 (if (funcall pred (car list2) (car list1))
1669 (push (pop list2) res)
1670 (push (pop list1) res)))
1671 (nconc (nreverse res) list1 list2))))
1672
1673 (defun gnus-emacs-version ()
1674 "Stringified Emacs version."
1675 (let* ((lst (if (listp gnus-user-agent)
1676 gnus-user-agent
1677 '(gnus emacs type)))
1678 (system-v (cond ((memq 'config lst)
1679 system-configuration)
1680 ((memq 'type lst)
1681 (symbol-name system-type))
1682 (t nil)))
1683 codename)
1684 (cond
1685 ((not (memq 'emacs lst))
1686 nil)
1687 ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1688 (concat "Emacs/" (match-string 1 emacs-version)
1689 (if system-v
1690 (concat " (" system-v ")")
1691 "")))
1692 (t emacs-version))))
1693
1694 (defun gnus-rename-file (old-path new-path &optional trim)
1695 "Rename OLD-PATH as NEW-PATH. If TRIM, recursively delete
1696 empty directories from OLD-PATH."
1697 (when (file-exists-p old-path)
1698 (let* ((old-dir (file-name-directory old-path))
1699 (old-name (file-name-nondirectory old-path))
1700 (new-dir (file-name-directory new-path))
1701 (new-name (file-name-nondirectory new-path))
1702 temp)
1703 (gnus-make-directory new-dir)
1704 (rename-file old-path new-path t)
1705 (when trim
1706 (while (progn (setq temp (directory-files old-dir))
1707 (while (member (car temp) '("." ".."))
1708 (setq temp (cdr temp)))
1709 (= (length temp) 0))
1710 (delete-directory old-dir)
1711 (setq old-dir (file-name-as-directory
1712 (file-truename
1713 (concat old-dir "..")))))))))
1714
1715 (defun gnus-set-file-modes (filename mode)
1716 "Wrapper for set-file-modes."
1717 (ignore-errors
1718 (set-file-modes filename mode)))
1719
1720 (if (fboundp 'set-process-query-on-exit-flag)
1721 (defalias 'gnus-set-process-query-on-exit-flag
1722 'set-process-query-on-exit-flag)
1723 (defalias 'gnus-set-process-query-on-exit-flag
1724 'process-kill-without-query))
1725
1726 (defalias 'gnus-read-shell-command
1727 (if (fboundp 'read-shell-command) 'read-shell-command 'read-string))
1728
1729 (declare-function image-size "image.c" (spec &optional pixels frame))
1730
1731 (defun gnus-rescale-image (image size)
1732 "Rescale IMAGE to SIZE if possible.
1733 SIZE is in format (WIDTH . HEIGHT). Return a new image.
1734 Sizes are in pixels."
1735 (if (or (not (fboundp 'imagemagick-types))
1736 (not (get-buffer-window (current-buffer))))
1737 image
1738 (let ((new-width (car size))
1739 (new-height (cdr size)))
1740 (when (> (cdr (image-size image t)) new-height)
1741 (setq image (or (create-image (plist-get (cdr image) :data) 'imagemagick t
1742 :height new-height)
1743 image)))
1744 (when (> (car (image-size image t)) new-width)
1745 (setq image (or
1746 (create-image (plist-get (cdr image) :data) 'imagemagick t
1747 :width new-width)
1748 image)))
1749 image)))
1750
1751 (defun gnus-recursive-directory-files (dir)
1752 "Return all regular files below DIR.
1753 The first found will be returned if a file has hard or symbolic links."
1754 (let (files attr attrs)
1755 (cl-labels
1756 ((fn (directory)
1757 (dolist (file (directory-files directory t))
1758 (setq attr (file-attributes (file-truename file)))
1759 (when (and (not (member attr attrs))
1760 (not (member (file-name-nondirectory file)
1761 '("." "..")))
1762 (file-readable-p file))
1763 (push attr attrs)
1764 (cond ((file-regular-p file)
1765 (push file files))
1766 ((file-directory-p file)
1767 (fn file)))))))
1768 (fn dir))
1769 files))
1770
1771 (defun gnus-list-memq-of-list (elements list)
1772 "Return non-nil if any of the members of ELEMENTS are in LIST."
1773 (let ((found nil))
1774 (dolist (elem elements)
1775 (setq found (or found
1776 (memq elem list))))
1777 found))
1778
1779 (eval-and-compile
1780 (cond
1781 ((fboundp 'match-substitute-replacement)
1782 (defalias 'gnus-match-substitute-replacement 'match-substitute-replacement))
1783 (t
1784 (defun gnus-match-substitute-replacement (replacement &optional fixedcase literal string subexp)
1785 "Return REPLACEMENT as it will be inserted by `replace-match'.
1786 In other words, all back-references in the form `\\&' and `\\N'
1787 are substituted with actual strings matched by the last search.
1788 Optional FIXEDCASE, LITERAL, STRING and SUBEXP have the same
1789 meaning as for `replace-match'.
1790
1791 This is the definition of match-substitute-replacement in subr.el from GNU Emacs."
1792 (let ((match (match-string 0 string)))
1793 (save-match-data
1794 (set-match-data (mapcar (lambda (x)
1795 (if (numberp x)
1796 (- x (match-beginning 0))
1797 x))
1798 (match-data t)))
1799 (replace-match replacement fixedcase literal match subexp)))))))
1800
1801 (if (fboundp 'string-match-p)
1802 (defalias 'gnus-string-match-p 'string-match-p)
1803 (defsubst gnus-string-match-p (regexp string &optional start)
1804 "\
1805 Same as `string-match' except this function does not change the match data."
1806 (save-match-data
1807 (string-match regexp string start))))
1808
1809 (if (fboundp 'string-prefix-p)
1810 (defalias 'gnus-string-prefix-p 'string-prefix-p)
1811 (defun gnus-string-prefix-p (str1 str2 &optional ignore-case)
1812 "Return non-nil if STR1 is a prefix of STR2.
1813 If IGNORE-CASE is non-nil, the comparison is done without paying attention
1814 to case differences."
1815 (and (<= (length str1) (length str2))
1816 (let ((prefix (substring str2 0 (length str1))))
1817 (if ignore-case
1818 (string-equal (downcase str1) (downcase prefix))
1819 (string-equal str1 prefix))))))
1820
1821 (defun gnus-test-list (list predicate)
1822 "To each element of LIST apply PREDICATE.
1823 Return nil if LIST is no list or is empty or some test returns nil;
1824 otherwise, return t."
1825 (when (and list (listp list))
1826 (let ((result (mapcar predicate list)))
1827 (not (memq nil result)))))
1828
1829 (defun gnus-subsetp (list1 list2)
1830 "Return t if LIST1 is a subset of LIST2.
1831 Similar to `subsetp' but use member for element test so that this works for
1832 lists of strings."
1833 (when (and (listp list1) (listp list2))
1834 (if list1
1835 (and (member (car list1) list2)
1836 (gnus-subsetp (cdr list1) list2))
1837 t)))
1838
1839 (defun gnus-setdiff (list1 list2)
1840 "Return member-based set difference of LIST1 and LIST2."
1841 (when (and list1 (listp list1) (listp list2))
1842 (if (member (car list1) list2)
1843 (gnus-setdiff (cdr list1) list2)
1844 (cons (car list1) (gnus-setdiff (cdr list1) list2)))))
1845
1846 ;;; Image functions.
1847
1848 (defun gnus-image-type-available-p (type)
1849 (and (fboundp 'image-type-available-p)
1850 (if (fboundp 'display-images-p)
1851 (display-images-p)
1852 t)
1853 (image-type-available-p type)))
1854
1855 (defun gnus-create-image (file &optional type data-p &rest props)
1856 (let ((face (plist-get props :face)))
1857 (when face
1858 (setq props (plist-put props :foreground (face-foreground face)))
1859 (setq props (plist-put props :background (face-background face))))
1860 (ignore-errors
1861 (apply 'create-image file type data-p props))))
1862
1863 (defun gnus-put-image (glyph &optional string category)
1864 (let ((point (point)))
1865 (insert-image glyph (or string " "))
1866 (put-text-property point (point) 'gnus-image-category category)
1867 (unless string
1868 (put-text-property (1- (point)) (point)
1869 'gnus-image-text-deletable t))
1870 glyph))
1871
1872 (defun gnus-remove-image (image &optional category)
1873 "Remove the image matching IMAGE and CATEGORY found first."
1874 (let ((start (point-min))
1875 val end)
1876 (while (and (not end)
1877 (or (setq val (get-text-property start 'display))
1878 (and (setq start
1879 (next-single-property-change start 'display))
1880 (setq val (get-text-property start 'display)))))
1881 (setq end (or (next-single-property-change start 'display)
1882 (point-max)))
1883 (if (and (equal val image)
1884 (equal (get-text-property start 'gnus-image-category)
1885 category))
1886 (progn
1887 (put-text-property start end 'display nil)
1888 (when (get-text-property start 'gnus-image-text-deletable)
1889 (delete-region start end)))
1890 (unless (= end (point-max))
1891 (setq start end
1892 end nil))))))
1893
1894 (defun gnus-kill-all-overlays ()
1895 "Delete all overlays in the current buffer."
1896 (let* ((overlayss (overlay-lists))
1897 (buffer-read-only nil)
1898 (overlays (delq nil (nconc (car overlayss) (cdr overlayss)))))
1899 (while overlays
1900 (delete-overlay (pop overlays)))))
1901
1902 (provide 'gnus-util)
1903
1904 ;;; gnus-util.el ends here