Refill some copyright headers.
[gnus] / lisp / gmm-utils.el
1 ;;; gmm-utils.el --- Utility functions for Gnus, Message and MML
2
3 ;; Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011
4 ;;   Free Software Foundation, Inc.
5
6 ;; Author: Reiner Steib <reiner.steib@gmx.de>
7 ;; Keywords: news
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This library provides self-contained utility functions.  The functions are
27 ;; used in Gnus, Message and MML, but within this library there are no
28 ;; dependencies on Gnus, Message, or MML.
29
30 ;;; Code:
31
32 (defgroup gmm nil
33   "Utility functions for Gnus, Message and MML."
34   :prefix "gmm-"
35   :version "22.1" ;; Gnus 5.10.9
36   :group 'lisp)
37
38 ;; Helper functions from `gnus-utils.el': gmm-verbose, gmm-message, gmm-error
39
40 (defcustom gmm-verbose 7
41   "Integer that says how verbose gmm should be.
42 The higher the number, the more messages will flash to say what
43 it did.  At zero, it will be totally mute; at five, it will
44 display most important messages; and at ten, it will keep on
45 jabbering all the time."
46   :type 'integer
47   :group 'gmm)
48
49 ;;;###autoload
50 (defun gmm-regexp-concat (regexp)
51   "Potentially concat a list of regexps into a single one.
52 The concatenation is done with logical ORs."
53   (cond ((null regexp)
54          nil)
55         ((stringp regexp)
56          regexp)
57         ((listp regexp)
58          (mapconcat (lambda (elt) (concat "\\(" elt "\\)"))
59                     regexp
60                     "\\|"))))
61
62 ;;;###autoload
63 (defun gmm-message (level &rest args)
64   "If LEVEL is lower than `gmm-verbose' print ARGS using `message'.
65
66 Guideline for numbers:
67 1 - error messages
68 3 - non-serious error messages
69 5 - messages for things that take a long time
70 7 - not very important messages on stuff
71 9 - messages inside loops."
72   (if (<= level gmm-verbose)
73       (apply 'message args)
74     ;; We have to do this format thingy here even if the result isn't
75     ;; shown - the return value has to be the same as the return value
76     ;; from `message'.
77     (apply 'format args)))
78
79 ;;;###autoload
80 (defun gmm-error (level &rest args)
81   "Beep an error if LEVEL is equal to or less than `gmm-verbose'.
82 ARGS are passed to `message'."
83   (when (<= (floor level) gmm-verbose)
84     (apply 'message args)
85     (ding)
86     (let (duration)
87       (when (and (floatp level)
88                  (not (zerop (setq duration (* 10 (- level (floor level)))))))
89         (sit-for duration))))
90   nil)
91
92 ;;;###autoload
93 (defun gmm-widget-p (symbol)
94   "Non-nil if SYMBOL is a widget."
95   (get symbol 'widget-type))
96
97 (autoload 'widget-create-child-value "wid-edit")
98 (autoload 'widget-convert "wid-edit")
99 (autoload 'widget-default-get "wid-edit")
100
101 ;; Copy of the `nnmail-lazy' code from `nnmail.el':
102 (define-widget 'gmm-lazy 'default
103   "Base widget for recursive datastructures.
104
105 This is a copy of the `lazy' widget in Emacs 22.1 provided for compatibility."
106   :format "%{%t%}: %v"
107   :convert-widget 'widget-value-convert-widget
108   :value-create (lambda (widget)
109                   (let ((value (widget-get widget :value))
110                         (type (widget-get widget :type)))
111                     (widget-put widget :children
112                                 (list (widget-create-child-value
113                                        widget (widget-convert type) value)))))
114   :value-delete 'widget-children-value-delete
115   :value-get (lambda (widget)
116                (widget-value (car (widget-get widget :children))))
117   :value-inline (lambda (widget)
118                   (widget-apply (car (widget-get widget :children))
119                                 :value-inline))
120   :default-get (lambda (widget)
121                  (widget-default-get
122                   (widget-convert (widget-get widget :type))))
123   :match (lambda (widget value)
124            (widget-apply (widget-convert (widget-get widget :type))
125                          :match value))
126   :validate (lambda (widget)
127               (widget-apply (car (widget-get widget :children)) :validate)))
128
129 ;; Note: The format of `gmm-tool-bar-item' may change if some future Emacs
130 ;; version will provide customizable tool bar buttons using a different
131 ;; interface.
132
133 ;; TODO: Extend API so that the "Command" entry can be a function or a plist.
134 ;; In case of a list it should have the format...
135 ;;
136 ;;  (:none command-without-modifier
137 ;;   :shift command-with-shift-pressed
138 ;;   :control command-with-ctrl-pressed
139 ;;   :control-shift command-with-control-and-shift-pressed
140 ;;   ;; mouse-2 and mouse-3 can't be used in Emacs yet.
141 ;;   :mouse-2 command-on-mouse-2-press
142 ;;   :mouse-3 command-on-mouse-3-press) ;; typically a menu of related commands
143 ;;
144 ;; Combinations of mouse-[23] plus shift and/or controll might be overkill.
145 ;;
146 ;; Then use (plist-get rs-command :none), (plist-get rs-command :shift)
147
148 (define-widget 'gmm-tool-bar-item (if (gmm-widget-p 'lazy) 'lazy 'gmm-lazy)
149   "Tool bar list item."
150   :tag "Tool bar item"
151   :type '(choice
152           (list :tag "Command and Icon"
153                 (function :tag "Command")
154                 (string :tag "Icon file")
155                 (choice
156                  (const :tag "Default map" nil)
157                  ;; Note: Usually we need non-nil attributes if map is t.
158                  (const :tag "No menu" t)
159                  (sexp :tag "Other map"))
160                 (plist :inline t :tag "Properties"))
161           (list :tag "Separator"
162                 (const :tag "No command" gmm-ignore)
163                 (string :tag "Icon file")
164                 (const :tag "No map")
165                 (plist :inline t :tag "Properties"))))
166
167 (define-widget 'gmm-tool-bar-zap-list (if (gmm-widget-p 'lazy) 'lazy 'gmm-lazy)
168   "Tool bar zap list."
169   :tag "Tool bar zap list"
170   :type '(choice (const :tag "Zap all" t)
171                  (const :tag "Keep all" nil)
172                  (list
173                   ;; :value
174                   ;; Work around (bug in customize?), see
175                   ;; <news:v9is48jrj1.fsf@marauder.physik.uni-ulm.de>
176                   ;; (new-file open-file dired kill-buffer write-file
177                   ;;        print-buffer customize help)
178                   (set :inline t
179                        (const new-file)
180                        (const open-file)
181                        (const dired)
182                        (const kill-buffer)
183                        (const save-buffer)
184                        (const write-file)
185                        (const undo)
186                        (const cut)
187                        (const copy)
188                        (const paste)
189                        (const search-forward)
190                        (const print-buffer)
191                        (const customize)
192                        (const help))
193                   (repeat :inline t
194                           :tag "Other"
195                           (symbol :tag "Icon item")))))
196
197 ;; (defun gmm-color-cells (&optional display)
198 ;;   "Return the number of color cells supported by DISPLAY.
199 ;; Compatibility function."
200 ;;   ;; `display-color-cells' doesn't return more than 256 even if color depth is
201 ;;   ;; > 8 in Emacs 21.
202 ;;   ;;
203 ;;   ;; Feel free to add proper XEmacs support.
204 ;;   (let* ((cells (and (fboundp 'display-color-cells)
205 ;;                   (display-color-cells display)))
206 ;;       (plane (and (fboundp 'x-display-planes)
207 ;;                   (ash 1 (x-display-planes))))
208 ;;       (none -1))
209 ;;     (max (if (integerp cells) cells none)
210 ;;       (if (integerp plane) plane none))))
211
212 (defcustom gmm-tool-bar-style
213   (if (and (boundp 'tool-bar-mode)
214            tool-bar-mode
215            (and (fboundp 'display-visual-class)
216                 (not (memq (display-visual-class)
217                            (list 'static-gray 'gray-scale
218                                  'static-color 'pseudo-color)))))
219       'gnome
220     'retro)
221   "Prefered tool bar style."
222   :type '(choice (const :tag "GNOME style" gnome)
223                  (const :tag "Retro look"  retro))
224   :group 'gmm)
225
226 (defvar tool-bar-map)
227
228 ;;;###autoload
229 (defun gmm-tool-bar-from-list (icon-list zap-list default-map)
230   "Make a tool bar from ICON-LIST.
231
232 Within each entry of ICON-LIST, the first element is a menu
233 command, the second element is an icon file name and the third
234 element is a test function.  You can use \\[describe-key]
235 <menu-entry> to find out the name of a menu command.  The fourth
236 and all following elements are passed as the PROPS argument to the
237 function `tool-bar-local-item'.
238
239 If ZAP-LIST is a list, remove those item from the default
240 `tool-bar-map'.  If it is t, start with a new sparse map.  You
241 can use \\[describe-key] <icon> to find out the name of an icon
242 item.  When \\[describe-key] <icon> shows \"<tool-bar> <new-file>
243 runs the command find-file\", then use `new-file' in ZAP-LIST.
244
245 DEFAULT-MAP specifies the default key map for ICON-LIST."
246   (let (;; For Emacs 21, we must let-bind `tool-bar-map'.  In Emacs 22, we
247         ;; could use some other local variable.
248         (tool-bar-map (if (eq zap-list t)
249                           (make-sparse-keymap)
250                         (copy-keymap tool-bar-map))))
251     (when (listp zap-list)
252       ;; Zap some items which aren't relevant for this mode and take up space.
253       (dolist (key zap-list)
254         (define-key tool-bar-map (vector key) nil)))
255     (mapc (lambda (el)
256             (let ((command (car el))
257                   (icon (nth 1 el))
258                   (fmap (or (nth 2 el) default-map))
259                   (props  (cdr (cdr (cdr el)))) )
260               ;; command may stem from different from-maps:
261               (cond ((eq command 'gmm-ignore)
262                      ;; The dummy `gmm-ignore', see `gmm-tool-bar-item'
263                      ;; widget.  Suppress tooltip by adding `:enable nil'.
264                      (if (fboundp 'tool-bar-local-item)
265                          (apply 'tool-bar-local-item icon nil nil
266                                 tool-bar-map :enable nil props)
267                        ;; (tool-bar-local-item ICON DEF KEY MAP &rest PROPS)
268                        ;; (tool-bar-add-item ICON DEF KEY &rest PROPS)
269                        (apply 'tool-bar-add-item icon nil nil :enable nil props)))
270                     ((equal fmap t) ;; Not a menu command
271                      (apply 'tool-bar-local-item
272                             icon command
273                             (intern icon) ;; reuse icon or fmap here?
274                             tool-bar-map props))
275                     (t ;; A menu command
276                      (apply 'tool-bar-local-item-from-menu
277                             ;; (apply 'tool-bar-local-item icon def key
278                             ;; tool-bar-map props)
279                             command icon tool-bar-map (symbol-value fmap)
280                             props)))
281               t))
282           (if (symbolp icon-list)
283               (eval icon-list)
284             icon-list))
285     tool-bar-map))
286
287 (defmacro defun-gmm (name function arg-list &rest body)
288   "Create function NAME.
289 If FUNCTION exists, then NAME becomes an alias for FUNCTION.
290 Otherwise, create function NAME with ARG-LIST and BODY."
291   (let ((defined-p (fboundp function)))
292     (if defined-p
293         `(defalias ',name ',function)
294       `(defun ,name ,arg-list ,@body))))
295
296 (defun-gmm gmm-image-search-load-path
297   image-search-load-path (file &optional path)
298   "Emacs 21 and XEmacs don't have `image-search-load-path'.
299 This function returns nil on those systems."
300   nil)
301
302 ;; Cf. `mh-image-load-path-for-library' in `mh-compat.el'.
303
304 (defun-gmm gmm-image-load-path-for-library
305   image-load-path-for-library (library image &optional path no-error)
306   "Return a suitable search path for images used by LIBRARY.
307
308 It searches for IMAGE in `image-load-path' (excluding
309 \"`data-directory'/images\") and `load-path', followed by a path
310 suitable for LIBRARY, which includes \"../../etc/images\" and
311 \"../etc/images\" relative to the library file itself, and then
312 in \"`data-directory'/images\".
313
314 Then this function returns a list of directories which contains
315 first the directory in which IMAGE was found, followed by the
316 value of `load-path'.  If PATH is given, it is used instead of
317 `load-path'.
318
319 If NO-ERROR is non-nil and a suitable path can't be found, don't
320 signal an error.  Instead, return a list of directories as before,
321 except that nil appears in place of the image directory.
322
323 Here is an example that uses a common idiom to provide
324 compatibility with versions of Emacs that lack the variable
325 `image-load-path':
326
327     ;; Shush compiler.
328     (defvar image-load-path)
329
330     (let* ((load-path (image-load-path-for-library \"mh-e\" \"mh-logo.xpm\"))
331            (image-load-path (cons (car load-path)
332                                   (when (boundp 'image-load-path)
333                                     image-load-path))))
334       (mh-tool-bar-folder-buttons-init))"
335   (unless library (error "No library specified"))
336   (unless image   (error "No image specified"))
337   (let (image-directory image-directory-load-path)
338     ;; Check for images in image-load-path or load-path.
339     (let ((img image)
340           (dir (or
341                 ;; Images in image-load-path.
342                 (gmm-image-search-load-path image) ;; "gmm-" prefix!
343                 ;; Images in load-path.
344                 (locate-library image)))
345           parent)
346       ;; Since the image might be in a nested directory (for
347       ;; example, mail/attach.pbm), adjust `image-directory'
348       ;; accordingly.
349       (when dir
350         (setq dir (file-name-directory dir))
351         (while (setq parent (file-name-directory img))
352           (setq img (directory-file-name parent)
353                 dir (expand-file-name "../" dir))))
354       (setq image-directory-load-path dir))
355
356     ;; If `image-directory-load-path' isn't Emacs' image directory,
357     ;; it's probably a user preference, so use it.  Then use a
358     ;; relative setting if possible; otherwise, use
359     ;; `image-directory-load-path'.
360     (cond
361      ;; User-modified image-load-path?
362      ((and image-directory-load-path
363            (not (equal image-directory-load-path
364                        (file-name-as-directory
365                         (expand-file-name "images" data-directory)))))
366       (setq image-directory image-directory-load-path))
367      ;; Try relative setting.
368      ((let (library-name d1ei d2ei)
369         ;; First, find library in the load-path.
370         (setq library-name (locate-library library))
371         (if (not library-name)
372             (error "Cannot find library %s in load-path" library))
373         ;; And then set image-directory relative to that.
374         (setq
375          ;; Go down 2 levels.
376          d2ei (file-name-as-directory
377                (expand-file-name
378                 (concat (file-name-directory library-name) "../../etc/images")))
379          ;; Go down 1 level.
380          d1ei (file-name-as-directory
381                (expand-file-name
382                 (concat (file-name-directory library-name) "../etc/images"))))
383         (setq image-directory
384               ;; Set it to nil if image is not found.
385               (cond ((file-exists-p (expand-file-name image d2ei)) d2ei)
386                     ((file-exists-p (expand-file-name image d1ei)) d1ei)))))
387      ;; Use Emacs' image directory.
388      (image-directory-load-path
389       (setq image-directory image-directory-load-path))
390      (no-error
391       (message "Could not find image %s for library %s" image library))
392      (t
393       (error "Could not find image %s for library %s" image library)))
394
395     ;; Return an augmented `path' or `load-path'.
396     (nconc (list image-directory)
397            (delete image-directory (copy-sequence (or path load-path))))))
398
399 (defun gmm-customize-mode (&optional mode)
400   "Customize customization group for MODE.
401 If mode is nil, use `major-mode' of the current buffer."
402   (interactive)
403   (customize-group
404    (or mode
405        (intern (let ((mode (symbol-name major-mode)))
406                  (string-match "^\\(.+\\)-mode$" mode)
407                  (match-string 1 mode))))))
408
409 (defun gmm-write-region (start end filename &optional append visit
410                                lockname mustbenew)
411   "Compatibility function for `write-region'.
412
413 In XEmacs, the seventh argument of `write-region' specifies the
414 coding-system."
415   (if (and mustbenew (featurep 'xemacs))
416       (if (file-exists-p filename)
417           (signal 'file-already-exists (list "File exists" filename))
418         (write-region start end filename append visit lockname))
419     (write-region start end filename append visit lockname mustbenew)))
420
421 (provide 'gmm-utils)
422
423 ;;; gmm-utils.el ends here