(gnus-ems-redefine): Call it.
[elisp/gnus.git-] / lisp / gnus-util.el
1 ;;; gnus-util.el --- utility functions for Semi-gnus
2 ;; Copyright (C) 1996,97,98,99 Free Software Foundation, Inc.
3
4 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
5 ;;      Tatsuya Ichikawa <t-ichi@po.shiojiri.ne.jp>
6 ;; Keywords: mail, news, MIME
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 2, or (at your option)
13 ;; 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; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Nothing in this file depends on any other parts of Gnus -- all
28 ;; functions and macros in this file are utility functions that are
29 ;; used by Gnus and may be used by any other package without loading
30 ;; Gnus first.
31
32 ;;; Code:
33
34 (eval-when-compile (require 'cl))
35 (eval-when-compile (require 'static))
36 (require 'custom)
37 (require 'nnheader)
38 (require 'message)
39 (require 'time-date)
40
41 (eval-and-compile
42   (autoload 'rmail-insert-rmail-file-header "rmail")
43   (autoload 'rmail-count-new-messages "rmail")
44   (autoload 'rmail-show-message "rmail"))
45
46 (defun gnus-boundp (variable)
47   "Return non-nil if VARIABLE is bound and non-nil."
48   (and (boundp variable)
49        (symbol-value variable)))
50
51 (defmacro gnus-eval-in-buffer-window (buffer &rest forms)
52   "Pop to BUFFER, evaluate FORMS, and then return to the original window."
53   (let ((tempvar (make-symbol "GnusStartBufferWindow"))
54         (w (make-symbol "w"))
55         (buf (make-symbol "buf"))
56         (frame (make-symbol "frame")))
57     `(let* ((,tempvar (selected-window))
58             (,buf ,buffer)
59             (,w (get-buffer-window ,buf 'visible))
60             ,frame)
61        (unwind-protect
62            (progn
63              (if ,w
64                  (progn
65                    (select-window ,w)
66                    (set-buffer (window-buffer ,w)))
67                (pop-to-buffer ,buf))
68              ,@forms)
69          (setq ,frame (selected-frame))
70          (select-window ,tempvar)
71          (select-frame ,frame)))))
72
73 (put 'gnus-eval-in-buffer-window 'lisp-indent-function 1)
74 (put 'gnus-eval-in-buffer-window 'edebug-form-spec '(form body))
75
76 (defmacro gnus-intern-safe (string hashtable)
77   "Set hash value.  Arguments are STRING, VALUE, and HASHTABLE."
78   `(let ((symbol (intern ,string ,hashtable)))
79      (or (boundp symbol)
80          (set symbol nil))
81      symbol))
82
83 ;; Avoid byte-compile warning.
84 ;; In Mule, this function will be redefined to `truncate-string',
85 ;; which takes 3 or 4 args.
86 (defun gnus-truncate-string (str width &rest ignore)
87   (substring str 0 width))
88
89 ;; Added by Geoffrey T. Dairiki <dairiki@u.washington.edu>.  A safe way
90 ;; to limit the length of a string.  This function is necessary since
91 ;; `(substr "abc" 0 30)' pukes with "Args out of range".
92 (defsubst gnus-limit-string (str width)
93   (if (> (length str) width)
94       (substring str 0 width)
95     str))
96
97 (defsubst gnus-functionp (form)
98   "Return non-nil if FORM is funcallable."
99   (or (and (symbolp form) (fboundp form))
100       (and (listp form) (eq (car form) 'lambda))
101       (byte-code-function-p form)))
102
103 (defsubst gnus-goto-char (point)
104   (and point (goto-char point)))
105
106 (defmacro gnus-buffer-exists-p (buffer)
107   `(let ((buffer ,buffer))
108      (when buffer
109        (funcall (if (stringp buffer) 'get-buffer 'buffer-name)
110                 buffer))))
111
112 (defmacro gnus-kill-buffer (buffer)
113   `(let ((buf ,buffer))
114      (when (gnus-buffer-exists-p buf)
115        (kill-buffer buf))))
116
117 (static-cond
118  ((fboundp 'point-at-bol)
119   (fset 'gnus-point-at-bol 'point-at-bol))
120  ((fboundp 'line-beginning-position)
121   (fset 'gnus-point-at-bol 'line-beginning-position))
122  (t
123   (defun gnus-point-at-bol ()
124     "Return point at the beginning of the line."
125     (let ((p (point)))
126       (beginning-of-line)
127       (prog1
128           (point)
129         (goto-char p))))
130   ))
131 (static-cond
132  ((fboundp 'point-at-eol)
133   (fset 'gnus-point-at-eol 'point-at-eol))
134  ((fboundp 'line-end-position)
135   (fset 'gnus-point-at-eol 'line-end-position))
136  (t
137   (defun gnus-point-at-eol ()
138     "Return point at the end of the line."
139     (let ((p (point)))
140       (end-of-line)
141       (prog1
142           (point)
143         (goto-char p))))
144   ))
145
146 (defun gnus-delete-first (elt list)
147   "Delete by side effect the first occurrence of ELT as a member of LIST."
148   (if (equal (car list) elt)
149       (cdr list)
150     (let ((total list))
151       (while (and (cdr list)
152                   (not (equal (cadr list) elt)))
153         (setq list (cdr list)))
154       (when (cdr list)
155         (setcdr list (cddr list)))
156       total)))
157
158 ;; Delete the current line (and the next N lines).
159 (defmacro gnus-delete-line (&optional n)
160   `(delete-region (progn (beginning-of-line) (point))
161                   (progn (forward-line ,(or n 1)) (point))))
162
163 (defun gnus-byte-code (func)
164   "Return a form that can be `eval'ed based on FUNC."
165   (let ((fval (indirect-function func)))
166     (if (byte-code-function-p fval)
167         (let ((flist (append fval nil)))
168           (setcar flist 'byte-code)
169           flist)
170       (cons 'progn (cddr fval)))))
171
172 (defun gnus-extract-address-components (from)
173   (let (name address)
174     ;; First find the address - the thing with the @ in it.  This may
175     ;; not be accurate in mail addresses, but does the trick most of
176     ;; the time in news messages.
177     (when (string-match "\\b[^@ \t<>]+[!@][^@ \t<>]+\\b" from)
178       (setq address (substring from (match-beginning 0) (match-end 0))))
179     ;; Then we check whether the "name <address>" format is used.
180     (and address
181          ;; Linear white space is not required.
182          (string-match (concat "[ \t]*<" (regexp-quote address) ">") from)
183          (and (setq name (substring from 0 (match-beginning 0)))
184               ;; Strip any quotes from the name.
185               (string-match "\".*\"" name)
186               (setq name (substring name 1 (1- (match-end 0))))))
187     ;; If not, then "address (name)" is used.
188     (or name
189         (and (string-match "(.+)" from)
190              (setq name (substring from (1+ (match-beginning 0))
191                                    (1- (match-end 0)))))
192         (and (string-match "()" from)
193              (setq name address))
194         ;; XOVER might not support folded From headers.
195         (and (string-match "(.*" from)
196              (setq name (substring from (1+ (match-beginning 0))
197                                    (match-end 0)))))
198     ;; Fix by Hallvard B Furuseth <h.b.furuseth@usit.uio.no>.
199     (list (or name from) (or address from))))
200
201 (defun gnus-fetch-field (field)
202   "Return the value of the header FIELD of current article."
203   (save-excursion
204     (save-restriction
205       (let ((case-fold-search t)
206             (inhibit-point-motion-hooks t))
207         (nnheader-narrow-to-headers)
208         (message-fetch-field field)))))
209
210 (defun gnus-goto-colon ()
211   (beginning-of-line)
212   (search-forward ":" (gnus-point-at-eol) t))
213
214 (defun gnus-remove-text-with-property (prop)
215   "Delete all text in the current buffer with text property PROP."
216   (save-excursion
217     (goto-char (point-min))
218     (while (not (eobp))
219       (while (get-text-property (point) prop)
220         (delete-char 1))
221       (goto-char (next-single-property-change (point) prop nil (point-max))))))
222
223 (defun gnus-newsgroup-directory-form (newsgroup)
224   "Make hierarchical directory name from NEWSGROUP name."
225   (let ((newsgroup (gnus-newsgroup-savable-name newsgroup))
226         (len (length newsgroup))
227         idx)
228     ;; If this is a foreign group, we don't want to translate the
229     ;; entire name.
230     (if (setq idx (string-match ":" newsgroup))
231         (aset newsgroup idx ?/)
232       (setq idx 0))
233     ;; Replace all occurrences of `.' with `/'.
234     (while (< idx len)
235       (when (= (aref newsgroup idx) ?.)
236         (aset newsgroup idx ?/))
237       (setq idx (1+ idx)))
238     newsgroup))
239
240 (defun gnus-newsgroup-savable-name (group)
241   ;; Replace any slashes in a group name (eg. an ange-ftp nndoc group)
242   ;; with dots.
243   (nnheader-replace-chars-in-string group ?/ ?.))
244
245 (defun gnus-string> (s1 s2)
246   (not (or (string< s1 s2)
247            (string= s1 s2))))
248
249 ;;; Time functions.
250
251 (defun gnus-file-newer-than (file date)
252   (let ((fdate (nth 5 (file-attributes file))))
253     (or (> (car fdate) (car date))
254         (and (= (car fdate) (car date))
255              (> (nth 1 fdate) (nth 1 date))))))
256
257 ;;; Keymap macros.
258
259 (defmacro gnus-local-set-keys (&rest plist)
260   "Set the keys in PLIST in the current keymap."
261   `(gnus-define-keys-1 (current-local-map) ',plist))
262
263 (defmacro gnus-define-keys (keymap &rest plist)
264   "Define all keys in PLIST in KEYMAP."
265   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist)))
266
267 (defmacro gnus-define-keys-safe (keymap &rest plist)
268   "Define all keys in PLIST in KEYMAP without overwriting previous definitions."
269   `(gnus-define-keys-1 (quote ,keymap) (quote ,plist) t))
270
271 (put 'gnus-define-keys 'lisp-indent-function 1)
272 (put 'gnus-define-keys-safe 'lisp-indent-function 1)
273 (put 'gnus-local-set-keys 'lisp-indent-function 1)
274
275 (defmacro gnus-define-keymap (keymap &rest plist)
276   "Define all keys in PLIST in KEYMAP."
277   `(gnus-define-keys-1 ,keymap (quote ,plist)))
278
279 (put 'gnus-define-keymap 'lisp-indent-function 1)
280
281 (defun gnus-define-keys-1 (keymap plist &optional safe)
282   (when (null keymap)
283     (error "Can't set keys in a null keymap"))
284   (cond ((symbolp keymap)
285          (setq keymap (symbol-value keymap)))
286         ((keymapp keymap))
287         ((listp keymap)
288          (set (car keymap) nil)
289          (define-prefix-command (car keymap))
290          (define-key (symbol-value (caddr keymap)) (cadr keymap) (car keymap))
291          (setq keymap (symbol-value (car keymap)))))
292   (let (key)
293     (while plist
294       (when (symbolp (setq key (pop plist)))
295         (setq key (symbol-value key)))
296       (if (or (not safe)
297               (eq (lookup-key keymap key) 'undefined))
298           (define-key keymap key (pop plist))
299         (pop plist)))))
300
301 (defun gnus-completing-read (default prompt &rest args)
302   ;; Like `completing-read', except that DEFAULT is the default argument.
303   (let* ((prompt (if default
304                      (concat prompt " (default " default ") ")
305                    (concat prompt " ")))
306          (answer (apply 'completing-read prompt args)))
307     (if (or (null answer) (zerop (length answer)))
308         default
309       answer)))
310
311 ;; Two silly functions to ensure that all `y-or-n-p' questions clear
312 ;; the echo area.
313 (defun gnus-y-or-n-p (prompt)
314   (prog1
315       (y-or-n-p prompt)
316     (message "")))
317
318 (defun gnus-yes-or-no-p (prompt)
319   (prog1
320       (yes-or-no-p prompt)
321     (message "")))
322
323 (defun gnus-dd-mmm (messy-date)
324   "Return a string like DD-MMM from a big messy string."
325   (condition-case ()
326       (format-time-string "%d-%b" (safe-date-to-time messy-date))
327     (error "  -   ")))
328
329 (defmacro gnus-date-get-time (date)
330   "Convert DATE string to Emacs time.
331 Cache the result as a text property stored in DATE."
332   ;; Either return the cached value...
333   `(let ((d ,date))
334      (if (equal "" d)
335          '(0 0)
336        (or (get-text-property 0 'gnus-time d)
337            ;; or compute the value...
338            (let ((time (safe-date-to-time d)))
339              ;; and store it back in the string.
340              (put-text-property 0 1 'gnus-time time d)
341              time)))))
342
343 (defsubst gnus-time-iso8601 (time)
344   "Return a string of TIME in YYMMDDTHHMMSS format."
345   (format-time-string "%Y%m%dT%H%M%S" time))
346
347 (defun gnus-date-iso8601 (date)
348   "Convert the DATE to YYMMDDTHHMMSS."
349   (condition-case ()
350       (gnus-time-iso8601 (gnus-date-get-time date))
351     (error "")))
352
353 (defun gnus-mode-string-quote (string)
354   "Quote all \"%\"'s in STRING."
355   (save-excursion
356     (gnus-set-work-buffer)
357     (insert string)
358     (goto-char (point-min))
359     (while (search-forward "%" nil t)
360       (insert "%"))
361     (buffer-string)))
362
363 ;; Make a hash table (default and minimum size is 256).
364 ;; Optional argument HASHSIZE specifies the table size.
365 (defun gnus-make-hashtable (&optional hashsize)
366   (make-vector (if hashsize (max (gnus-create-hash-size hashsize) 256) 256) 0))
367
368 ;; Make a number that is suitable for hashing; bigger than MIN and
369 ;; equal to some 2^x.  Many machines (such as sparcs) do not have a
370 ;; hardware modulo operation, so they implement it in software.  On
371 ;; many sparcs over 50% of the time to intern is spent in the modulo.
372 ;; Yes, it's slower than actually computing the hash from the string!
373 ;; So we use powers of 2 so people can optimize the modulo to a mask.
374 (defun gnus-create-hash-size (min)
375   (let ((i 1))
376     (while (< i min)
377       (setq i (* 2 i)))
378     i))
379
380 (defcustom gnus-verbose 7
381   "*Integer that says how verbose Gnus should be.
382 The higher the number, the more messages Gnus will flash to say what
383 it's doing.  At zero, Gnus will be totally mute; at five, Gnus will
384 display most important messages; and at ten, Gnus will keep on
385 jabbering all the time."
386   :group 'gnus-start
387   :type 'integer)
388
389 ;; Show message if message has a lower level than `gnus-verbose'.
390 ;; Guideline for numbers:
391 ;; 1 - error messages, 3 - non-serious error messages, 5 - messages
392 ;; for things that take a long time, 7 - not very important messages
393 ;; on stuff, 9 - messages inside loops.
394 (defun gnus-message (level &rest args)
395   (if (<= level gnus-verbose)
396       (apply 'message args)
397     ;; We have to do this format thingy here even if the result isn't
398     ;; shown - the return value has to be the same as the return value
399     ;; from `message'.
400     (apply 'format args)))
401
402 (defun gnus-error (level &rest args)
403   "Beep an error if LEVEL is equal to or less than `gnus-verbose'."
404   (when (<= (floor level) gnus-verbose)
405     (apply 'message args)
406     (ding)
407     (let (duration)
408       (when (and (floatp level)
409                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
410         (sit-for duration))))
411   nil)
412
413 (defun gnus-split-references (references)
414   "Return a list of Message-IDs in REFERENCES."
415   (let ((beg 0)
416         ids)
417     (while (string-match "<[^>]+>" references beg)
418       (push (substring references (match-beginning 0) (setq beg (match-end 0)))
419             ids))
420     (nreverse ids)))
421
422 (defsubst gnus-parent-id (references &optional n)
423   "Return the last Message-ID in REFERENCES.
424 If N, return the Nth ancestor instead."
425   (when references
426     (let ((ids (inline (gnus-split-references references))))
427       (while (nthcdr (or n 1) ids)
428         (setq ids (cdr ids)))
429       (car ids))))
430
431 (defsubst gnus-buffer-live-p (buffer)
432   "Say whether BUFFER is alive or not."
433   (and buffer
434        (get-buffer buffer)
435        (buffer-name (get-buffer buffer))))
436
437 (defun gnus-horizontal-recenter ()
438   "Recenter the current buffer horizontally."
439   (if (< (current-column) (/ (window-width) 2))
440       (set-window-hscroll (get-buffer-window (current-buffer) t) 0)
441     (let* ((orig (point))
442            (end (window-end (get-buffer-window (current-buffer) t)))
443            (max 0))
444       (when end
445         ;; Find the longest line currently displayed in the window.
446         (goto-char (window-start))
447         (while (and (not (eobp))
448                     (< (point) end))
449           (end-of-line)
450           (setq max (max max (current-column)))
451           (forward-line 1))
452         (goto-char orig)
453         ;; Scroll horizontally to center (sort of) the point.
454         (if (> max (window-width))
455             (set-window-hscroll
456              (get-buffer-window (current-buffer) t)
457              (min (- (current-column) (/ (window-width) 3))
458                   (+ 2 (- max (window-width)))))
459           (set-window-hscroll (get-buffer-window (current-buffer) t) 0))
460         max))))
461
462 (defun gnus-read-event-char ()
463   "Get the next event."
464   (let ((event (read-event)))
465     ;; should be gnus-characterp, but this can't be called in XEmacs anyway
466     (cons (and (numberp event) event) event)))
467
468 (defun gnus-sortable-date (date)
469   "Make string suitable for sorting from DATE."
470   (gnus-time-iso8601 (date-to-time date)))
471
472 (defun gnus-copy-file (file &optional to)
473   "Copy FILE to TO."
474   (interactive
475    (list (read-file-name "Copy file: " default-directory)
476          (read-file-name "Copy file to: " default-directory)))
477   (unless to
478     (setq to (read-file-name "Copy file to: " default-directory)))
479   (when (file-directory-p to)
480     (setq to (concat (file-name-as-directory to)
481                      (file-name-nondirectory file))))
482   (copy-file file to))
483
484 (defun gnus-kill-all-overlays ()
485   "Delete all overlays in the current buffer."
486   (let* ((overlayss (overlay-lists))
487          (buffer-read-only nil)
488          (overlays (delq nil (nconc (car overlayss) (cdr overlayss)))))
489     (while overlays
490       (delete-overlay (pop overlays)))))
491
492 (defvar gnus-work-buffer " *gnus work*")
493
494 (defun gnus-set-work-buffer ()
495   "Put point in the empty Gnus work buffer."
496   (if (get-buffer gnus-work-buffer)
497       (progn
498         (set-buffer gnus-work-buffer)
499         (erase-buffer))
500     (set-buffer (gnus-get-buffer-create gnus-work-buffer))
501     (kill-all-local-variables)))
502
503 (defmacro gnus-group-real-name (group)
504   "Find the real name of a foreign newsgroup."
505   `(let ((gname ,group))
506      (if (string-match "^[^:]+:" gname)
507          (substring gname (match-end 0))
508        gname)))
509
510 (defun gnus-make-sort-function (funs)
511   "Return a composite sort condition based on the functions in FUNC."
512   (cond
513    ;; Just a simple function.
514    ((gnus-functionp funs) funs)
515    ;; No functions at all.
516    ((null funs) funs)
517    ;; A list of functions.
518    ((or (cdr funs)
519         (listp (car funs)))
520     `(lambda (t1 t2)
521        ,(gnus-make-sort-function-1 (reverse funs))))
522    ;; A list containing just one function.
523    (t
524     (car funs))))
525
526 (defun gnus-make-sort-function-1 (funs)
527   "Return a composite sort condition based on the functions in FUNC."
528   (let ((function (car funs))
529         (first 't1)
530         (last 't2))
531     (when (consp function)
532       (cond
533        ;; Reversed spec.
534        ((eq (car function) 'not)
535         (setq function (cadr function)
536               first 't2
537               last 't1))
538        ((gnus-functionp function)
539         )
540        (t
541         (error "Invalid sort spec: %s" function))))
542     (if (cdr funs)
543         `(or (,function ,first ,last)
544              (and (not (,function ,last ,first))
545                   ,(gnus-make-sort-function-1 (cdr funs))))
546       `(,function ,first ,last))))
547
548 (defun gnus-turn-off-edit-menu (type)
549   "Turn off edit menu in `gnus-TYPE-mode-map'."
550   (define-key (symbol-value (intern (format "gnus-%s-mode-map" type)))
551     [menu-bar edit] 'undefined))
552
553 (defun gnus-prin1 (form)
554   "Use `prin1' on FORM in the current buffer.
555 Bind `print-quoted' and `print-readably' to t while printing."
556   (let ((print-quoted t)
557         (print-readably t)
558         (print-escape-multibyte nil)
559         print-level print-length)
560     (prin1 form (current-buffer))))
561
562 (defun gnus-prin1-to-string (form)
563   "The same as `prin1', but bind `print-quoted' and `print-readably' to t."
564   (let ((print-quoted t)
565         (print-readably t))
566     (prin1-to-string form)))
567
568 (defun gnus-make-directory (directory)
569   "Make DIRECTORY (and all its parents) if it doesn't exist."
570   (when (and directory
571              (not (file-exists-p directory)))
572     (make-directory directory t))
573   t)
574
575 (defun gnus-write-buffer (file)
576   "Write the current buffer's contents to FILE."
577   ;; Make sure the directory exists.
578   (gnus-make-directory (file-name-directory file))
579   ;; Write the buffer.
580   (write-region (point-min) (point-max) file nil 'quietly))
581
582 (defun gnus-write-buffer-as-binary (file)
583   "Write the current buffer's contents to FILE without code conversion."
584   ;; Make sure the directory exists.
585   (gnus-make-directory (file-name-directory file))
586   ;; Write the buffer.
587   (write-region-as-binary (point-min) (point-max) file nil 'quietly))
588
589 (defun gnus-write-buffer-as-coding-system (coding-system file)
590   "Write the current buffer's contents to FILE with code conversion."
591   ;; Make sure the directory exists.
592   (gnus-make-directory (file-name-directory file))
593   ;; Write the buffer.
594   (write-region-as-coding-system
595    coding-system (point-min) (point-max) file nil 'quietly))
596
597 (defun gnus-delete-file (file)
598   "Delete FILE if it exists."
599   (when (file-exists-p file)
600     (delete-file file)))
601
602 (defun gnus-strip-whitespace (string)
603   "Return STRING stripped of all whitespace."
604   (while (string-match "[\r\n\t ]+" string)
605     (setq string (replace-match "" t t string)))
606   string)
607
608 (defsubst gnus-put-text-property-excluding-newlines (beg end prop val)
609   "The same as `put-text-property', but don't put this prop on any newlines in the region."
610   (save-match-data
611     (save-excursion
612       (save-restriction
613         (goto-char beg)
614         (while (re-search-forward "[ \t]*\n" end 'move)
615           (gnus-put-text-property beg (match-beginning 0) prop val)
616           (setq beg (point)))
617         (gnus-put-text-property beg (point) prop val)))))
618
619 (defun gnus-put-text-property-excluding-characters-with-faces (beg end
620                                                                    prop val)
621   "The same as `put-text-property', but don't put props on characters with the `gnus-face' property."
622   (let ((b beg))
623     (while (/= b end)
624       (when (get-text-property b 'gnus-face)
625         (setq b (next-single-property-change b 'gnus-face nil end)))
626       (when (/= b end)
627         (gnus-put-text-property
628          b (setq b (next-single-property-change b 'gnus-face nil end))
629          prop val)))))
630
631 ;;; Protected and atomic operations.  dmoore@ucsd.edu 21.11.1996
632 ;;; The primary idea here is to try to protect internal datastructures
633 ;;; from becoming corrupted when the user hits C-g, or if a hook or
634 ;;; similar blows up.  Often in Gnus multiple tables/lists need to be
635 ;;; updated at the same time, or information can be lost.
636
637 (defvar gnus-atomic-be-safe t
638   "If t, certain operations will be protected from interruption by C-g.")
639
640 (defmacro gnus-atomic-progn (&rest forms)
641   "Evaluate FORMS atomically, which means to protect the evaluation
642 from being interrupted by the user.  An error from the forms themselves
643 will return without finishing the operation.  Since interrupts from
644 the user are disabled, it is recommended that only the most minimal
645 operations are performed by FORMS.  If you wish to assign many
646 complicated values atomically, compute the results into temporary
647 variables and then do only the assignment atomically."
648   `(let ((inhibit-quit gnus-atomic-be-safe))
649      ,@forms))
650
651 (put 'gnus-atomic-progn 'lisp-indent-function 0)
652
653 (defmacro gnus-atomic-progn-assign (protect &rest forms)
654   "Evaluate FORMS, but insure that the variables listed in PROTECT
655 are not changed if anything in FORMS signals an error or otherwise
656 non-locally exits.  The variables listed in PROTECT are updated atomically.
657 It is safe to use gnus-atomic-progn-assign with long computations.
658
659 Note that if any of the symbols in PROTECT were unbound, they will be
660 set to nil on a sucessful assignment.  In case of an error or other
661 non-local exit, it will still be unbound."
662   (let* ((temp-sym-map (mapcar (lambda (x) (list (make-symbol
663                                                   (concat (symbol-name x)
664                                                           "-tmp"))
665                                                  x))
666                                protect))
667          (sym-temp-map (mapcar (lambda (x) (list (cadr x) (car x)))
668                                temp-sym-map))
669          (temp-sym-let (mapcar (lambda (x) (list (car x)
670                                                  `(and (boundp ',(cadr x))
671                                                        ,(cadr x))))
672                                temp-sym-map))
673          (sym-temp-let sym-temp-map)
674          (temp-sym-assign (apply 'append temp-sym-map))
675          (sym-temp-assign (apply 'append sym-temp-map))
676          (result (make-symbol "result-tmp")))
677     `(let (,@temp-sym-let
678            ,result)
679        (let ,sym-temp-let
680          (setq ,result (progn ,@forms))
681          (setq ,@temp-sym-assign))
682        (let ((inhibit-quit gnus-atomic-be-safe))
683          (setq ,@sym-temp-assign))
684        ,result)))
685
686 (put 'gnus-atomic-progn-assign 'lisp-indent-function 1)
687 ;(put 'gnus-atomic-progn-assign 'edebug-form-spec '(sexp body))
688
689 (defmacro gnus-atomic-setq (&rest pairs)
690   "Similar to setq, except that the real symbols are only assigned when
691 there are no errors.  And when the real symbols are assigned, they are
692 done so atomically.  If other variables might be changed via side-effect,
693 see gnus-atomic-progn-assign.  It is safe to use gnus-atomic-setq
694 with potentially long computations."
695   (let ((tpairs pairs)
696         syms)
697     (while tpairs
698       (push (car tpairs) syms)
699       (setq tpairs (cddr tpairs)))
700     `(gnus-atomic-progn-assign ,syms
701        (setq ,@pairs))))
702
703 ;(put 'gnus-atomic-setq 'edebug-form-spec '(body))
704
705
706 ;;; Functions for saving to babyl/mail files.
707
708 (defvar rmail-default-rmail-file)
709 (defun gnus-output-to-rmail (filename &optional ask)
710   "Append the current article to an Rmail file named FILENAME."
711   (require 'rmail)
712   ;; Most of these codes are borrowed from rmailout.el.
713   (setq filename (expand-file-name filename))
714   (setq rmail-default-rmail-file filename)
715   (let ((artbuf (current-buffer))
716         (tmpbuf (get-buffer-create " *Gnus-output*")))
717     (save-excursion
718       (or (get-file-buffer filename)
719           (file-exists-p filename)
720           (if (or (not ask)
721                   (gnus-yes-or-no-p
722                    (concat "\"" filename "\" does not exist, create it? ")))
723               (let ((file-buffer (create-file-buffer filename)))
724                 (save-excursion
725                   (set-buffer file-buffer)
726                   (rmail-insert-rmail-file-header)
727                   (let ((require-final-newline nil))
728                     (gnus-write-buffer filename)))
729                 (kill-buffer file-buffer))
730             (error "Output file does not exist")))
731       (set-buffer tmpbuf)
732       (erase-buffer)
733       (insert-buffer-substring artbuf)
734       (gnus-convert-article-to-rmail)
735       ;; Decide whether to append to a file or to an Emacs buffer.
736       (let ((outbuf (get-file-buffer filename)))
737         (if (not outbuf)
738             (write-region-as-binary (point-min) (point-max) filename 'append)
739           ;; File has been visited, in buffer OUTBUF.
740           (set-buffer outbuf)
741           (let ((buffer-read-only nil)
742                 (msg (and (boundp 'rmail-current-message)
743                           (symbol-value 'rmail-current-message))))
744             ;; If MSG is non-nil, buffer is in RMAIL mode.
745             (when msg
746               (widen)
747               (narrow-to-region (point-max) (point-max)))
748             (insert-buffer-substring tmpbuf)
749             (when msg
750               (goto-char (point-min))
751               (widen)
752               (search-backward "\n\^_")
753               (narrow-to-region (point) (point-max))
754               (rmail-count-new-messages t)
755               (when (rmail-summary-exists)
756                 (rmail-select-summary
757                  (rmail-update-summary)))
758               (rmail-count-new-messages t)
759               (rmail-show-message msg))
760             (save-buffer)))))
761     (kill-buffer tmpbuf)))
762
763 (defun gnus-output-to-mail (filename &optional ask)
764   "Append the current article to a mail file named FILENAME."
765   (setq filename (expand-file-name filename))
766   (let ((artbuf (current-buffer))
767         (tmpbuf (get-buffer-create " *Gnus-output*")))
768     (save-excursion
769       ;; Create the file, if it doesn't exist.
770       (when (and (not (get-file-buffer filename))
771                  (not (file-exists-p filename)))
772         (if (or (not ask)
773                 (gnus-y-or-n-p
774                  (concat "\"" filename "\" does not exist, create it? ")))
775             (let ((file-buffer (create-file-buffer filename)))
776               (save-excursion
777                 (set-buffer file-buffer)
778                 (let ((require-final-newline nil))
779                   (gnus-write-buffer-as-binary filename)))
780               (kill-buffer file-buffer))
781           (error "Output file does not exist")))
782       (set-buffer tmpbuf)
783       (erase-buffer)
784       (insert-buffer-substring artbuf)
785       (goto-char (point-min))
786       (if (looking-at "From ")
787           (forward-line 1)
788         (insert "From nobody " (current-time-string) "\n"))
789       (let (case-fold-search)
790         (while (re-search-forward "^From " nil t)
791           (beginning-of-line)
792           (insert ">")))
793       ;; Decide whether to append to a file or to an Emacs buffer.
794       (let ((outbuf (get-file-buffer filename)))
795         (if (not outbuf)
796             (let ((buffer-read-only nil))
797               (save-excursion
798                 (goto-char (point-max))
799                 (forward-char -2)
800                 (unless (looking-at "\n\n")
801                   (goto-char (point-max))
802                   (unless (bolp)
803                     (insert "\n"))
804                   (insert "\n"))
805                 (goto-char (point-max))
806                 (write-region-as-binary (point-min) (point-max)
807                                         filename 'append)))
808           ;; File has been visited, in buffer OUTBUF.
809           (set-buffer outbuf)
810           (let ((buffer-read-only nil))
811             (goto-char (point-max))
812             (unless (eobp)
813               (insert "\n"))
814             (insert "\n")
815             (insert-buffer-substring tmpbuf)))))
816     (kill-buffer tmpbuf)))
817
818 (defun gnus-convert-article-to-rmail ()
819   "Convert article in current buffer to Rmail message format."
820   (let ((buffer-read-only nil))
821     ;; Convert article directly into Babyl format.
822     (goto-char (point-min))
823     (insert "\^L\n0, unseen,,\n*** EOOH ***\n")
824     (while (search-forward "\n\^_" nil t) ;single char
825       (replace-match "\n^_" t t))       ;2 chars: "^" and "_"
826     (goto-char (point-max))
827     (insert "\^_")))
828
829 (defun gnus-map-function (funs arg)
830   "Applies the result of the first function in FUNS to the second, and so on.
831 ARG is passed to the first function."
832   (let ((myfuns funs))
833     (while myfuns
834       (setq arg (funcall (pop myfuns) arg)))
835     arg))
836
837 (defun gnus-run-hooks (&rest funcs)
838   "Does the same as `run-hooks', but saves excursion."
839   (let ((buf (current-buffer)))
840     (unwind-protect
841         (apply 'run-hooks funcs)
842       (set-buffer buf))))
843
844 ;;;
845 ;;; .netrc and .authinforc parsing
846 ;;;
847
848 (defun gnus-parse-netrc (file)
849   "Parse FILE and return an list of all entries in the file."
850   (when (file-exists-p file)
851     (with-temp-buffer
852       (let ((tokens '("machine" "default" "login"
853                       "password" "account" "macdef" "force"))
854             alist elem result pair)
855         (insert-file-contents file)
856         (goto-char (point-min))
857         ;; Go through the file, line by line.
858         (while (not (eobp))
859           (narrow-to-region (point) (gnus-point-at-eol))
860           ;; For each line, get the tokens and values.
861           (while (not (eobp))
862             (skip-chars-forward "\t ")
863             ;; Skip lines that begin with a "#".
864             (if (eq (char-after) ?#)
865                 (goto-char (point-max))
866               (unless (eobp)
867                 (setq elem
868                       (if (= (following-char) ?\")
869                           (read (current-buffer))
870                         (buffer-substring
871                          (point) (progn (skip-chars-forward "^\t ")
872                                         (point)))))
873                 (cond
874                  ((equal elem "macdef")
875                   ;; We skip past the macro definition.
876                   (widen)
877                   (while (and (zerop (forward-line 1))
878                               (looking-at "$")))
879                   (narrow-to-region (point) (point)))
880                  ((member elem tokens)
881                   ;; Tokens that don't have a following value are ignored,
882                   ;; except "default".
883                   (when (and pair (or (cdr pair)
884                                       (equal (car pair) "default")))
885                     (push pair alist))
886                   (setq pair (list elem)))
887                  (t
888                   ;; Values that haven't got a preceding token are ignored.
889                   (when pair
890                     (setcdr pair elem)
891                     (push pair alist)
892                     (setq pair nil)))))))
893           (when alist
894             (push (nreverse alist) result))
895           (setq alist nil
896                 pair nil)
897           (widen)
898           (forward-line 1))
899         (nreverse result)))))
900
901 (defun gnus-netrc-machine (list machine)
902   "Return the netrc values from LIST for MACHINE or for the default entry."
903   (let ((rest list))
904     (while (and list
905                 (not (equal (cdr (assoc "machine" (car list))) machine)))
906       (pop list))
907     (car (or list
908              (progn (while (and rest (not (assoc "default" (car rest))))
909                       (pop rest))
910                     rest)))))
911
912 (defun gnus-netrc-get (alist type)
913   "Return the value of token TYPE from ALIST."
914   (cdr (assoc type alist)))
915
916 ;;; Various
917
918 (defvar gnus-group-buffer)              ; Compiler directive
919 (defun gnus-alive-p ()
920   "Say whether Gnus is running or not."
921   (and (boundp 'gnus-group-buffer)
922        (get-buffer gnus-group-buffer)
923        (save-excursion
924          (set-buffer gnus-group-buffer)
925          (eq major-mode 'gnus-group-mode))))
926
927 (defun gnus-remove-duplicates (list)
928   (let (new (tail list))
929     (while tail
930       (or (member (car tail) new)
931           (setq new (cons (car tail) new)))
932       (setq tail (cdr tail)))
933     (nreverse new)))
934
935 (defun gnus-delete-if (predicate list)
936   "Delete elements from LIST that satisfy PREDICATE."
937   (let (out)
938     (while list
939       (unless (funcall predicate (car list))
940         (push (car list) out))
941       (pop list))
942     (nreverse out)))
943
944 (defun gnus-delete-alist (key alist)
945   "Delete all entries in ALIST that have a key eq to KEY."
946   (let (entry)
947     (while (setq entry (assq key alist))
948       (setq alist (delq entry alist)))
949     alist))
950
951 (defmacro gnus-pull (key alist &optional assoc-p)
952   "Modify ALIST to be without KEY."
953   (unless (symbolp alist)
954     (error "Not a symbol: %s" alist))
955   (let ((fun (if assoc-p 'assoc 'assq)))
956     `(setq ,alist (delq (,fun ,key ,alist) ,alist))))
957
958 (defun gnus-globalify-regexp (re)
959   "Returns a regexp that matches a whole line, iff RE matches a part of it."
960   (concat (unless (string-match "^\\^" re) "^.*")
961           re
962           (unless (string-match "\\$$" re) ".*$")))
963
964 (defun gnus-set-window-start (&optional point)
965   "Set the window start to POINT, or (point) if nil."
966   (let ((win (get-buffer-window (current-buffer) t)))
967     (when win
968       (set-window-start win (or point (point))))))
969
970 (defun gnus-annotation-in-region-p (b e)
971   (if (= b e)
972       (eq (cadr (memq 'gnus-undeletable (text-properties-at b))) t)
973     (text-property-any b e 'gnus-undeletable t)))
974
975 (defun gnus-or (&rest elems)
976   "Return non-nil if any of the elements are non-nil."
977   (catch 'found
978     (while elems
979       (when (pop elems)
980         (throw 'found t)))))
981
982 (defun gnus-and (&rest elems)
983   "Return non-nil if all of the elements are non-nil."
984   (catch 'found
985     (while elems
986       (unless (pop elems)
987         (throw 'found nil)))
988     t))
989
990 (defun gnus-write-active-file-as-coding-system (coding-system file hashtb
991                                                               &optional
992                                                               full-names)
993   (let ((output-coding-system coding-system)
994         (coding-system-for-write coding-system))
995     (with-temp-file file
996       (mapatoms
997        (lambda (sym)
998          (when (and sym
999                     (boundp sym)
1000                     (symbol-value sym))
1001            (insert (format "%S %d %d y\n"
1002                            (if full-names
1003                                sym
1004                              (intern (gnus-group-real-name (symbol-name sym))))
1005                            (or (cdr (symbol-value sym))
1006                                (car (symbol-value sym)))
1007                            (car (symbol-value sym))))))
1008        hashtb)
1009       (goto-char (point-max))
1010       (while (search-backward "\\." nil t)
1011         (delete-char 1)))))
1012
1013 (defun gnus-union (a b)
1014   "Add members of list A to list B if they are not equal to items already
1015 in B.  This function is copied from `shadow-union' in file shadowfile.el.
1016 It is faster than cl-`union' and it uses `member' even though cl-`union'
1017 uses `memq' for comparing each element."
1018   (if (null a)
1019       b
1020     (if (member (car a) b)
1021         (gnus-union (cdr a) b)
1022       (gnus-union (cdr a) (cons (car a) b)))))
1023
1024 (gnus-ems-redefine)
1025
1026 (provide 'gnus-util)
1027
1028 ;;; gnus-util.el ends here