Document reserved keys
[emacs.git] / lisp / gnus / gnus-util.el
blob1c42d7d0ef8115d4eae01399bea8fbe231f32ee9
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 (defun gnus-remove-if (predicate sequence &optional hash-table-p)
1121 "Return a copy of SEQUENCE with all items satisfying PREDICATE removed.
1122 SEQUENCE should be a list, a vector, or a string. Returns always a list.
1123 If HASH-TABLE-P is non-nil, regards SEQUENCE as a hash table."
1124 (let (out)
1125 (if hash-table-p
1126 (mapatoms (lambda (symbol)
1127 (unless (funcall predicate symbol)
1128 (push symbol out)))
1129 sequence)
1130 (unless (listp sequence)
1131 (setq sequence (append sequence nil)))
1132 (while sequence
1133 (unless (funcall predicate (car sequence))
1134 (push (car sequence) out))
1135 (setq sequence (cdr sequence))))
1136 (nreverse out)))
1138 (defun gnus-remove-if-not (predicate sequence &optional hash-table-p)
1139 "Return a copy of SEQUENCE with all items not satisfying PREDICATE removed.
1140 SEQUENCE should be a list, a vector, or a string. Returns always a list.
1141 If HASH-TABLE-P is non-nil, regards SEQUENCE as a hash table."
1142 (let (out)
1143 (if hash-table-p
1144 (mapatoms (lambda (symbol)
1145 (when (funcall predicate symbol)
1146 (push symbol out)))
1147 sequence)
1148 (unless (listp sequence)
1149 (setq sequence (append sequence nil)))
1150 (while sequence
1151 (when (funcall predicate (car sequence))
1152 (push (car sequence) out))
1153 (setq sequence (cdr sequence))))
1154 (nreverse out)))
1156 (defun gnus-grep-in-list (word list)
1157 "Find if a WORD matches any regular expression in the given LIST."
1158 (when (and word list)
1159 (catch 'found
1160 (dolist (r list)
1161 (when (string-match r word)
1162 (throw 'found r))))))
1164 (defmacro gnus-alist-pull (key alist &optional assoc-p)
1165 "Modify ALIST to be without KEY."
1166 (unless (symbolp alist)
1167 (error "Not a symbol: %s" alist))
1168 (let ((fun (if assoc-p 'assoc 'assq)))
1169 `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
1171 (defun gnus-globalify-regexp (re)
1172 "Return a regexp that matches a whole line, if RE matches a part of it."
1173 (concat (unless (string-match "^\\^" re) "^.*")
1175 (unless (string-match "\\$$" re) ".*$")))
1177 (defun gnus-set-window-start (&optional point)
1178 "Set the window start to POINT, or (point) if nil."
1179 (let ((win (gnus-get-buffer-window (current-buffer) t)))
1180 (when win
1181 (set-window-start win (or point (point))))))
1183 (defun gnus-annotation-in-region-p (b e)
1184 (if (= b e)
1185 (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
1186 (text-property-any b e 'gnus-undeletable t)))
1188 (defun gnus-or (&rest elems)
1189 "Return non-nil if any of the elements are non-nil."
1190 (catch 'found
1191 (while elems
1192 (when (pop elems)
1193 (throw 'found t)))))
1195 (defun gnus-and (&rest elems)
1196 "Return non-nil if all of the elements are non-nil."
1197 (catch 'found
1198 (while elems
1199 (unless (pop elems)
1200 (throw 'found nil)))
1203 ;; gnus.el requires mm-util.
1204 (declare-function mm-disable-multibyte "mm-util")
1206 (defun gnus-write-active-file (file hashtb &optional full-names)
1207 ;; `coding-system-for-write' should be `raw-text' or equivalent.
1208 (let ((coding-system-for-write nnmail-active-file-coding-system))
1209 (with-temp-file file
1210 ;; The buffer should be in the unibyte mode because group names
1211 ;; are ASCII text or encoded non-ASCII text (i.e., unibyte).
1212 (mm-disable-multibyte)
1213 (mapatoms
1214 (lambda (sym)
1215 (when (and sym
1216 (boundp sym)
1217 (symbol-value sym))
1218 (insert (format "%S %d %d y\n"
1219 (if full-names
1221 (intern (gnus-group-real-name (symbol-name sym))))
1222 (or (cdr (symbol-value sym))
1223 (car (symbol-value sym)))
1224 (car (symbol-value sym))))))
1225 hashtb)
1226 (goto-char (point-max))
1227 (while (search-backward "\\." nil t)
1228 (delete-char 1)))))
1230 ;; Fixme: Why not use `with-output-to-temp-buffer'?
1231 (defmacro gnus-with-output-to-file (file &rest body)
1232 (let ((buffer (make-symbol "output-buffer"))
1233 (size (make-symbol "output-buffer-size"))
1234 (leng (make-symbol "output-buffer-length"))
1235 (append (make-symbol "output-buffer-append")))
1236 `(let* ((,size 131072)
1237 (,buffer (make-string ,size 0))
1238 (,leng 0)
1239 (,append nil)
1240 (standard-output
1241 (lambda (c)
1242 (aset ,buffer ,leng c)
1244 (if (= ,size (setq ,leng (1+ ,leng)))
1245 (progn (write-region ,buffer nil ,file ,append 'no-msg)
1246 (setq ,leng 0
1247 ,append t))))))
1248 ,@body
1249 (when (> ,leng 0)
1250 (let ((coding-system-for-write 'no-conversion))
1251 (write-region (substring ,buffer 0 ,leng) nil ,file
1252 ,append 'no-msg))))))
1254 (put 'gnus-with-output-to-file 'lisp-indent-function 1)
1255 (put 'gnus-with-output-to-file 'edebug-form-spec '(form body))
1257 (defun gnus-add-text-properties-when
1258 (property value start end properties &optional object)
1259 "Like `add-text-properties', only applied on where PROPERTY is VALUE."
1260 (let (point)
1261 (while (and start
1262 (< start end) ;; XEmacs will loop for every when start=end.
1263 (setq point (text-property-not-all start end property value)))
1264 (add-text-properties start point properties object)
1265 (setq start (text-property-any point end property value)))
1266 (if start
1267 (add-text-properties start end properties object))))
1269 (defun gnus-remove-text-properties-when
1270 (property value start end properties &optional object)
1271 "Like `remove-text-properties', only applied on where PROPERTY is VALUE."
1272 (let (point)
1273 (while (and start
1274 (< start end)
1275 (setq point (text-property-not-all start end property value)))
1276 (remove-text-properties start point properties object)
1277 (setq start (text-property-any point end property value)))
1278 (if start
1279 (remove-text-properties start end properties object))
1282 (defun gnus-string-remove-all-properties (string)
1283 (condition-case ()
1284 (let ((s string))
1285 (set-text-properties 0 (length string) nil string)
1287 (error string)))
1289 ;; This might use `compare-strings' to reduce consing in the
1290 ;; case-insensitive case, but it has to cope with null args.
1291 ;; (`string-equal' uses symbol print names.)
1292 (defun gnus-string-equal (x y)
1293 "Like `string-equal', except it compares case-insensitively."
1294 (and (= (length x) (length y))
1295 (or (string-equal x y)
1296 (string-equal (downcase x) (downcase y)))))
1298 (defcustom gnus-use-byte-compile t
1299 "If non-nil, byte-compile crucial run-time code.
1300 Setting it to nil has no effect after the first time `gnus-byte-compile'
1301 is run."
1302 :type 'boolean
1303 :version "22.1"
1304 :group 'gnus-various)
1306 (defun gnus-byte-compile (form)
1307 "Byte-compile FORM if `gnus-use-byte-compile' is non-nil."
1308 (if gnus-use-byte-compile
1309 (progn
1310 (require 'bytecomp)
1311 (defalias 'gnus-byte-compile
1312 (lambda (form)
1313 (let ((byte-compile-warnings '(unresolved callargs redefine)))
1314 (byte-compile form))))
1315 (gnus-byte-compile form))
1316 form))
1318 (defun gnus-remassoc (key alist)
1319 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
1320 The modified LIST is returned. If the first member
1321 of LIST has a car that is `equal' to KEY, there is no way to remove it
1322 by side effect; therefore, write `(setq foo (gnus-remassoc key foo))' to be
1323 sure of changing the value of `foo'."
1324 (when alist
1325 (if (equal key (caar alist))
1326 (cdr alist)
1327 (setcdr alist (gnus-remassoc key (cdr alist)))
1328 alist)))
1330 (defun gnus-update-alist-soft (key value alist)
1331 (if value
1332 (cons (cons key value) (gnus-remassoc key alist))
1333 (gnus-remassoc key alist)))
1335 (defun gnus-create-info-command (node)
1336 "Create a command that will go to info NODE."
1337 `(lambda ()
1338 (interactive)
1339 ,(concat "Enter the info system at node " node)
1340 (Info-goto-node ,node)
1341 (setq gnus-info-buffer (current-buffer))
1342 (gnus-configure-windows 'info)))
1344 (defun gnus-not-ignore (&rest args)
1347 (defvar gnus-directory-sep-char-regexp "/"
1348 "The regexp of directory separator character.
1349 If you find some problem with the directory separator character, try
1350 \"[/\\\\]\" for some systems.")
1352 (defun gnus-url-unhex (x)
1353 (if (> x ?9)
1354 (if (>= x ?a)
1355 (+ 10 (- x ?a))
1356 (+ 10 (- x ?A)))
1357 (- x ?0)))
1359 ;; Fixme: Do it like QP.
1360 (defun gnus-url-unhex-string (str &optional allow-newlines)
1361 "Remove %XX, embedded spaces, etc in a url.
1362 If optional second argument ALLOW-NEWLINES is non-nil, then allow the
1363 decoding of carriage returns and line feeds in the string, which is normally
1364 forbidden in URL encoding."
1365 (let ((tmp "")
1366 (case-fold-search t))
1367 (while (string-match "%[0-9a-f][0-9a-f]" str)
1368 (let* ((start (match-beginning 0))
1369 (ch1 (gnus-url-unhex (elt str (+ start 1))))
1370 (code (+ (* 16 ch1)
1371 (gnus-url-unhex (elt str (+ start 2))))))
1372 (setq tmp (concat
1373 tmp (substring str 0 start)
1374 (cond
1375 (allow-newlines
1376 (char-to-string code))
1377 ((or (= code ?\n) (= code ?\r))
1378 " ")
1379 (t (char-to-string code))))
1380 str (substring str (match-end 0)))))
1381 (setq tmp (concat tmp str))
1382 tmp))
1384 (defun gnus-make-predicate (spec)
1385 "Transform SPEC into a function that can be called.
1386 SPEC is a predicate specifier that contains stuff like `or', `and',
1387 `not', lists and functions. The functions all take one parameter."
1388 `(lambda (elem) ,(gnus-make-predicate-1 spec)))
1390 (defun gnus-make-predicate-1 (spec)
1391 (cond
1392 ((symbolp spec)
1393 `(,spec elem))
1394 ((listp spec)
1395 (if (memq (car spec) '(or and not))
1396 `(,(car spec) ,@(mapcar 'gnus-make-predicate-1 (cdr spec)))
1397 (error "Invalid predicate specifier: %s" spec)))))
1399 (defun gnus-completing-read (prompt collection &optional require-match
1400 initial-input history def)
1401 "Call `gnus-completing-read-function'."
1402 (funcall gnus-completing-read-function
1403 (concat prompt (when def
1404 (concat " (default " def ")"))
1405 ": ")
1406 collection require-match initial-input history def))
1408 (defun gnus-emacs-completing-read (prompt collection &optional require-match
1409 initial-input history def)
1410 "Call standard `completing-read-function'."
1411 (let ((completion-styles gnus-completion-styles))
1412 (completing-read prompt collection
1413 nil require-match initial-input history def)))
1415 (autoload 'ido-completing-read "ido")
1416 (defun gnus-ido-completing-read (prompt collection &optional require-match
1417 initial-input history def)
1418 "Call `ido-completing-read-function'."
1419 (ido-completing-read prompt collection nil require-match
1420 initial-input history def))
1423 (declare-function iswitchb-read-buffer "iswitchb"
1424 (prompt &optional default require-match
1425 _predicate start matches-set))
1426 (defvar iswitchb-temp-buflist)
1427 (defvar iswitchb-mode)
1429 (defun gnus-iswitchb-completing-read (prompt collection &optional require-match
1430 initial-input history def)
1431 "`iswitchb' based completing-read function."
1432 ;; Make sure iswitchb is loaded before we let-bind its variables.
1433 ;; If it is loaded inside the let, variables can become unbound afterwards.
1434 (require 'iswitchb)
1435 (let ((iswitchb-make-buflist-hook
1436 (lambda ()
1437 (setq iswitchb-temp-buflist
1438 (let ((choices (append
1439 (when initial-input (list initial-input))
1440 (symbol-value history) collection))
1441 filtered-choices)
1442 (dolist (x choices)
1443 (setq filtered-choices (adjoin x filtered-choices)))
1444 (nreverse filtered-choices))))))
1445 (unwind-protect
1446 (progn
1447 (or iswitchb-mode
1448 (add-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup))
1449 (iswitchb-read-buffer prompt def require-match))
1450 (or iswitchb-mode
1451 (remove-hook 'minibuffer-setup-hook 'iswitchb-minibuffer-setup)))))
1453 (put 'gnus-parse-without-error 'lisp-indent-function 0)
1454 (put 'gnus-parse-without-error 'edebug-form-spec '(body))
1456 (defmacro gnus-parse-without-error (&rest body)
1457 "Allow continuing onto the next line even if an error occurs."
1458 `(while (not (eobp))
1459 (condition-case ()
1460 (progn
1461 ,@body
1462 (goto-char (point-max)))
1463 (error
1464 (gnus-error 4 "Invalid data on line %d"
1465 (count-lines (point-min) (point)))
1466 (forward-line 1)))))
1468 (defun gnus-cache-file-contents (file variable function)
1469 "Cache the contents of FILE in VARIABLE. The contents come from FUNCTION."
1470 (let ((time (nth 5 (file-attributes file)))
1471 contents value)
1472 (if (or (null (setq value (symbol-value variable)))
1473 (not (equal (car value) file))
1474 (not (equal (nth 1 value) time)))
1475 (progn
1476 (setq contents (funcall function file))
1477 (set variable (list file time contents))
1478 contents)
1479 (nth 2 value))))
1481 (defun gnus-multiple-choice (prompt choice &optional idx)
1482 "Ask user a multiple choice question.
1483 CHOICE is a list of the choice char and help message at IDX."
1484 (let (tchar buf)
1485 (save-window-excursion
1486 (save-excursion
1487 (while (not tchar)
1488 (message "%s (%s): "
1489 prompt
1490 (concat
1491 (mapconcat (lambda (s) (char-to-string (car s)))
1492 choice ", ") ", ?"))
1493 (setq tchar (read-char))
1494 (when (not (assq tchar choice))
1495 (setq tchar nil)
1496 (setq buf (get-buffer-create "*Gnus Help*"))
1497 (pop-to-buffer buf)
1498 (fundamental-mode)
1499 (buffer-disable-undo)
1500 (erase-buffer)
1501 (insert prompt ":\n\n")
1502 (let ((max -1)
1503 (list choice)
1504 (alist choice)
1505 (idx (or idx 1))
1506 (i 0)
1507 n width pad format)
1508 ;; find the longest string to display
1509 (while list
1510 (setq n (length (nth idx (car list))))
1511 (unless (> max n)
1512 (setq max n))
1513 (setq list (cdr list)))
1514 (setq max (+ max 4)) ; %c, `:', SPACE, a SPACE at end
1515 (setq n (/ (1- (window-width)) max)) ; items per line
1516 (setq width (/ (1- (window-width)) n)) ; width of each item
1517 ;; insert `n' items, each in a field of width `width'
1518 (while alist
1519 (if (< i n)
1521 (setq i 0)
1522 (delete-char -1) ; the `\n' takes a char
1523 (insert "\n"))
1524 (setq pad (- width 3))
1525 (setq format (concat "%c: %-" (int-to-string pad) "s"))
1526 (insert (format format (caar alist) (nth idx (car alist))))
1527 (setq alist (cdr alist))
1528 (setq i (1+ i))))))))
1529 (if (buffer-live-p buf)
1530 (kill-buffer buf))
1531 tchar))
1533 (defun gnus-frame-or-window-display-name (object)
1534 "Given a frame or window, return the associated display name.
1535 Return nil otherwise."
1536 (if (or (framep object)
1537 (and (windowp object)
1538 (setq object (window-frame object))))
1539 (let ((display (frame-parameter object 'display)))
1540 (if (and (stringp display)
1541 ;; Exclude invalid display names.
1542 (string-match "\\`[^:]*:[0-9]+\\(\\.[0-9]+\\)?\\'"
1543 display))
1544 display))))
1546 (defvar tool-bar-mode)
1548 (defun gnus-tool-bar-update (&rest ignore)
1549 "Update the tool bar."
1550 (when (and (boundp 'tool-bar-mode)
1551 tool-bar-mode)
1552 (let* ((args nil)
1553 (func (cond ((fboundp 'tool-bar-update)
1554 'tool-bar-update)
1555 ((fboundp 'force-window-update)
1556 'force-window-update)
1557 ((fboundp 'redraw-frame)
1558 (setq args (list (selected-frame)))
1559 'redraw-frame)
1560 (t 'ignore))))
1561 (apply func args))))
1563 ;; Fixme: This has only one use (in gnus-agent), which isn't worthwhile.
1564 (defmacro gnus-mapcar (function seq1 &rest seqs2_n)
1565 "Apply FUNCTION to each element of the sequences, and make a list of the results.
1566 If there are several sequences, FUNCTION is called with that many arguments,
1567 and mapping stops as soon as the shortest sequence runs out. With just one
1568 sequence, this is like `mapcar'. With several, it is like the Common Lisp
1569 `mapcar' function extended to arbitrary sequence types."
1571 (if seqs2_n
1572 (let* ((seqs (cons seq1 seqs2_n))
1573 (cnt 0)
1574 (heads (mapcar (lambda (seq)
1575 (make-symbol (concat "head"
1576 (int-to-string
1577 (setq cnt (1+ cnt))))))
1578 seqs))
1579 (result (make-symbol "result"))
1580 (result-tail (make-symbol "result-tail")))
1581 `(let* ,(let* ((bindings (cons nil nil))
1582 (heads heads))
1583 (nconc bindings (list (list result '(cons nil nil))))
1584 (nconc bindings (list (list result-tail result)))
1585 (while heads
1586 (nconc bindings (list (list (pop heads) (pop seqs)))))
1587 (cdr bindings))
1588 (while (and ,@heads)
1589 (setcdr ,result-tail (cons (funcall ,function
1590 ,@(mapcar (lambda (h) (list 'car h))
1591 heads))
1592 nil))
1593 (setq ,result-tail (cdr ,result-tail)
1594 ,@(mapcan (lambda (h) (list h (list 'cdr h))) heads)))
1595 (cdr ,result)))
1596 `(mapcar ,function ,seq1)))
1598 (defun gnus-emacs-version ()
1599 "Stringified Emacs version."
1600 (let* ((lst (if (listp gnus-user-agent)
1601 gnus-user-agent
1602 '(gnus emacs type)))
1603 (system-v (cond ((memq 'config lst)
1604 system-configuration)
1605 ((memq 'type lst)
1606 (symbol-name system-type))
1607 (t nil)))
1608 codename)
1609 (cond
1610 ((not (memq 'emacs lst))
1611 nil)
1612 ((string-match "^\\(\\([.0-9]+\\)*\\)\\.[0-9]+$" emacs-version)
1613 (concat "Emacs/" emacs-version
1614 (if system-v
1615 (concat " (" system-v ")")
1616 "")))
1617 (t emacs-version))))
1619 (defun gnus-rename-file (old-path new-path &optional trim)
1620 "Rename OLD-PATH as NEW-PATH. If TRIM, recursively delete
1621 empty directories from OLD-PATH."
1622 (when (file-exists-p old-path)
1623 (let* ((old-dir (file-name-directory old-path))
1624 (old-name (file-name-nondirectory old-path))
1625 (new-dir (file-name-directory new-path))
1626 (new-name (file-name-nondirectory new-path))
1627 temp)
1628 (gnus-make-directory new-dir)
1629 (rename-file old-path new-path t)
1630 (when trim
1631 (while (progn (setq temp (directory-files old-dir))
1632 (while (member (car temp) '("." ".."))
1633 (setq temp (cdr temp)))
1634 (= (length temp) 0))
1635 (delete-directory old-dir)
1636 (setq old-dir (file-name-as-directory
1637 (file-truename
1638 (concat old-dir "..")))))))))
1640 (defun gnus-set-file-modes (filename mode)
1641 "Wrapper for set-file-modes."
1642 (ignore-errors
1643 (set-file-modes filename mode)))
1645 (declare-function image-size "image.c" (spec &optional pixels frame))
1647 (defun gnus-rescale-image (image size)
1648 "Rescale IMAGE to SIZE if possible.
1649 SIZE is in format (WIDTH . HEIGHT). Return a new image.
1650 Sizes are in pixels."
1651 (if (or (not (fboundp 'imagemagick-types))
1652 (not (get-buffer-window (current-buffer))))
1653 image
1654 (let ((new-width (car size))
1655 (new-height (cdr size)))
1656 (when (> (cdr (image-size image t)) new-height)
1657 (setq image (or (create-image (plist-get (cdr image) :data) 'imagemagick t
1658 :height new-height)
1659 image)))
1660 (when (> (car (image-size image t)) new-width)
1661 (setq image (or
1662 (create-image (plist-get (cdr image) :data) 'imagemagick t
1663 :width new-width)
1664 image)))
1665 image)))
1667 (defun gnus-recursive-directory-files (dir)
1668 "Return all regular files below DIR.
1669 The first found will be returned if a file has hard or symbolic links."
1670 (let (files attr attrs)
1671 (cl-labels
1672 ((fn (directory)
1673 (dolist (file (directory-files directory t))
1674 (setq attr (file-attributes (file-truename file)))
1675 (when (and (not (member attr attrs))
1676 (not (member (file-name-nondirectory file)
1677 '("." "..")))
1678 (file-readable-p file))
1679 (push attr attrs)
1680 (cond ((file-regular-p file)
1681 (push file files))
1682 ((file-directory-p file)
1683 (fn file)))))))
1684 (fn dir))
1685 files))
1687 (defun gnus-list-memq-of-list (elements list)
1688 "Return non-nil if any of the members of ELEMENTS are in LIST."
1689 (let ((found nil))
1690 (dolist (elem elements)
1691 (setq found (or found
1692 (memq elem list))))
1693 found))
1695 (defun gnus-test-list (list predicate)
1696 "To each element of LIST apply PREDICATE.
1697 Return nil if LIST is no list or is empty or some test returns nil;
1698 otherwise, return t."
1699 (when (and list (listp list))
1700 (let ((result (mapcar predicate list)))
1701 (not (memq nil result)))))
1703 (defun gnus-subsetp (list1 list2)
1704 "Return t if LIST1 is a subset of LIST2.
1705 Similar to `subsetp' but use member for element test so that this works for
1706 lists of strings."
1707 (when (and (listp list1) (listp list2))
1708 (if list1
1709 (and (member (car list1) list2)
1710 (gnus-subsetp (cdr list1) list2))
1711 t)))
1713 (defun gnus-setdiff (list1 list2)
1714 "Return member-based set difference of LIST1 and LIST2."
1715 (when (and list1 (listp list1) (listp list2))
1716 (if (member (car list1) list2)
1717 (gnus-setdiff (cdr list1) list2)
1718 (cons (car list1) (gnus-setdiff (cdr list1) list2)))))
1720 ;;; Image functions.
1722 (defun gnus-image-type-available-p (type)
1723 (and (display-images-p)
1724 (image-type-available-p type)))
1726 (defun gnus-create-image (file &optional type data-p &rest props)
1727 (let ((face (plist-get props :face)))
1728 (when face
1729 (setq props (plist-put props :foreground (face-foreground face)))
1730 (setq props (plist-put props :background (face-background face))))
1731 (ignore-errors
1732 (apply 'create-image file type data-p props))))
1734 (defun gnus-put-image (glyph &optional string category)
1735 (let ((point (point)))
1736 (insert-image glyph (or string " "))
1737 (put-text-property point (point) 'gnus-image-category category)
1738 (unless string
1739 (put-text-property (1- (point)) (point)
1740 'gnus-image-text-deletable t))
1741 glyph))
1743 (defun gnus-remove-image (image &optional category)
1744 "Remove the image matching IMAGE and CATEGORY found first."
1745 (let ((start (point-min))
1746 val end)
1747 (while (and (not end)
1748 (or (setq val (get-text-property start 'display))
1749 (and (setq start
1750 (next-single-property-change start 'display))
1751 (setq val (get-text-property start 'display)))))
1752 (setq end (or (next-single-property-change start 'display)
1753 (point-max)))
1754 (if (and (equal val image)
1755 (equal (get-text-property start 'gnus-image-category)
1756 category))
1757 (progn
1758 (put-text-property start end 'display nil)
1759 (when (get-text-property start 'gnus-image-text-deletable)
1760 (delete-region start end)))
1761 (unless (= end (point-max))
1762 (setq start end
1763 end nil))))))
1765 (defun gnus-kill-all-overlays ()
1766 "Delete all overlays in the current buffer."
1767 (let* ((overlayss (overlay-lists))
1768 (buffer-read-only nil)
1769 (overlays (delq nil (nconc (car overlayss) (cdr overlayss)))))
1770 (while overlays
1771 (delete-overlay (pop overlays)))))
1773 (provide 'gnus-util)
1775 ;;; gnus-util.el ends here