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