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