Initial Commit
[packages] / xemacs-packages / hyperbole / hypb.el
1 ;;; hypb.el --- Miscellaneous Hyperbole support features.
2
3 ;; Copyright (C) 1991-1995, Free Software Foundation, Inc.
4 ;; Developed with support from Motorola Inc.
5
6 ;; Author: Bob Weiner, Brown U.
7 ;; Maintainer: Mats Lidell <matsl@contactor.se>
8 ;; Keywords: extensions, hypermedia
9
10 ;; This file is part of GNU Hyperbole.
11
12 ;; GNU Hyperbole is free software; you can redistribute it and/or
13 ;; modify it under the terms of the GNU General Public License as
14 ;; published by the Free Software Foundation; either version 3, or (at
15 ;; your option) any later version.
16
17 ;; GNU Hyperbole is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 ;; General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26
27 ;;; Commentary:
28
29 ;;; Code:
30
31 ;;;
32 ;;; Other required Elisp libraries
33 ;;;
34
35 (mapcar 'require '(hversion hact))
36
37 ;;;
38 ;;; Public variables
39 ;;;
40
41 (defconst hypb:help-buf-suffix " Hypb Help*"
42   "Suffix attached to all native Hyperbole help buffer names.")
43
44 ;;;
45 ;;; Public functions
46 ;;;
47
48 (defun hypb:call-process-p (program infile &optional predicate &rest args)
49   "Calls an external PROGRAM with INFILE for input.
50 If PREDICATE is given, it is evaluated in a buffer with the PROGRAM's
51 output and the result returned.  If PREDICATE is nil, returns t iff
52 program has no output or just a 0-valued output.
53 Rest of ARGS are passed as arguments to PROGRAM."
54   (let ((buf (get-buffer-create "*test-output*"))
55         (found))
56     (save-excursion
57       (set-buffer buf) (setq buffer-read-only nil) (erase-buffer)
58       (apply 'call-process program infile buf nil args)
59       (setq found 
60             (if predicate
61                 (eval predicate)
62               (or (= (point-max) 1) ;; No output, consider cmd a success.
63                   (and (< (point-max) 4)
64                        (string= (buffer-substring 1 2) "0")))))
65       (set-buffer-modified-p nil)
66       (kill-buffer buf))
67     found))
68
69
70 (defun hypb:chmod (op octal-permissions file)
71   "Uses OP and OCTAL-PERMISSIONS integer to set FILE permissions.
72 OP may be +, -, xor, or default =."
73   (let ((func (cond ((eq op '+)   (function logior))
74                     ((eq op '-)   (function
75                                    (lambda (p1 p2) (logand (lognot p1) p2))))
76                     ((eq op 'xor) (function logxor))
77                     (t            (function (lambda (p1 p2) p1))))))
78     (set-file-modes file (funcall func (hypb:oct-to-int octal-permissions)
79                                   (file-modes file)))))
80
81 (defun hypb:cmd-key-string (cmd-sym &optional keymap)
82   "Returns a single pretty printed key sequence string bound to CMD-SYM.
83 Global keymap is used unless optional KEYMAP is given."
84   (if (and cmd-sym (symbolp cmd-sym) (fboundp cmd-sym))
85   (let* ((get-keys (function
86                     (lambda (cmd-sym keymap)
87                       (key-description (where-is-internal
88                                         cmd-sym keymap 'first)))))
89          (keys (funcall get-keys cmd-sym keymap)))
90     (concat "{"
91             (if (string= keys "")
92                 (concat (funcall get-keys 'execute-extended-command nil)
93                         " " (symbol-name cmd-sym) " RTN")
94               keys)
95             "}"))
96   (error "(hypb:cmd-key-string): Invalid cmd-sym arg: %s." cmd-sym)))
97
98 ;;;###autoload
99 (defun hypb:configuration (&optional out-buf)
100   "Insert Emacs configuration information at the end of optional OUT-BUF or the current buffer."
101   (save-excursion
102     (and out-buf (set-buffer out-buf))
103     (goto-char (point-max))
104     (delete-blank-lines) (delete-blank-lines)
105     (let ((start (point)))
106       (insert (format "I use:\tEditor:      %s\n\tHyperbole:   %s\n"
107                       (if (boundp 'epoch::version)
108                           epoch::version
109                         (hypb:replace-match-string
110                          " of .+" (emacs-version) "" t))
111                       hyperb:version))
112       (if (and (boundp 'system-configuration) (stringp system-configuration))
113           (insert (format "\tSys Type:    %s\n" system-configuration)))
114       (insert (format "\tOS Type:     %s\n\tWindow Sys:  %s\n"
115                       system-type (or window-system hyperb:window-system
116                                       "None")))
117       (if (and (boundp 'hmail:reader) hmail:reader)
118           (insert (format "\tMailer:      %s\n"
119                           (cond ((eq hmail:reader 'rmail-mode) "RMAIL")
120                                 ((eq hmail:reader 'vm-mode)
121                                  (concat "VM " vm-version))
122                                 ((and (eq hmail:reader 'mh-show-mode)
123                                       (string-match "v ?\\([0-9]+.[0-9]+\\)"
124                                           mh-e-RCS-id))
125                                  (concat "MH-e "
126                                          (substring mh-e-RCS-id
127                                                     (match-beginning 1)
128                                                     (match-end 1))))
129                                 ((eq hmail:reader 'pm-fdr-mode)
130                                  (concat "PIEmail " pm-version))
131                                 ))))
132       (if (and (boundp 'hnews:reader) (boundp 'gnus-version) hnews:reader)
133           (insert (format "\tNews Rdr:    %s\n" gnus-version)))
134       (if (and (boundp 'br-version) (stringp br-version))
135           (insert (format "\tOO-Browser:  %s\n" br-version)))
136       (untabify start (point)))))
137
138 (if (fboundp 'copy-tree)
139     (fset 'hypb:copy-sublists 'copy-tree)
140   ;;
141   ;; This function is derived from a copylefted function.
142   ;; Define hypb:copy-sublists if not a builtin.  This version 
143   ;; is a Lisp translation of the C version in Lemacs 19.8.
144   ;; Copyright (C) 1985, 1986, 1987, 1992, 1993 Free Software Foundation, Inc.
145   ;; Available for use and distribution under the GPL.
146   ;;
147   (defun hypb:copy-sublists (obj &optional vector-p)
148     "Return a copy of a list and substructures.
149 The argument is copied, and any lists contained within it are copied
150 recursively.  Circularities and shared substructures are not preserved.
151 Second arg VECP causes vectors to be copied, too.  Strings are not copied."
152     (cond ((consp obj)
153            (let (rest)
154              (setq obj (copy-sequence obj)
155                    rest obj)
156              (while (consp rest)
157                (let ((elt (car rest)))
158                  (if quit-flag (top-level))
159                  (if (or (consp elt) (vectorp elt))
160                      (setcar rest (hypb:copy-sublists elt vector-p)))
161                  (if (vectorp (cdr rest))
162                      (setcdr rest (hypb:copy-sublists (cdr rest) vector-p)))
163                  (setq rest (cdr rest))))))
164           ((and (vectorp obj) obj)
165            (let ((i (length obj))
166                  (j 0)
167                  elt)
168              (setq obj (copy-sequence obj))
169              (while (< j i)
170                (setq elt (aref obj j))
171                (if quit-flag (top-level))
172                (if (or (consp elt) (vectorp elt))
173                    (aset obj j (hypb:copy-sublists elt vector-p)))
174                (setq j (1+ j))))))
175     obj))
176
177 (defun hypb:debug ()
178   "Loads Hyperbole hbut.el source file and sets debugging traceback flag."
179   (interactive)
180   (or (featurep 'hinit) (load "hsite"))
181   (or (and (featurep 'hbut)
182            (let ((func (hypb:indirect-function 'ebut:create)))
183              (not (or (hypb:v19-byte-code-p func)
184                       (eq 'byte-code
185                           (car (car (nthcdr 3 (hypb:indirect-function
186                                                'ebut:create)))))))))
187       (load "hbut.el"))
188   (setq debug-on-error t))
189
190 (defun hypb:domain-name ()
191   "Returns current Internet domain name with '@' prepended or nil if none."
192   (let* ((dname-cmd (or (file-exists-p "/usr/bin/domainname")
193                         (file-exists-p "/bin/domainname")))
194          (dname (or (getenv "DOMAINNAME")
195                     (if dname-cmd
196                         (hypb:call-process-p
197                          "domainname" nil 
198                          '(substring (buffer-string) 0 -1))))))
199     (if (or (and dname (string-match "\\." dname))
200             (let* ((src "/etc/resolv.conf")
201                    (src-buf-exists-p (get-file-buffer src)))
202               (and (file-exists-p src) (file-readable-p src)
203                    (save-excursion
204                      (set-buffer (find-file-noselect src))
205                      (goto-char (point-min))
206                      (if (re-search-forward  "^domain[ \t]+\\([^ \t\n]+\\)"
207                                              nil t)
208                          (setq dname (buffer-substring (match-beginning 1)
209                                                        (match-end 1))))
210                      (or src-buf-exists-p (kill-buffer nil))
211                      dname))))
212         (concat "@" dname))))
213
214 (defun hypb:error (&rest args)
215   "Signals an error typically to be caught by 'hui:menu'."
216   (let ((msg (apply 'format args)))
217     (put 'error 'error-message msg)
218     (error msg)))
219
220 (defun hypb:functionp (obj)
221 "Returns t if OBJ is a function, nil otherwise."
222   (cond
223     ((symbolp obj) (fboundp obj))
224     ((subrp obj))
225     ((hypb:v19-byte-code-p obj))
226     ((consp obj)
227      (if (eq (car obj) 'lambda) (listp (car (cdr obj)))))
228     (t nil)))
229
230 (defun hypb:function-copy (func-symbol)
231   "Copies FUNC-SYMBOL's body for overloading.  Returns copy of body."
232   (if (fboundp func-symbol)
233       (let ((func (hypb:indirect-function func-symbol)))
234         (cond ((listp func) (copy-sequence func))
235               ((subrp func) (error "(hypb:function-copy): `%s' is a primitive; can't copy body."
236                                    func-symbol))
237               ((and (hypb:v19-byte-code-p func) (fboundp 'make-byte-code))
238                (let ((new-code (append func nil))) ; turn it into a list
239                  (apply 'make-byte-code new-code)))
240               (t (error "(hypb:function-copy): Can't copy function body: %s" func))
241               ))
242     (error "(hypb:function-copy): `%s' symbol is not bound to a function."
243            func-symbol)))
244
245 (defun hypb:function-overload (func-sym prepend &rest new-forms)
246   "Redefine function named FUNC-SYM by either PREPENDing (or appending if nil) rest of quoted NEW-FORMS."
247   (let ((old-func-sym (intern
248                         (concat "*hypb-old-"
249                                 (symbol-name func-sym)
250                                 "*"))))
251     (or (fboundp old-func-sym)
252         (fset old-func-sym (hypb:function-copy func-sym)))
253     (let* ((old-func (hypb:indirect-function old-func-sym))
254            (old-param-list (action:params old-func))
255            (param-list (action:param-list old-func))
256            (old-func-call
257              (list (if (memq '&rest old-param-list)
258                        ;; Have to account for extra list wrapper from &rest.
259                        (cons 'apply
260                              (cons (list 'quote old-func-sym) param-list))
261                      (cons old-func-sym param-list)))))
262       (eval (append
263               (list 'defun func-sym old-param-list)
264               (delq nil
265                     (list
266                       (documentation old-func-sym)
267                       (action:commandp old-func-sym)))
268               (if prepend
269                   (append new-forms old-func-call)
270                 (append old-func-call new-forms)))))))
271
272 (defun hypb:function-symbol-replace (func-sym sym-to-replace replace-with-sym)
273   "Replaces in body of FUNC-SYM SYM-TO-REPLACE with REPLACE-WITH-SYM.
274 All occurrences within lists are replaced.  Returns body of modified FUNC-SYM."
275   (let ((body (hypb:indirect-function func-sym))
276         (arg-vector) (arg))
277     (if (listp body)
278         ;; assume V18 byte compiler
279         (setq arg-vector
280               (car (delq nil (mapcar
281                                (function
282                                  (lambda (elt)
283                                    (and (listp elt)
284                                         (vectorp (setq arg-vector (nth 2 elt)))
285                                         arg-vector)))
286                                body))))
287       ;; assume V19 byte compiler   (eq (compiled-function-p body) t)
288       (setq arg (aref body 2)
289             arg-vector (if (vectorp arg) arg))
290       )
291     (if arg-vector
292         ;; Code is byte-compiled.
293         (let ((i (1- (length arg-vector))))
294           (setq arg nil)
295           (while (and (not arg) (>= i 0))
296             (if (eq (setq arg (aref arg-vector i)) sym-to-replace)
297                 (aset arg-vector i replace-with-sym)
298               (setq arg nil i (1- i)))))
299       ;; Code is not byte-compiled.
300       ;; Only replaces occurrence of symbol as an element of a list.
301       (hypb:map-sublists
302         (function
303           (lambda (atom list) (if (eq atom sym-to-replace)
304                                   (let ((again t))
305                                     (while (and again list)
306                                       (if (eq (car list) atom)
307                                           (progn (setcar list replace-with-sym)
308                                                  (setq again nil))
309                                         (setq list (cdr list))))))))
310         body)
311       )
312     body))
313
314 (defun hypb:help-buf-name (&optional prefix)
315   "Returns a Hyperbole help buffer name for current buffer.
316 With optional PREFIX string, uses it rather than buffer name."
317   (let ((bn (or prefix (buffer-name))))
318     (if (string-match " Hypb " bn)
319         (buffer-name (generate-new-buffer bn))
320       (concat "*" bn hypb:help-buf-suffix))))
321
322 (defun hypb:indirect-function (obj)
323   "Return the function at the end of OBJ's function chain.
324 Resolves autoloadable function symbols properly."
325   (let ((func
326          (if (fboundp 'indirect-function)
327              (indirect-function obj)
328            (while (symbolp obj)
329              (setq obj (symbol-function obj)))
330            obj)))
331     ;; Handle functions with autoload bodies.
332     (if (and (symbolp obj) (listp func) (eq (car func) 'autoload))
333         (let ((load-file (car (cdr func))))
334           (load load-file)
335           ;; Prevent infinite recursion
336           (if (equal func (symbol-function obj))
337               (error "(hypb:indirect-function): Autoload of '%s' failed" obj)
338             (hypb:indirect-function obj)))
339       func)))
340
341 (defun hypb:insert-region (buffer start end invisible-flag)
342   "Insert into BUFFER the contents of a region from START to END in the current buffer.
343 INVISIBLE-FLAG, if non-nil, means invisible text in an outline region is
344 copied, otherwise, it is omitted."
345   (let ((from-koutline (eq major-mode 'kotl-mode)))
346   (append-to-buffer buffer start end)
347   (save-excursion
348     (set-buffer buffer)
349     (let ((first (- (point) (- end start)))
350           (last (point)))
351       ;; Remove from buffer any copied text that was hidden if invisible-flag
352       ;; is nil.
353       (if invisible-flag
354           ;; Show all hidden text within the copy.
355           (subst-char-in-region first last ?\r ?\n t)
356         ;; Remove hidden text.
357         (goto-char first)
358         (while (search-forward "\r" last t)
359           (delete-region (1- (point)) (progn (end-of-line) (point)))))
360       ;;
361       ;; If region came from a koutline, remove any characters with an
362       ;; invisible property which separate cells.
363       (if from-koutline
364           (kproperty:map
365            (function (lambda (prop) (delete-char 1))) 'invisible t))))))
366         
367 (if (or hyperb:xemacs-p hyperb:emacs19-p)
368     (fset 'hypb:mark 'mark)
369   (defun hypb:mark (inactive-p)
370     "Return this buffer's mark value as integer, or nil if no mark.
371 INACTIVE-P non-nil means return value of mark even if region is not active
372 under Emacs version 19.
373 If you are using this in an editing command, you are most likely making
374 a mistake; see the documentation of `set-mark'."
375     (mark))
376   )
377 (if hyperb:xemacs-p
378     (fset 'hypb:mark-marker 'mark-marker)
379   (defun hypb:mark-marker (inactive-p)
380     "Return this buffer's mark as a marker object, or nil if no mark.
381 INACTIVE-P is unused, it is for compatibility with Lucid Emacs'
382 version of mark-marker."
383     (mark-marker))
384   )
385
386 (defun hypb:map-sublists (func list)
387   "Applies FUNC to every atom found at any level of LIST.
388 FUNC must take two arguments, an atom and a list in which the atom is found.
389 Returns values from applications of FUNC as a list with the same
390 structure as LIST.  FUNC is therefore normally used just for its side-effects."
391   (mapcar (function
392             (lambda (elt) (if (atom elt)
393                               (funcall func elt list)
394                             (hypb:map-sublists func elt)))
395             list)))
396
397 (defun hypb:map-vector (func object)
398   "Returns list of results of application of FUNC to each element of OBJECT.
399 OBJECT should be a vector or byte-code object."
400   (if (not (or (vectorp object) (hypb:v19-byte-code-p object)))
401       (error "(hypb:map-vector): Second argument must be a vector or byte-code object."))
402   (let ((end (length object))
403         (i 0)
404         (result))
405     (while (< i end)
406       (setq result (cons (funcall func (aref object i)) result)
407             i (1+ i)))
408     (nreverse result)))
409
410 (defun hypb:mouse-help-file ()
411   "Return the full path to the Hyperbole mouse key help file."
412   (let* ((hypb-man (expand-file-name "man/" hyperb:dir))
413          (help-file (expand-file-name "hypb-mouse.txt" hypb-man)))
414     (if (or (file-exists-p help-file)
415             (file-exists-p
416              (setq help-file (expand-file-name
417                               "hypb-mouse.txt" data-directory))))
418         help-file
419       (error "(hypb:mouse-help-file): Non-existent file: \"%s\"" help-file))))
420
421 (if (or hyperb:xemacs-p hyperb:emacs19-p)
422     (fset 'hypb:push-mark 'push-mark)
423   (defun hypb:push-mark (&optional location nomsg activate-region)
424     "Set mark at LOCATION (point, by default) and push old mark on mark ring.
425 If the last global mark pushed was not in the current buffer,
426 also push LOCATION on the global mark ring.
427 Display `Mark set' unless the optional second arg NOMSG is non-nil.
428 Optional third arg ACTIVATE-REGION is ignored.
429
430 Novice Emacs Lisp programmers often try to use the mark for the wrong
431 purposes.  See the documentation of `set-mark' for more information."
432     (push-mark location nomsg))
433   )
434
435 (defun hypb:replace-match-string (regexp str newtext &optional literal)
436   "Replaces all matches for REGEXP in STR with NEWTEXT string.
437 Optional LITERAL non-nil means do a literal replacement.
438 Otherwise treat \\ in NEWTEXT string as special:
439   \\& means substitute original matched text,
440   \\N means substitute match for \(...\) number N,
441   \\\\ means insert one \\.
442 NEWTEXT may instead be a function of one argument, the string to replace in,
443 that returns a replacement string."
444   (if (not (stringp str))
445       (error "(hypb:replace-match-string): 2nd arg must be a string: %s" str))
446   (if (or (stringp newtext) (hypb:functionp newtext))
447       nil
448     (error "(hypb:replace-match-string): 3rd arg must be a string or function: %s"
449            newtext))
450   (let ((rtn-str "")
451         (start 0)
452         (special)
453         match prev-start)
454     (while (setq match (string-match regexp str start))
455       (setq prev-start start
456             start (match-end 0)
457             rtn-str
458             (concat
459               rtn-str
460               (substring str prev-start match)
461               (cond ((hypb:functionp newtext) (funcall newtext str))
462                     (literal newtext)
463                     (t (mapconcat
464                          (function
465                            (lambda (c)
466                              (if special
467                                  (progn
468                                    (setq special nil)
469                                    (cond ((eq c ?\\) "\\")
470                                          ((eq c ?&)
471                                           (substring str
472                                                      (match-beginning 0)
473                                                      (match-end 0)))
474                                          ((and (>= c ?0) (<= c ?9))
475                                           (if (> c (+ ?0 (length
476                                                            (match-data))))
477                                               ;; Invalid match num
478                                               (error "(hypb:replace-match-string) Invalid match num: %c" c)
479                                             (setq c (- c ?0))
480                                             (substring str
481                                                        (match-beginning c)
482                                                        (match-end c))))
483                                          (t (char-to-string c))))
484                                (if (eq c ?\\) (progn (setq special t) nil)
485                                  (char-to-string c)))))
486                          newtext ""))))))
487     (concat rtn-str (substring str start))))
488
489 (defun hypb:supercite-p ()
490   "Returns non-nil iff the Emacs add-on supercite package is in use."
491   (let (hook-val)
492     (if (memq t (mapcar
493                  (function
494                   (lambda (hook-var)
495                     (and (boundp hook-var)
496                          (progn (setq hook-val (symbol-value hook-var))
497                                 (cond ((listp hook-val)
498                                        (if (memq 'sc-cite-original hook-val)
499                                            t))
500                                       ((eq hook-val 'sc-cite-original)))))))
501                  '(mail-citation-hook mail-yank-hooks)))
502         t)))
503
504 ;;; Next function is copied from a copylefted function:
505 ;;; Copyright (C) 1987, 1988 Kyle E. Jones
506 (if (or hyperb:xemacs-p hyperb:emacs19-p)
507     (defun hypb:window-list-all-frames (&optional mini)
508       "Returns a list of Lisp window objects for all Emacs windows in all frames.
509 Optional first arg MINI t means include the minibuffer window
510 in the list, even if it is not active.  If MINI is neither t
511 nor nil it means to not count the minibuffer window even if it is active."
512       (let* ((first-window (next-window
513                             (previous-window (selected-window) nil t t)
514                             mini t t))
515              (windows (cons first-window nil))
516              (current-cons windows)
517              (w (next-window first-window mini t t)))
518         (while (not (eq w first-window))
519           (setq current-cons (setcdr current-cons (cons w nil)))
520           (setq w (next-window w mini t t)))
521         windows)))
522
523 ;;; Next function is copied from a copylefted function:
524 ;;; Copyright (C) 1987, 1988 Kyle E. Jones
525 (defun hypb:window-list (&optional mini)
526   "Returns a list of Lisp window objects for all Emacs windows in selected frame.
527 Optional first arg MINI t means include the minibuffer window
528 in the list, even if it is not active.  If MINI is neither t
529 nor nil it means to not count the minibuffer window even if it is active."
530   (let* ((first-window (next-window
531                         (previous-window (selected-window)) mini))
532          (windows (cons first-window nil))
533          (current-cons windows)
534          (w (next-window first-window mini)))
535     (while (not (eq w first-window))
536       (setq current-cons (setcdr current-cons (cons w nil)))
537       (setq w (next-window w mini)))
538     windows))
539
540 (defun hypb:v19-byte-code-p (obj)
541   "Return non-nil iff OBJ is an Emacs V19 byte compiled object."
542   (or (and (fboundp 'compiled-function-p) (compiled-function-p obj))
543       (and (fboundp 'byte-code-function-p) (byte-code-function-p obj))))
544
545 ;; Deprecated!? Used by OO-Browser and just defined here as a noop.
546 ;;;###autoload
547 (defun hypb:display-file-with-logo (&optional file)
548   "Display an optional text FILE with a banner prepended.
549 Without file, the banner is prepended to the current buffer."
550 )
551
552 ;;;
553 ;;; Private functions
554 ;;;
555
556 (defun hypb:oct-to-int (oct-num)
557   "Returns octal integer OCTAL-NUM converted to a decimal integer."
558   (let ((oct-str (int-to-string oct-num))
559         (dec-num 0))
560     (and (string-match "[^0-7]" oct-str)
561          (error (format "(hypb:oct-to-int): Bad octal number: %s" oct-str)))
562     (mapconcat (function
563                 (lambda (o)
564                   (setq dec-num (+ (* dec-num 8)
565                                    (if (and (>= o ?0) (<= o ?7))
566                                        (- o ?0))))))
567                oct-str "")
568     dec-num))
569
570 ;;;
571 ;;; Private variables
572 ;;;
573
574 (provide 'hypb)
575
576 ;;; hypb.el ends here