Initial Commit
[packages] / xemacs-packages / hyperbole / hpath.el
1 ;;; hpath.el --- Hyperbole support routines for handling UNIX paths.  
2
3 ;; Copyright (C) 1991-1995, 2006 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: comm, hypermedia, unix
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 ;;; Public variables
33 ;;;
34
35 (require 'mm-decode)
36
37 (defvar hpath:rfc "/anonymous@ds.internic.net:rfc/rfc%s.txt"
38   "*String to be used in the call: (hpath:rfc rfc-num)
39 to create an path to the RFC document for 'rfc-num'.")
40
41 (defvar hpath:suffixes '(".gz" ".Z")
42   "*List of filename suffixes to add or remove within (hpath:exists-p) calls.")
43
44 (defvar hpath:tmp-prefix "/tmp/remote-"
45   "*Pathname prefix to attach to remote files copied locally for use with external viewers.")
46
47 ;;;
48 ;;; Public functions
49 ;;;
50
51 (defun hpath:absolute-to (path &optional default-dirs)
52   "Returns PATH as an absolute path relative to one directory from optional DEFAULT-DIRS or 'default-directory'.
53 Returns PATH unchanged when it is not a valid path or when DEFAULT-DIRS
54 is invalid.  DEFAULT-DIRS when non-nil may be a single directory or a list of
55 directories.  The first one in which PATH is found is used."
56   (if (not (and (stringp path) (hpath:is-p path nil t)))
57       path
58     (if (not (cond ((null default-dirs)
59                     (setq default-dirs (cons default-directory nil)))
60                    ((stringp default-dirs)
61                     (setq default-dirs (cons default-dirs nil)))
62                    ((listp default-dirs))
63                    (t nil)))
64         path
65       (let ((rtn) dir)
66         (while (and default-dirs (null rtn))
67           (setq dir (expand-file-name
68                      (file-name-as-directory (car default-dirs)))
69                 rtn (expand-file-name path dir)
70                 default-dirs (cdr default-dirs))
71           (or (file-exists-p rtn) (setq rtn nil)))
72         (or rtn path)))))
73
74 (defun hpath:ange-ftp-at-p ()
75   "Returns an ange-ftp pathname that point is within or nil.
76 See the 'ange-ftp' or 'efs' Elisp packages for pathname format details.
77 Always returns nil if (hpath:ange-ftp-available-p) returns nil."
78   (if (hpath:ange-ftp-available-p)
79       (let ((user (hpath:ange-ftp-default-user))
80             path)
81         (setq path
82               (save-excursion
83                 (skip-chars-backward "^[ \t\n\"`'\(\{<")
84                 (cond
85                   ((hpath:url-at-p)
86                    (if (string-equal
87                          (buffer-substring (match-beginning 1) (match-end 1))
88                          "ftp")
89                        (concat
90                         "/"
91                         ;; user
92                         (if (match-beginning 2)
93                             (buffer-substring
94                              (match-beginning 2) (match-end 2))
95                           (concat user "@"))
96                         ;; domain
97                         (hpath:delete-trailer
98                          (buffer-substring (match-beginning 3) (match-end 3)))
99                         ":"
100                         ;; path
101                         (if (match-beginning 5)
102                             (buffer-substring (match-beginning 5)
103                                               (match-end 5))))
104                      ;; else ignore this other type of WWW path
105                      ))
106                   ;; user, domain and path
107                   ((looking-at "/?[^/:@ \t\n\^M\"`']+@[^/:@ \t\n\^M\"`']+:[^]@ \t\n\^M\"`'\)\}]*")
108                    (buffer-substring (match-beginning 0) (match-end 0)))
109                   ;; @domain and path
110                   ((looking-at "@[^/:@ \t\n\^M\"`']+:[^]@ \t\n\^M\"`'\)\}]*")
111                    (concat "/" user (buffer-substring
112                                       (match-beginning 0) (match-end 0))))
113                   ;; domain and path
114                   ((and (looking-at
115                           "/?\\(\\([^/:@ \t\n\^M\"`']+\\):[^]@:, \t\n\^M\"`'\)\}]*\\)[] \t\n\^M,.\"`'\)\}]")
116                         (setq path (buffer-substring
117                                      (match-beginning 1) (match-end 1)))
118                         (string-match "[^.]\\.[^.]"
119                                       (buffer-substring (match-beginning 2)
120                                                         (match-end 2))))
121                    (concat "/" user "@" path))
122                   ;; host and path
123                   ((and (looking-at
124                          "/\\([^/:@ \t\n\^M\"`']+:[^]@:, \t\n\^M\"`'\)\}]*\\)")
125                         (setq path (buffer-substring
126                                      (match-beginning 1) (match-end 1))))
127                    (concat "/" user "@" path))
128                   )))
129         (hpath:delete-trailer path))))
130
131 (defun hpath:ange-ftp-p (path)
132   "Returns non-nil iff PATH is an ange-ftp pathname.
133 See the 'ange-ftp' or 'efs' Elisp package for pathname format details.
134 Always returns nil if (hpath:ange-ftp-available-p) returns nil."
135   (and (stringp path)
136        (or (featurep 'ange-ftp) (featurep 'efs))
137        (let ((user (hpath:ange-ftp-default-user))
138              result)
139          (setq result
140                (cond
141                  ((hpath:url-p path)
142                   (if (string-equal
143                         (substring path (match-beginning 1) (match-end 1))
144                         "ftp")
145                       (concat
146                         "/"
147                         ;; user
148                         (if (match-beginning 2)
149                             (substring path (match-beginning 2) (match-end 2))
150                           (concat user "@"))
151                         ;; domain
152                         (hpath:delete-trailer
153                          (substring path (match-beginning 3) (match-end 3)))
154                         ":"
155                         ;; path
156                         (if (match-beginning 5)
157                             (substring path (match-beginning 5)
158                                        (match-end 5))))
159                     ;; else ignore this other type of WWW path
160                     ))
161                  ;; user, domain and path
162                  ((string-match "/?[^/:@ \t\n\^M\"`']+@[^/:@ \t\n\^M\"`']+:[^]@ \t\n\^M\"`'\)\}]*"
163                                 path)
164                   (substring path (match-beginning 0) (match-end 0)))
165                  ;; @domain and path
166                  ((string-match "@[^/:@ \t\n\^M\"`']+:[^]@ \t\n\^M\"`'\)\}]*"
167                                 path)
168                   (concat "/" user
169                           (substring path (match-beginning 0) (match-end 0))))
170                  ;; domain and path
171                  ((and (string-match
172                          "/?\\(\\([^/:@ \t\n\^M\"`']+\\):[^]@:, \t\n\^M\"`'\)\}]*\\)"
173                          path)
174                        (setq result (substring path
175                                                (match-beginning 1) (match-end 1)))
176                        (string-match "[^.]\\.[^.]"
177                                      (substring path (match-beginning 2)
178                                                 (match-end 2))))
179                   (concat "/" user "@" result))
180                  ;; host and path
181                  ((and (string-match
182                          "/\\([^/:@ \t\n\^M\"`']+:[^]@:, \t\n\^M\"`'\)\}]*\\)"
183                          path)
184                        (setq result (substring
185                                       path
186                                       (match-beginning 1) (match-end 1))))
187                   (concat "/" user "@" result))
188                  ))
189         (hpath:delete-trailer result))))
190
191 (defun hpath:at-p (&optional type non-exist)
192   "Returns delimited path or non-delimited ange-ftp path at point, if any.
193 World wide web urls are treated as non-paths so they are handled elsewhere.
194 Delimiters may be:  double quotes, open and close single quote, or
195 Texinfo file references.
196 If optional TYPE is the symbol 'file or 'directory, then only that path type is
197 accepted as a match.  Only locally reachable paths are checked for existence.
198 With optional NON-EXIST, nonexistent local paths are allowed.
199 Absolute pathnames must begin with a '/' or '~'.  Relative pathnames
200 must begin with a './' or '../' to be recognized."
201   (cond (;; Local file URLs
202          (hpath:is-p (hargs:delimited
203                       "file://localhost" "[ \t\n\^M\"\'\}]" nil t)))
204         ((hpath:ange-ftp-at-p))
205         ((hpath:www-at-p) nil)
206         ((hpath:is-p (or (hargs:delimited "\"" "\"") 
207                          ;; Filenames in Info docs
208                          (hargs:delimited "\`" "\'")
209                          ;; Filenames in TexInfo docs
210                          (hargs:delimited "@file{" "}"))
211                      type non-exist))))
212
213 (defun hpath:find (filename &optional other-window-p)
214   "Edit file FILENAME using program from hpath:find-alist if available.
215 Otherwise, switch to a buffer visiting file FILENAME, creating one if none
216 already exists.
217
218 FILENAME may start with a special prefix character which is
219 handled as follows:
220   !filename  - execute as a non-windowed program within a shell;
221   &filename  - execute as a windowed program;
222   -filename  - load as an Emacs Lisp program.
223
224 Return non-nil iff file is displayed within a buffer (not with an external
225 program)."
226   (interactive "FFind file: ")
227   (let (modifier)
228     (if (string-match hpath:prefix-regexp filename)
229         (setq modifier (aref filename 0)
230               filename (substring filename (match-end 0))))
231     (setq filename (hpath:substitute-value filename))
232     (cond (modifier (cond ((eq modifier ?!)
233                            (hact 'exec-shell-cmd filename))
234                           ((eq modifier ?&)
235                            (hact 'exec-window-cmd filename))
236                           ((eq modifier ?-)
237                            (load filename)))
238                     nil)
239           (t (let ((find-program (hpath:find-program filename)))
240                (cond ((stringp find-program)
241                       (hact 'exec-window-cmd find-program)
242                       nil)
243                      ((hypb:functionp find-program)
244                       (funcall find-program filename)
245                       nil)
246                      (t (setq filename (hpath:validate filename))
247                         (funcall (if (and other-window-p
248                                           (not (br-in-browser)))
249                                      'switch-to-buffer-other-window
250                                    'switch-to-buffer)
251                                  (find-file-noselect filename))
252                         t)))))))
253
254 (defun hpath:find-other-window (filename)
255   "Edit file FILENAME, in another window or using program from hpath:find-alist.
256 May create a new window, or reuse an existing one; see the function display-buffer.
257
258 Alternatively, FILENAME may start with a prefix character to indicate special
259 handling.  See documentation of `hpath:find' for details.
260
261 Return non-nil iff file is displayed within a buffer."
262   (interactive "FFind file in other window: ")
263   (hpath:find filename t))
264
265 (defun hpath:is-p (path &optional type non-exist)
266   "Returns PATH if PATH is a Unix path, else nil.
267 If optional TYPE is the symbol 'file or 'directory, then only that path type
268 is accepted as a match.  The existence of the path is checked only for
269 locally reachable paths (Info paths are not checked).  Single spaces are
270 permitted in middle of existing pathnames, but not at the start or end.  Tabs
271 and newlines are converted to space before the pathname is checked, this
272 normalized path form is what is returned for PATH.  With optional NON-EXIST,
273 nonexistent local paths are allowed."
274   (let ((rtn-path path)
275         (suffix))
276     (and (stringp path)
277          ;; Path may be a link reference with other components other than a
278          ;; pathname.  These components always follow a comma, so strip them,
279          ;; if any, before checking path.
280          (if (string-match "[ \t\n\^M]*," path)
281              (setq rtn-path (concat (substring path 0 (match-beginning 0))
282                                      "%s" (substring path (match-beginning 0)))
283                    path (substring path 0 (match-beginning 0)))
284            (setq rtn-path (concat rtn-path "%s")))
285          (if (string-match hpath:prefix-regexp path)
286              (setq path (substring path (match-end 0)))
287            t)
288          (not (or (string= path "")
289                   (string-match "\\`\\s \\|\\s \\'" path)))
290          ;; Convert tabs and newlines to space.
291          (setq path (hbut:key-to-label (hbut:label-to-key path)))
292          (or (not (string-match "[()]" path))
293              (string-match "\\`([^ \t\n\^M\)]+)[ *A-Za-z0-9]" path))
294          (if (string-match "\\${[^}]+}" path)
295              (setq path (hpath:substitute-value path))
296            t)
297          (not (string-match "[\t\n\^M\"`'{}|\\]" path))
298          (or (not (hpath:www-p path))
299              (string-match "^ftp:" path))
300          (let ((remote-path (string-match "@.+:\\|^/.+:\\|.+:/" path)))
301            (if (cond (remote-path
302                       (cond ((eq type 'file)
303                              (not (string-equal "/" (substring path -1))))
304                             ((eq type 'directory)
305                              (string-equal "/" (substring path -1)))
306                             (t)))
307                      ((or (and non-exist
308                                (or
309                                 ;; Info or ange-ftp path, so don't check for.
310                                 (string-match "[()]" path)
311                                 (hpath:ange-ftp-p path)
312                                 (setq suffix (hpath:exists-p path t))
313                                 ;; Don't allow spaces in non-existent
314                                 ;; pathnames.
315                                 (not (string-match " " path))))
316                           (setq suffix (hpath:exists-p path t)))
317                       (cond ((eq type 'file)
318                              (not (file-directory-p path)))
319                             ((eq type 'directory)
320                              (file-directory-p path))
321                             (t)))
322                      )
323                ;; Return path if non-nil return value
324                (if (stringp suffix) ;; suffix could = t, which we ignore
325                    (if (string-match
326                         (concat (regexp-quote suffix) "%s") rtn-path)
327                        ;; remove suffix
328                        (concat (substring rtn-path 0 (match-beginning 0))
329                                (substring rtn-path (match-end 0)))
330                      ;; add suffix
331                      (format rtn-path suffix))
332                  (format rtn-path "")))))))
333
334 ;; Used by OO-Browser.
335 (defun hpath:push-tag-mark ()
336   "Add a tag return marker at point if within a programming language file buffer.
337 Is a no-op if the function `push-tag-mark' is not available."
338   (if (and buffer-file-name
339            comment-start
340            (fboundp 'push-tag-mark)
341            (not (memq last-command
342                       '(find-tag find-tag-other-window tags-loop-continue))))
343       ;; push old position
344       (push-tag-mark)))
345
346 (defun hpath:relative-to (path &optional default-dir)
347   "Returns PATH relative to optional DEFAULT-DIR or 'default-directory'.
348 Returns PATH unchanged when it is not a valid path."
349   (if (not (and (stringp path) (hpath:is-p path)))
350       path
351     (setq default-dir
352           (expand-file-name
353            (file-name-as-directory (or default-dir default-directory)))
354           path (expand-file-name path))
355     (and path default-dir
356          (if (string-equal "/" default-dir)
357              path
358            (let ((end-dir (min (length path) (length default-dir))))
359              (cond
360               ((string-equal (substring path 0 end-dir) default-dir)
361                (concat "./" (substring path end-dir)))
362               ((progn (setq default-dir (file-name-directory (directory-file-name default-dir))
363                             end-dir (min (length path) (length default-dir)))
364                       (string-equal (substring path 0 end-dir) default-dir))
365                (concat "../" (substring path end-dir)))
366               ((progn (setq default-dir (file-name-directory (directory-file-name default-dir))
367                             end-dir (min (length path) (length default-dir)))
368                       (string-equal (substring path 0 end-dir) default-dir))
369                (concat "../../" (substring path end-dir)))
370               (t path)))))))
371
372 (defun hpath:rfc (rfc-num)
373   "Return pathname to textual rfc document indexed by RFC-NUM.
374 See the documentation of the 'hpath:rfc' variable."
375   (format hpath:rfc rfc-num))
376
377 (defun hpath:substitute-value (path)
378   "Substitutes matching value for Emacs Lisp variables and environment variables in PATH.
379 Returns path with variable values substituted."
380   (substitute-in-file-name
381     (hypb:replace-match-string
382       "\\${[^}]+}"
383       path
384       (function
385         (lambda (str)
386           (let* ((var-group (substring path match start))
387                  (var-name (substring path (+ match 2) (1- start)))
388                  (rest-of-path (substring path start))
389                  (sym (intern-soft var-name)))
390             (if (file-name-absolute-p rest-of-path)
391                 (setq rest-of-path (substring rest-of-path 1)))
392             (if (and sym (boundp sym))
393                 (directory-file-name
394                  (hpath:substitute-dir var-name rest-of-path))
395               var-group))))
396       t)))
397
398 (defun hpath:substitute-var (path)
399   "Replaces up to one match in PATH with first matching variable from 'hpath:variables'."
400   (if (not (and (stringp path) (string-match "/" path) (hpath:is-p path)))
401       path
402     (setq path (hpath:symlink-referent path))
403     (let ((new-path)
404           (vars hpath:variables)          
405           result var val)
406       (while (and vars (null new-path))
407         (setq var (car vars) vars (cdr vars))
408         (if (boundp var)
409             (progn (setq val (symbol-value var))
410                    (cond ((stringp val)
411                           (if (setq result
412                                     (hpath:substitute-var-name var val path))
413                               (setq new-path result)))
414                          ((null val))
415                          ((listp val)
416                           (while (and val (null new-path))
417                             (if (setq result
418                                     (hpath:substitute-var-name var (car val) path))
419                                 (setq new-path result))
420                             (setq val (cdr val))))
421                          (t (error "(hpath:substitute-var): '%s' has invalid value for hpath:variables" var))))))
422       (or new-path path)
423       )))
424
425 ;;
426 ;; The following function recursively resolves all UNIX links to their
427 ;; final referents.
428 ;; Works with Apollo's variant and other strange links like:
429 ;; /usr/local -> $(SERVER_LOCAL)/usr/local, /usr/bin ->
430 ;; ../$(SYSTYPE)/usr/bin and /tmp -> `node_data/tmp.  It also handles
431 ;; relative links properly as in /usr/local/emacs -> gnu/emacs which must
432 ;; be resolved relative to the '/usr/local' directory.
433 ;; It will fail on Apollos if the '../' notation is used to move just
434 ;; above the '/' directory level.  This is fairly uncommon and so the
435 ;; problem has not been fixed.
436 ;;
437 (defun hpath:symlink-referent (linkname)
438   "Returns expanded file or directory referent of LINKNAME.
439 LINKNAME should not end with a directory delimiter.
440 Returns nil if LINKNAME is not a string.
441 Returns LINKNAME unchanged if it is not a symbolic link but is a pathname."
442   (if (stringp linkname)
443       (or (file-symlink-p linkname) linkname)))
444
445 (defun hpath:symlink-expand (referent dirname)
446   "Returns expanded file or directory REFERENT relative to DIRNAME."
447   (let ((var-link)
448         (dir dirname))
449     (while (string-match "\\$(\\([^\)]*\\))" referent)
450       (setq var-link (getenv (substring referent (match-beginning 1)
451                                         (match-end 1)))
452             referent (concat (substring referent 0 (match-beginning 0))
453                              var-link
454                              (substring referent (match-end 0)))))
455     ;; If referent is not an absolute path
456     (let ((nd-abbrev (string-match "`node_data" referent)))
457       (if (and nd-abbrev (= nd-abbrev 0))
458           (setq referent (concat
459                            ;; Prepend node name given in dirname, if any
460                            (and (string-match "^//[^/]+" dirname)
461                                 (substring dirname 0 (match-end 0)))
462                            "/sys/" (substring referent 1)))))
463     (while (string-match "\\(^\\|/\\)\\.\\.\\(/\\|$\\)" referent)
464       ;; Match to "//.." or "/.." at the start of link referent
465       (while (string-match "^\\(//\\.\\.\\|/\\.\\.\\)\\(/\\|$\\)" referent)
466         (setq referent (substring referent (match-end 1))))
467       ;; Match to "../" or ".." at the start of link referent
468       (while (string-match "^\\.\\.\\(/\\|$\\)" referent)
469         (setq dir (file-name-directory (directory-file-name dir))
470               referent (concat dir (substring referent (match-end 0)))))
471       ;; Match to rest of "../" in link referent
472       (while (string-match "[^/]+/\\.\\./" referent)
473         (setq referent (concat (substring referent 0 (match-beginning 0))
474                                (substring referent (match-end 0))))))
475     (and (/= (aref referent 0) ?~)
476          (/= (aref referent 0) ?/)
477          (setq referent (expand-file-name referent dirname))))
478   referent)
479
480 (defun hpath:validate (path)
481   "Returns PATH if PATH is a valid, readable path, else signals error.
482 Info and ange-ftp remote pathnames are considered readable without any
483 validation checks.
484 Default-directory should be equal to current Hyperbole button source
485 directory when called, so that PATH is expanded relative to it." 
486   (cond ((not (stringp path))
487          (error "(hpath:validate): \"%s\" is not a pathname." path))
488         ((or (string-match "[()]" path) (hpath:ange-ftp-p path))
489          ;; info or ange-ftp path, so don't validate
490          path)
491         ((if (not (hpath:www-p path))
492              ;; Otherwise, must not be a WWW link ref and must be a readable
493              ;; path.
494              (let ((return-path (hpath:exists-p path)))
495                (and return-path (file-readable-p return-path)
496                     return-path))))
497         (t (error "(hpath:validate): \"%s\" is not readable." path))))
498
499 (defun hpath:url-at-p ()
500   "Return world-wide-web universal resource locator (url) that point immediately precedes or nil.
501 Use buffer-substring with match-beginning and match-end on the following
502 groupings:
503   1 = access protocol
504   2 = optional username
505   3 = host and domain to connect to
506   4 = optional port number to use
507   5 = pathname to access."
508   ;; WWW URL format:  <protocol>:/[<user>@]<domain>[:<port>]/<path>
509   ;;             or   <protocol>://[<user>@]<domain>[:<port>]<path>
510   ;; Avoid [a-z]:/path patterns since these may be disk paths on OS/2, DOS or
511   ;; Windows.
512   (if (looking-at "\\([a-zA-Z][a-zA-Z]+\\)://?\\([^@/: \t\n\^M]+@\\)?\\([^/:@ \t\n\^M\"`']+\\)\\(:[0-9]+\\)?\\([/~][^]@ \t\n\^M\"`'\)\}>]*\\)?")
513       (save-excursion
514         (goto-char (match-end 0))
515         (skip-chars-backward ".?#!*()")
516         (buffer-substring (match-beginning 0) (point)))))
517
518 (defun hpath:url-p (obj)
519   "Return t if OBJ is a world-wide-web universal resource locator (url) string, else nil.
520 Use string-match with match-beginning and match-end on the following groupings:
521   1 = access protocol
522   2 = optional username
523   3 = host and domain to connect to
524   4 = optional port number to use
525   5 = pathname to access."
526   ;; WWW URL format:  <protocol>:/[<user>@]<domain>[:<port>]/<path>
527   ;;             or   <protocol>://[<user>@]<domain>[:<port>]<path>
528   ;; Avoid [a-z]:/path patterns since these may be disk paths on OS/2, DOS or
529   ;; Windows.
530   (and (stringp obj)
531        (string-match "\\`<?\\([a-zA-Z][a-zA-Z]+\\)://?\\([^@/: \t\n\^M]+@\\)?\\([^/:@ \t\n\^M\"`']+\\)\\(:[0-9]+\\)?\\([/~][^]@ \t\n\^M\"`'\)\}>]*\\)?>?\\'"
532                      obj)
533        t))
534
535 (defun hpath:www-at-p (&optional include-start-and-end-p)
536   "Returns a world-wide-web link reference that point is within or nil.
537 With optional INCLUDE-START-AND-END-P non-nil, returns list of:
538   (link-string begin-position end-position)."
539   (save-excursion
540     (skip-chars-backward "^[ \t\n\"`'\(\{<")
541     (cond ((not include-start-and-end-p)
542            (hpath:url-at-p))
543           ((hpath:url-at-p)
544            (list (buffer-substring (match-beginning 0) (match-end 0))
545                  (match-beginning 0)
546                  (match-end 0))))))
547
548 (defun hpath:www-p (path)
549   "Returns non-nil iff PATH is a world-wide-web link reference."
550   (and (stringp path) (hpath:url-p path) path))
551
552 ;;;
553 ;;; Private functions
554 ;;;
555
556 (defun hpath:ange-ftp-available-p ()
557   "Return t if the ange-ftp or efs package is available, nil otherwise.
558 Either the package must have been loaded already or under versions of Emacs
559 19, it must be set for autoloading via 'file-name-handler-alist'."
560   (or (featurep 'ange-ftp) (featurep 'efs)
561       (and (boundp 'file-name-handler-alist) ; v19
562            (or (rassq 'ange-ftp-hook-function file-name-handler-alist)
563                (rassq 'efs-file-handler-function file-name-handler-alist))
564            t)))
565
566
567
568 (defun hpath:ange-ftp-default-user ()
569   "Return default user account for remote file access with ange-ftp or efs.
570 Returns \"anonymous\" if neither ange-ftp-default-user nor efs-default-user
571 is set."
572   (cond ((and (boundp 'ange-ftp-default-user)
573               (stringp ange-ftp-default-user))
574          ange-ftp-default-user)
575         ((and (boundp 'efs-default-user)
576               (stringp efs-default-user))
577          efs-default-user)
578         (t "anonymous")))
579
580 (defun hpath:delete-trailer (string)
581   "Return string minus any trailing .?#!*() characters."
582   (save-match-data
583     (if (and (stringp string) (> (length string) 0)
584              (string-match "[.?#!*()]+\\'" string))
585         (substring string 0 (match-beginning 0))
586       string)))
587
588 (defun hpath:exists-p (path &optional suffix-flag)
589   "Return PATH if it exists.  (This does not mean you can read it.)
590 If PATH exists with or without a suffix from hpath:suffixes, then that
591 pathname is returned.
592
593 With optional SUFFIX-FLAG and PATH exists, return suffix added or removed
594 from path or t."
595   (let ((return-path)
596         (suffix) suffixes)
597     (if (file-exists-p path)
598         (setq return-path path)
599       (setq suffixes hpath:suffixes)
600       (while suffixes
601         (setq suffix (car suffixes))
602         (if (string-match (concat (regexp-quote suffix) "\\'") path)
603             ;; Remove suffix
604             (setq return-path (substring path 0 (match-beginning 0)))
605           ;; Add suffix
606           (setq return-path (concat path suffix)))
607         (if (file-exists-p return-path)
608             (setq suffixes nil);; found a match
609           (setq suffix nil
610                 suffixes (cdr suffixes)
611                 return-path nil))))
612     (if return-path
613         (if suffix-flag
614             (or suffix t)
615           return-path))))
616
617 (defun hpath:find-file-mailcap (file-name)
618   "Find command to view FILE-NAME according to the mailcap file."
619   (mailcap-parse-mailcaps)
620   (let (mime-type method)
621     (if (and (string-match "\\.[^\\.]+$" file-name)
622              (setq mime-type
623                    (mailcap-extension-to-mime
624                     (match-string 0 file-name)))
625              (stringp
626               (setq method
627                     (cdr (assoc 'viewer
628                                 (car (mailcap-mime-info mime-type
629                                                         'all)))))))
630         (mm-mailcap-command method file-name nil))))
631
632 (defun hpath:find-program (filename)
633   "Return shell or Lisp command to execute to display FILENAME or nil.
634 Return nil if FILENAME is a directory name. If there is a mime viewer
635 for the file it is used.  See also documentation for
636 'hpath:find-alist' and 'hpath:display-alist'."
637   (let ((cmd))
638     (cond ((and (stringp filename) (file-directory-p filename))
639            nil)
640           ((setq cmd (hpath:find-file-mailcap filename)) cmd)
641           ((stringp (setq cmd (hpath:match filename hpath:find-alist)))
642            (let ((orig-path filename))
643              ;; If filename is a remote path, we have to copy it to a
644              ;; temporary local file and then display that.
645              (if (hpath:ange-ftp-p filename)
646                  (copy-file orig-path
647                             (setq filename
648                                   (concat hpath:tmp-prefix
649                                           (file-name-nondirectory orig-path)))
650                             t t))
651              ;;
652              ;; Permit %s substitution of filename within program.
653              (if (string-match "[^%]%s" cmd)
654                  (format cmd filename)
655                (concat cmd " " filename))))
656           ((null cmd)
657            (hpath:match filename hpath:display-alist))
658           (t cmd))))
659
660 (defun hpath:match (filename regexp-alist)
661   "If FILENAME matches the car of any element in REGEXP-ALIST, return its cdr.
662 REGEXP-ALIST elements must be of the form (<filename-regexp>
663 . <command-to-display-file>).  <command-to-display-file> may be a string
664 representing an external window-system command to run or it may be a Lisp
665 function to call with FILENAME as its single argument."
666   (let ((cmd)
667         elt)
668     (while (and (not cmd) regexp-alist)
669       (if (string-match (car (setq elt (car regexp-alist))) filename)
670           (setq cmd (cdr elt)))
671       (setq regexp-alist (cdr regexp-alist)))
672     cmd))
673
674 (defun hpath:substitute-dir (var-name rest-of-path)
675   "Returns a dir for VAR-NAME using REST-OF-PATH to find match or triggers an error when no match.
676 VAR-NAME's value may be a directory or a list of directories.  If it is a
677 list, the first directory prepended to REST-OF-PATH which produces a valid
678 local pathname is returned."
679   (let (sym val)
680     (cond ((not (stringp var-name))
681            (error "(hpath:substitute-dir): VAR-NAME arg, '%s', must be a string" var-name))
682           ((not (and (setq sym (intern-soft var-name))
683                      (boundp sym)))
684            (error "(hpath:substitute-dir): VAR-NAME arg, \"%s\", is not a bound variable"
685                   var-name))
686           ((stringp (setq val (symbol-value sym)))
687            (if (hpath:validate (expand-file-name rest-of-path val))
688                val))
689           ((listp val)
690            (let ((dir))
691              (while (and val (not dir))
692                (setq dir (car val) val (cdr val))
693                (or (and (stringp dir)
694                         (file-name-absolute-p dir)
695                         (file-readable-p (expand-file-name rest-of-path dir)))
696                    (setq dir nil)))
697              (if dir (hpath:validate (directory-file-name dir))
698                (error "(hpath:substitute-dir): Can't find match for \"%s\""
699                       (concat "${" var-name "}/" rest-of-path))
700                )))
701           (t (error "(hpath:substitute-dir): Value of VAR-NAME, \"%s\", must be a string or list" var-name))
702           )))
703
704 (defun hpath:substitute-var-name (var-symbol var-dir-val path)
705   "Replaces with VAR-SYMBOL any occurrences of VAR-DIR-VAL in PATH.
706 Replacement is done iff VAR-DIR-VAL is an absolute path.
707 If PATH is modified, returns PATH, otherwise returns nil."
708   (if (and (stringp var-dir-val) (file-name-absolute-p var-dir-val))
709       (let ((new-path (hypb:replace-match-string
710                         (regexp-quote (file-name-as-directory
711                                         (or var-dir-val default-directory)))
712                         path (concat "${" (symbol-name var-symbol) "}/")
713                         t)))
714         (if (equal new-path path) nil new-path))))
715
716
717 ;;;
718 ;;; Private variables
719 ;;;
720
721
722 (defvar hpath:prefix-regexp "\\`[-!&][ ]*"
723   "Regexp matching command characters which may precede a pathname.
724 These are used to indicate how to display or execute the pathname.
725   - means evaluate it as Emacs Lisp;
726   ! means execute it as a shell script
727   & means run it under the current window system.")
728
729 (provide 'hpath)
730
731 ;;; hpath.el ends here