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