Initial Commit
[packages] / xemacs-packages / net-utils / shadowfile.el
1 ;;; shadowfile.el --- automatic file copying for Emacs 19
2
3 ;; Copyright (C) 1993, 1994 Free Software Foundation, Inc.
4
5 ;; Author: Boris Goldowsky <boris@gnu.ai.mit.edu>
6 ;; Keywords: comm
7
8 ;; This file is part of XEmacs.
9
10 ;; XEmacs is free software; you can redistribute it and/or modify it
11 ;; 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 ;; XEmacs is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 ;; General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
22 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
23 ;; 02111-1307, USA.
24
25 ;; LCD Archive Entry:
26 ;; shadowfile|Boris Goldowsky|boris@gnu.ai.mit.edu|
27 ;; Helps you keep identical copies of files in multiple places.|
28 ;; $Date: 2007-03-06 14:03:00 $ |$Revision: 1.3 $|~/misc/shadowfile.el.Z|
29
30 ;;; Synched up with: FSF 19.30.
31
32 ;; Commentary:
33
34 ;;  This package helps you to keep identical copies of files in more than one
35 ;;  place - possibly on different machines.  When you save a file, it checks
36 ;;  whether it is on the list of files with "shadows", and if so, it tries to
37 ;;  copy it when you exit emacs (or use the shadow-copy-files command).
38
39 ;; Installation & Use:
40
41 ;;  Put (require 'shadowfile) in your .emacs; add clusters (if necessary)
42 ;;  and file groups with shadow-define-cluster,
43 ;;  shadow-define-literal-group, and shadow-define-regexp-group (see the
44 ;;  documentation for these functions for information on how and when to
45 ;;  use them).  After doing this once, everything should be automatic.
46
47 ;;  The lists of clusters and shadows are saved in a file called .shadows,
48 ;;  so that they can be remembered from one emacs session to another, even
49 ;;  (as much as possible) if the emacs session terminates abnormally.  The
50 ;;  files needing to be copied are stored in .shadow_todo; if a file cannot
51 ;;  be copied for any reason, it will stay on the list to be tried again
52 ;;  next time.  The .shadows file should itself have shadows on all your
53 ;;  accounts so that the information in it is consistent everywhere, but
54 ;;  .shadow_todo is local information and should have no shadows.
55
56 ;;  If you do not want to copy a particular file, you can answer "no" and
57 ;;  be asked again next time you hit C-x 4 s or exit emacs.  If you do not
58 ;;  want to be asked again, use shadow-cancel, and you will not be asked
59 ;;  until you change the file and save it again.  If you do not want to
60 ;;  shadow that file ever again, you can edit it out of the .shadows
61 ;;  buffer.  Anytime you edit the .shadows buffer, you must type M-x
62 ;;  shadow-read-files to load in the new information, or your changes will
63 ;;  be overwritten!
64
65 ;; Bugs & Warnings:
66 ;;
67 ;;  - It is bad to have two emacses both running shadowfile at the same
68 ;;  time.  It tries to detect this condition, but is not always successful.
69 ;;
70 ;;  - You have to be careful not to edit a file in two locations
71 ;;  before shadowfile has had a chance to copy it; otherwise
72 ;;  "updating shadows" will overwrite one of the changed versions.
73 ;;
74 ;;  - It ought to check modification times of both files to make sure
75 ;;  it is doing the right thing.  This will have to wait until
76 ;;  file-newer-than-file-p works between machines.
77 ;;
78 ;;  - It will not make directories for you, it just fails to copy files
79 ;;  that belong in non-existent directories.
80 ;;
81 ;;  Please report any bugs to me (boris@gnu.ai.mit.edu).  Also let me know
82 ;;  if you have suggestions or would like to be informed of updates.
83
84 ;;; Code:
85
86 (provide 'shadowfile)
87 (require 'efs-auto)
88
89 ;;; I don't think this is very cool...  hope it works without the setting.
90 (setq find-file-visit-truename t)       ; makes life easier with symbolic links
91
92 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
93 ;;; Variables
94 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
95 (defgroup shadowfile nil
96   "Keep identical copies of files in more than one place."
97   :group 'files
98   :prefix "shadow")
99
100 (defcustom shadow-noquery nil
101   "*If t, always copy shadow files without asking.
102 If nil \(the default), always ask.  If not nil and not t, ask only if there
103 is no buffer currently visiting the file."
104   :type 'boolean
105   :group 'shadowfile)
106
107 (defcustom shadow-inhibit-message nil
108   "*If nonnil, do not display a message when a file needs copying."
109   :type 'boolean
110   :group 'shadowfile)
111
112 (defcustom shadow-inhibit-overload nil
113   "If nonnil, shadowfile won't redefine C-x C-c.
114 Normally it overloads the function `save-buffers-kill-emacs' to check
115 for files have been changed and need to be copied to other systems."
116   :type 'boolean
117   :group 'shadowfile)
118
119 (defcustom shadow-info-file nil
120   "File to keep shadow information in.  
121 The shadow-info-file should be shadowed to all your accounts to
122 ensure consistency.  Default: ~/.xemacs/shadows"
123   :type '(choice (const :tag "Default" nil)
124                  (file))
125   :group 'shadowfile)
126
127 (defcustom shadow-todo-file nil
128   "File to store the list of uncopied shadows in.
129 This means that if a remote system is down, or for any reason you cannot or
130 decide not to copy your shadow files at the end of one emacs session, it will
131 remember and ask you again in your next emacs session.
132 This file must NOT be shadowed to any other system, it is host-specific.
133 Default: ~/.xemacs/shadow_todo"
134   :type '(choice (const :tag "Default" nil)
135                  (file))
136   :group 'shadowfile)
137
138 ;;; The following two variables should in most cases initialize themselves
139 ;;; correctly.  They are provided as variables in case the defaults are wrong
140 ;;; on your machine \(and for efficiency).
141
142 (defvar shadow-system-name (system-name)
143   "The complete hostname of this machine.")
144
145 (defvar shadow-homedir nil
146   "Your home directory on this machine.")
147
148 ;;;
149 ;;; Internal variables whose values are stored in the info and todo files:
150 ;;;
151
152 (defvar shadow-clusters nil
153   "List of host clusters \(see shadow-define-cluster).")
154
155 (defvar shadow-literal-groups nil
156   "List of files that are shared between hosts.
157 This list contains shadow structures with literal filenames, created by
158 shadow-define-group.")
159
160 (defvar shadow-regexp-groups nil
161   "List of file types that are shared between hosts.
162 This list contains shadow structures with regexps matching filenames, 
163 created by shadow-define-regexp-group.")
164
165 ;;;
166 ;;; Other internal variables:
167 ;;;
168
169 (defvar shadow-files-to-copy nil)       ; List of files that need to
170                                         ; be copied to remote hosts.
171
172 (defvar shadow-hashtable nil)           ; for speed
173
174 (defvar shadow-info-buffer nil)         ; buf visiting shadow-info-file
175 (defvar shadow-todo-buffer nil)         ; buf visiting shadow-todo-file
176
177 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
178 ;;; Syntactic sugar; General list and string manipulation
179 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
180
181 (defmacro shadow-when (condition &rest body)
182   ;; From cl.el
183   "(shadow-when CONDITION . BODY) => evaluate BODY if CONDITION is true."
184   (` (if (not (, condition))  ()  (,@ body))))
185   
186 (defun shadow-union (a b)
187   "Add members of list A to list B
188 if they are not equal to items already in B."
189   (if (null a)
190       b
191     (if (member (car a) b)
192         (shadow-union (cdr a) b)
193       (shadow-union (cdr a) (cons (car a) b)))))
194
195 (defun shadow-find (func list)
196   "If FUNC applied to some element of LIST is nonnil, 
197 return the first such element."
198   (while (and list (not (funcall func (car list))))
199     (setq list (cdr list)))
200   (car list))
201
202 (defun shadow-remove-if (func list)
203   "Remove elements satisfying FUNC from LIST.
204 Nondestructive; actually returns a copy of the list with the elements removed."
205   (if list
206       (if (funcall func (car list))
207           (shadow-remove-if func (cdr list))
208         (cons (car list) (shadow-remove-if func (cdr list))))
209     nil))
210
211 (defun shadow-join (strings sep)
212   "Concatenate elements of the list of STRINGS with SEP between each."
213   (cond ((null strings) "")
214         ((null (cdr strings)) (car strings))
215         ((concat (car strings) " " (shadow-join (cdr strings) sep)))))
216
217 (defun shadow-regexp-superquote (string)
218   "Like regexp-quote, but includes the ^ and $ 
219 to make sure regexp matches nothing but STRING."
220   (concat "^" (regexp-quote string) "$"))
221
222 (defun shadow-suffix (prefix string)
223   "If PREFIX begins STRING, return the rest.
224 Return value is nonnil if PREFIX and STRING are string= up to the length of
225 PREFIX."
226   (let ((lp (length prefix))
227         (ls (length string)))
228     (if (and (>= ls lp)
229              (string= prefix (substring string 0 lp)))
230         (substring string lp))))
231
232 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
233 ;;; Clusters and sites
234 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
235
236 ;;; I use the term `site' to refer to a string which may be the name of a
237 ;;; cluster or a literal hostname.  All user-level commands should accept
238 ;;; either.
239
240 (defun shadow-make-cluster (name primary regexp)
241   "Creates a shadow cluster 
242 called NAME, using the PRIMARY hostname, REGEXP matching all hosts in the
243 cluster.  The variable shadow-clusters associates the names of clusters to
244 these structures. 
245    This function is for program use: to create clusters interactively, use
246 shadow-define-cluster instead."
247   (list name primary regexp))
248
249 (defmacro shadow-cluster-name (cluster)
250   "Return the name of the CLUSTER."
251   (list 'elt cluster 0))
252
253 (defmacro shadow-cluster-primary (cluster)
254   "Return the primary hostname of a CLUSTER."
255   (list 'elt cluster 1))
256
257 (defmacro shadow-cluster-regexp (cluster)
258   "Return the regexp matching hosts in a CLUSTER."
259   (list 'elt cluster 2))
260
261 (defun shadow-set-cluster (name primary regexp)
262   "Put cluster NAME on the list of clusters,
263 replacing old definition if any.  PRIMARY and REGEXP are the
264 information defining the cluster.  For interactive use, call
265 shadow-define-cluster instead."
266   (let ((rest (shadow-remove-if
267                (function (lambda (x) (equal name (car x))))
268                shadow-clusters)))
269     (setq shadow-clusters 
270           (cons (shadow-make-cluster name primary regexp)
271                 rest))))
272
273 (defmacro shadow-get-cluster (name)
274   "Return cluster named NAME, or nil."
275   (list 'assoc name 'shadow-clusters))
276
277 (defun shadow-site-primary (site)
278   "If SITE is a cluster, return primary host, otherwise return SITE."
279   (let ((c (shadow-get-cluster site)))
280     (if c
281         (shadow-cluster-primary c)
282       site)))
283
284 ;;; SITES
285
286 (defun shadow-site-cluster (site)
287   "Given a SITE \(hostname or cluster name), return the cluster
288 that it is in, or nil."
289   (or (assoc site shadow-clusters)
290       (shadow-find
291        (function (lambda (x)
292                    (string-match (shadow-cluster-regexp x)
293                                  site)))
294        shadow-clusters)))
295
296 (defun shadow-read-site ()
297   "Read a cluster name or hostname from the minibuffer."
298   (let ((ans (completing-read "Host or cluster name [RET when done]: "
299                               shadow-clusters)))
300     (if (equal "" ans)
301         nil
302       ans)))
303
304 (defun shadow-site-match (site1 site2)
305   "Nonnil iff SITE1 is or includes SITE2.  
306 Each may be a host or cluster name; if they are clusters, regexp of site1 will
307 be matched against the primary of site2."
308   (or (string-equal site1 site2) ; quick check
309       (let* ((cluster1 (shadow-get-cluster site1))
310              (primary2 (shadow-site-primary site2)))
311         (if cluster1
312             (string-match (shadow-cluster-regexp cluster1) primary2)
313           (string-equal site1 primary2)))))
314
315 (defun shadow-get-user (site)
316   "Returns the default username for a site."
317   (efs-get-user (shadow-site-primary site)))
318
319 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
320 ;;; Filename manipulation
321 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
322
323 (defun shadow-parse-fullpath (fullpath)
324   "Parse PATH into \(site user path) list,
325 or leave it alone if it already is one.  Returns nil if the argument is not a
326 full efs ftp pathname."
327   (if (listp fullpath)
328       fullpath
329     (efs-ftp-path fullpath)))
330
331 (defun shadow-parse-path (path)
332   "Parse any PATH into \(site user path) list.
333 Argument can be a simple path, full efs ftp path, or already a hup list."
334   (or (shadow-parse-fullpath path)
335       (list shadow-system-name
336             (user-login-name)
337             path)))
338
339 (defsubst shadow-make-fullpath (host user path)
340   "Make an efs style fullpath out of HOST, USER (optional), and PATH.
341 This is probably not as general as it ought to be."
342   (concat "/" 
343           (if user (concat user "@"))
344           host ":"
345           path))
346
347 (defun shadow-replace-path-component (fullpath newpath)
348   "Return FULLPATH with the pathname component changed to NEWPATH."
349   (let ((hup (shadow-parse-fullpath fullpath)))
350     (shadow-make-fullpath (nth 0 hup) (nth 1 hup) newpath)))
351
352 (defun shadow-local-file (file)
353   "If FILENAME is at this site,
354 remove /user@host part.  If refers to a different system or a different user on
355 this system, return nil."
356   (let ((hup (shadow-parse-fullpath file)))
357     (cond ((null hup) file)
358           ((and (shadow-site-match (nth 0 hup) shadow-system-name)
359                 (string-equal (nth 1 hup) (user-login-name)))
360            (nth 2 hup))
361           (t nil))))
362
363 (defun shadow-expand-cluster-in-file-name (file)
364   "If hostname part of FILE is a cluster, expand it
365 into the cluster's primary hostname.  Will return the pathname bare if it is
366 a local file."
367   (let ((hup (shadow-parse-path file)))
368     (cond ((null hup) file)
369           ((shadow-local-file hup))
370           ((shadow-make-fullpath (shadow-site-primary (nth 0 hup))
371                                  (nth 1 hup)
372                                  (nth 2 hup))))))
373
374 (defun shadow-expand-file-name (file &optional default)
375   "Expand file name and get file's true name."
376   (file-truename (expand-file-name file default)))
377
378 (defun shadow-contract-file-name (file)
379   "Simplify FILENAME
380 by replacing (when possible) home directory with ~, and hostname with cluster
381 name that includes it.  Filename should be absolute and true."
382   (let* ((hup (shadow-parse-path file))
383          (homedir (if (shadow-local-file hup)
384                       shadow-homedir
385                     (file-name-as-directory
386                      (nth 2 (shadow-parse-fullpath 
387                              (expand-file-name
388                               (shadow-make-fullpath
389                                (nth 0 hup) (nth 1 hup) "~")))))))
390          (suffix (shadow-suffix homedir (nth 2 hup)))
391          (cluster (shadow-site-cluster (nth 0 hup))))
392     (shadow-make-fullpath
393      (if cluster
394          (shadow-cluster-name cluster)
395        (nth 0 hup))
396      (nth 1 hup)
397      (if suffix 
398          (concat "~/" suffix)
399        (nth 2 hup)))))
400
401 (defun shadow-same-site (pattern file)
402   "True if the site of PATTERN and of FILE are on the same site.
403 If usernames are supplied, they must also match exactly.  PATTERN and FILE may
404 be lists of host, user, path, or efs ftp pathnames.  FILE may also be just a
405 local filename."
406   (let ((pattern-sup (shadow-parse-fullpath pattern))
407         (file-sup    (shadow-parse-path file)))
408     (and
409      (shadow-site-match (nth 0 pattern-sup) (nth 0 file-sup))
410      (or (null (nth 1 pattern-sup))
411          (string-equal (nth 1 pattern-sup) (nth 1 file-sup))))))
412
413 (defun shadow-file-match (pattern file &optional regexp)
414  "Returns t if PATTERN matches FILE.
415 If REGEXP is supplied and nonnil, the pathname part of the pattern is a regular
416 expression, otherwise it must match exactly.  The sites and usernames must
417 match---see shadow-same-site.  The pattern must be in full efs ftp format, but
418 the file can be any valid filename.  This function does not do any filename
419 expansion or contraction, you must do that yourself first."
420  (let* ((pattern-sup (shadow-parse-fullpath pattern))
421         (file-sup (shadow-parse-path file)))
422    (and (shadow-same-site pattern-sup file-sup)
423         (if regexp 
424             (string-match (nth 2 pattern-sup) (nth 2 file-sup))
425           (string-equal (nth 2 pattern-sup) (nth 2 file-sup))))))
426  
427 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
428 ;;; User-level Commands
429 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
430
431 (defun shadow-define-cluster (name)
432   "Edit \(or create) the definition of a cluster.
433 This is a group of hosts that share directories, so that copying to or from
434 one of them is sufficient to update the file on all of them.  Clusters are
435 defined by a name, the network address of a primary host \(the one we copy
436 files to), and a regular expression that matches the hostnames of all the sites
437 in the cluster."
438   (interactive (list (completing-read "Cluster name: " shadow-clusters () ())))
439   (let* ((old (shadow-get-cluster name))
440          (primary (read-string "Primary host: "
441                                (if old (shadow-cluster-primary old) 
442                                  name)))
443          (regexp   (let (try-regexp)
444                      (while (not
445                              (string-match 
446                               (setq try-regexp
447                                     (read-string 
448                                      "Regexp matching all host names: "
449                                      (if old (shadow-cluster-regexp old)
450                                        (shadow-regexp-superquote primary))))
451                               primary))
452                        (message "Regexp doesn't include the primary host!")
453                        (sit-for 2))
454                      try-regexp))
455 ;        (username (read-no-blanks-input 
456 ;                   (format "Username [default: %s]: " 
457 ;                           (shadow-get-user primary))
458 ;                   (if old (or (shadow-cluster-username old) "")
459 ;                     (user-login-name))))
460          )
461 ;    (if (string-equal "" username) (setq username nil))
462     (shadow-set-cluster name primary regexp)))
463
464 (defun shadow-define-literal-group ()
465   "Declare a single file to be shared between sites.
466 It may have different filenames on each site.  When this file is edited, the
467 new version will be copied to each of the other locations.  Sites can be
468 specific hostnames, or names of clusters \(see shadow-define-cluster)."
469   (interactive)
470   (let* ((hup (shadow-parse-fullpath 
471                (shadow-contract-file-name (buffer-file-name))))
472          (path (nth 2 hup))
473          user site group)
474     (while (setq site (shadow-read-site))
475       (setq user (read-string (format "Username [default %s]: "
476                                       (shadow-get-user site)))
477             path (read-string "Filename: " path))
478       (setq group (cons (shadow-make-fullpath site 
479                                               (if (string-equal "" user)
480                                                   (shadow-get-user site)
481                                                 user)
482                                               path)
483                         group)))
484     (setq shadow-literal-groups (cons group shadow-literal-groups)))
485   (shadow-write-info-file))
486
487 (defun shadow-define-regexp-group ()
488   "Make each of a group of files be shared between hosts.
489 Prompts for regular expression; files matching this are shared between a list
490 of sites, which are also prompted for. The filenames must be identical on all
491 hosts \(if they aren't, use shadow-define-group instead of this function).
492 Each site can be either a hostname or the name of a cluster \(see
493 shadow-define-cluster)."
494   (interactive)
495   (let ((regexp (read-string 
496                  "Filename regexp: " 
497                  (if (buffer-file-name)
498                      (shadow-regexp-superquote
499                       (nth 2
500                            (shadow-parse-path
501                             (shadow-contract-file-name
502                              (buffer-file-name))))))))
503         site sites usernames)
504     (while (setq site (shadow-read-site))
505       (setq sites (cons site sites))
506       (setq usernames 
507             (cons (read-string (format "Username for %s: " site)
508                                (shadow-get-user site))
509                   usernames)))
510     (setq shadow-regexp-groups 
511           (cons (shadow-make-group regexp sites usernames)
512                 shadow-regexp-groups))
513     (shadow-write-info-file)))
514     
515 (defun shadow-shadows ()
516   ;; Mostly for debugging.
517   "Interactive function to display shadows of a buffer."
518   (interactive)
519   (let ((msg (shadow-join (mapcar (function cdr)
520                                   (shadow-shadows-of (buffer-file-name)))
521                           " ")))
522     (message "%s"
523              (if (zerop (length msg)) 
524                  "No shadows."
525                msg))))
526
527 (defun shadow-copy-files (&optional arg)
528   "Copy all pending shadow files.
529 With prefix argument, copy all pending files without query.
530 Pending copies are stored in variable shadow-files-to-copy, and in
531 shadow-todo-file if necessary.  This function is invoked by
532 shadow-save-buffers-kill-emacs, so it is not usually necessary to
533 call it manually."
534   (interactive "P")
535   (if (and (not shadow-files-to-copy) (interactive-p))
536       (message "No files need to be shadowed.")
537     (save-excursion
538       (map-y-or-n-p (function
539                      (lambda (pair)
540                        (or arg shadow-noquery
541                            (format "Copy shadow file %s? " (cdr pair)))))
542                     (function shadow-copy-file)
543                     shadow-files-to-copy
544                     '("shadow" "shadows" "copy"))
545       (shadow-write-todo-file t))))
546
547 (defun shadow-cancel ()
548   "Cancel the instruction to copy some files.
549 Prompts for which copy operations to cancel.  You will not be asked to copy
550 them again, unless you make more changes to the files.  To cancel a shadow
551 permanently, remove the group from shadow-literal-groups or
552 shadow-regexp-groups."
553   (interactive)
554   (map-y-or-n-p (function (lambda (pair)
555                             (format "Cancel copying %s to %s? " 
556                                     (car pair) (cdr pair))))
557                 (function (lambda (pair) 
558                             (shadow-remove-from-todo pair)))
559                 shadow-files-to-copy
560                 '("shadow" "shadows" "cancel copy"))
561   (message "There are %d shadows to be updated." 
562            (length shadow-files-to-copy))
563   (shadow-write-todo-file))
564
565 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
566 ;;; Internal functions
567 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
568
569 (defun shadow-make-group (regexp sites usernames)
570   "Makes a description of a file group---
571 actually a list of regexp efs ftp file names---from REGEXP \(name of file to
572 be shadowed), list of SITES, and corresponding list of USERNAMES for each
573 site."
574   (if sites
575       (cons (shadow-make-fullpath (car sites) (car usernames) regexp)
576             (shadow-make-group regexp (cdr sites) (cdr usernames)))
577     nil))
578
579 (defun shadow-copy-file (s)
580   "Copy one shadow file."
581   (let* ((buffer 
582           (cond ((get-file-buffer 
583                   (abbreviate-file-name (shadow-expand-file-name (car s)))))
584                 ((not (file-readable-p (car s)))
585                  (if (y-or-n-p
586                       (format "Cannot find file %s--cancel copy request?"
587                               (car s)))
588                      (shadow-remove-from-todo s))
589                  nil)
590                 ((or (eq t shadow-noquery)
591                      (y-or-n-p 
592                       (format "No buffer for %s -- update shadow anyway?"
593                               (car s))))
594                  (find-file-noselect (car s)))))
595          (to (shadow-expand-cluster-in-file-name (cdr s))))
596     (shadow-when buffer
597       (set-buffer buffer)
598       (save-restriction
599         (widen)
600         (condition-case nil
601             (progn
602               (write-region (point-min) (point-max) to)
603               (shadow-remove-from-todo s))
604           (error (message "Shadow %s not updated!" (cdr s))))))))
605
606 (defun shadow-shadows-of (file)
607   "Returns copy operations needed to update FILE.
608 Filename should have clusters expanded, but otherwise can have any format.  
609 Return value is a list of dotted pairs like \(from . to), where from
610 and to are absolute file names."
611   (or (symbol-value (intern-soft file shadow-hashtable))
612       (let* ((absolute-file (shadow-expand-file-name
613                              (or (shadow-local-file file) file)
614                              shadow-homedir))
615              (canonical-file (shadow-contract-file-name absolute-file))
616              (shadows 
617               (mapcar (function (lambda (shadow)
618                                   (cons absolute-file shadow)))
619                       (append
620                        (shadow-shadows-of-1
621                         canonical-file shadow-literal-groups nil)
622                        (shadow-shadows-of-1
623                         canonical-file shadow-regexp-groups t)))))
624         (set (intern file shadow-hashtable) shadows))))
625
626 (defun shadow-shadows-of-1 (file groups regexp)
627   "Return list of FILE's shadows in GROUPS, 
628 which are considered as regular expressions if third arg REGEXP is true."
629   (if groups
630       (let ((nonmatching
631              (shadow-remove-if 
632               (function (lambda (x) (shadow-file-match x file regexp)))
633               (car groups))))
634         (append (cond ((equal nonmatching (car groups)) nil)
635                       (regexp 
636                        (let ((realpath (nth 2 (shadow-parse-fullpath file))))
637                          (mapcar 
638                           (function 
639                            (lambda (x) 
640                              (shadow-replace-path-component x realpath)))
641                           nonmatching)))
642                       (t nonmatching))
643                 (shadow-shadows-of-1 file (cdr groups) regexp)))))
644
645 (defun shadow-add-to-todo ()
646   "If current buffer has shadows, add them to the list
647 of files needing to be copied."
648   (let ((shadows (shadow-shadows-of 
649                   (shadow-expand-file-name 
650                    (buffer-file-name (current-buffer))))))
651     (shadow-when shadows
652       (setq shadow-files-to-copy
653             (shadow-union shadows shadow-files-to-copy))
654       (shadow-when (not shadow-inhibit-message)
655         (message "%s" (substitute-command-keys
656                        "Use \\[shadow-copy-files] to update shadows."))
657         (sit-for 1))
658       (shadow-write-todo-file)))
659   nil)     ; Return nil for write-file-hooks
660
661 (defun shadow-remove-from-todo (pair)
662   "Remove PAIR from shadow-files-to-copy.
663 PAIR must be (eq to) one of the elements of that list."
664   (setq shadow-files-to-copy 
665         (shadow-remove-if (function (lambda (s) (eq s pair)))
666                           shadow-files-to-copy)))
667
668 (defun shadow-read-files ()
669   "Visits and loads shadow-info-file and shadow-todo-file,
670 thus restoring shadowfile's state from your last emacs session.
671 Returns t unless files were locked; then returns nil."
672   (interactive)
673   (if (and (fboundp 'file-locked-p)
674            (or (stringp (file-locked-p shadow-info-file))
675                (stringp (file-locked-p shadow-todo-file))))
676       (progn
677         (message "Shadowfile is running in another emacs; can't have two.")
678         (beep)
679         (sit-for 3)
680         nil)
681     (save-excursion
682       (shadow-when shadow-info-file
683         (set-buffer (setq shadow-info-buffer
684                           (find-file-noselect shadow-info-file)))
685         (shadow-when (and (not (buffer-modified-p))
686                           (file-newer-than-file-p (make-auto-save-file-name)
687                                                   shadow-info-file))
688           (erase-buffer)
689           (message "Data recovered from %s." 
690                    (car (insert-file-contents (make-auto-save-file-name))))
691           (sit-for 1))
692         (eval-current-buffer))
693       (shadow-when shadow-todo-file
694         (set-buffer (setq shadow-todo-buffer 
695                           (find-file-noselect shadow-todo-file)))
696         (shadow-when (and (not (buffer-modified-p))
697                           (file-newer-than-file-p (make-auto-save-file-name)
698                                                   shadow-todo-file))
699           (erase-buffer)
700           (message "Data recovered from %s." 
701                    (car (insert-file-contents (make-auto-save-file-name))))
702           (sit-for 1))
703         (eval-current-buffer nil))
704       (shadow-invalidate-hashtable))
705     t))
706
707 (defun shadow-write-info-file ()
708   "Write out information to shadow-info-file.
709 Also clears shadow-hashtable, since when there are new shadows defined, the old
710 hashtable info is invalid."
711   (shadow-invalidate-hashtable)
712   (if shadow-info-file
713       (save-excursion
714         (or (buffer-live-p shadow-info-buffer)
715             (setq shadow-info-buffer (find-file-noselect shadow-info-file)))
716         (set-buffer shadow-info-buffer)
717         (delete-region (point-min) (point-max))
718         (shadow-insert-var 'shadow-clusters)
719         (shadow-insert-var 'shadow-literal-groups)
720         (shadow-insert-var 'shadow-regexp-groups))))
721
722 (defun shadow-write-todo-file (&optional save)
723   "Write out information to shadow-todo-file.  
724 With nonnil argument also saves the buffer."
725   (save-excursion
726     (or (buffer-live-p shadow-todo-buffer)
727         (setq shadow-todo-buffer (find-file-noselect shadow-todo-file)))
728     (set-buffer shadow-todo-buffer)
729     (delete-region (point-min) (point-max))
730     (shadow-insert-var 'shadow-files-to-copy)
731     (if save (shadow-save-todo-file))))
732
733 (defun shadow-save-todo-file ()
734   (if (and (buffer-live-p shadow-todo-buffer)
735            (buffer-modified-p shadow-todo-buffer))
736       (save-excursion
737         (set-buffer shadow-todo-buffer)
738         (condition-case nil             ; have to continue even in case of 
739             (basic-save-buffer)         ; error, otherwise kill-emacs might
740           (error                        ; not work!
741            (message "WARNING: Can't save shadow todo file; it is locked!")
742            (sit-for 1))))))
743
744 (defun shadow-invalidate-hashtable ()
745   (setq shadow-hashtable (make-vector 37 0)))
746
747 (defun shadow-insert-var (variable)
748   "Prettily insert a setq command for VARIABLE.
749 which, when later evaluated, will restore it to its current setting.
750 SYMBOL must be the name of a variable whose value is a list."
751   (let ((standard-output (current-buffer)))
752     (insert (format "(setq %s" variable))
753     (cond ((consp (eval variable))
754            (insert "\n  '(") 
755            (prin1 (car (eval variable)))
756            (let ((rest (cdr (eval variable))))
757              (while rest
758                (insert "\n    ")
759                (prin1 (car rest))
760                (setq rest (cdr rest)))
761              (insert "))\n\n")))
762           (t (insert " ")
763              (prin1 (eval variable))
764              (insert ")\n\n")))))
765
766 (defun shadow-save-buffers-kill-emacs (&optional arg)
767   "Offer to save each buffer and copy shadows, then kill this Emacs process.
768 With prefix arg, silently save all file-visiting buffers, then kill.
769
770 Extended by shadowfile to automatically save `shadow-todo-file' and
771 look for files that have been changed and need to be copied to other systems."
772   ;; This function is necessary because we need to get control and save
773   ;; the todo file /after/ saving other files, but /before/ the warning
774   ;; message about unsaved buffers (because it can get modified by the
775   ;; action of saving other buffers).  `kill-emacs-hook' is no good
776   ;; because it is not called at the correct time, and also because it is
777   ;; called when the terminal is disconnected and we cannot ask whether
778   ;; to copy files.
779   (interactive "P")
780   (shadow-save-todo-file)
781   (save-some-buffers arg t)
782   (shadow-copy-files)
783   (shadow-save-todo-file)
784   (and (or (not (memq t (mapcar (function
785                                  (lambda (buf) (and (buffer-file-name buf)
786                                                     (buffer-modified-p buf))))
787                                 (buffer-list))))
788            (yes-or-no-p "Modified buffers exist; exit anyway? "))
789        (or (not (fboundp 'process-list))
790            ;; process-list is not defined on VMS.
791            (let ((processes (process-list))
792                  active)
793              (while processes
794                (and (memq (process-status (car processes)) '(run stop open))
795                     (let ((val (process-kill-without-query (car processes))))
796                       (process-kill-without-query (car processes) val)
797                       val)
798                     (setq active t))
799                (setq processes (cdr processes)))
800              (or (not active)
801                  (yes-or-no-p "Active processes exist; kill them and exit anyway? "))))
802        (kill-emacs)))
803
804 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
805 ;;; Lucid Emacs compatibility 
806 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
807
808 ;; This is on hold until someone tells me about a working version of
809 ;; map-ynp for Lucid Emacs.
810
811 ;(shadow-when (string-match "Lucid" emacs-version)
812 ;  (require 'symlink-fix)
813 ;  (require 'efs-auto)
814 ;  (require 'map-ynp)
815 ;  (if (not (fboundp 'file-truename))
816 ;      (fset 'shadow-expand-file-name 
817 ;           (symbol-function 'symlink-expand-file-name)))
818 ;  (if (not (fboundp 'efs-ftp-name))
819 ;      (fset 'efs-ftp-name
820 ;           (symbol-function 'efs-ftp-path))))
821
822 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
823 ;;; Hook us up
824 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
825
826 ;;; File shadowing is activated at load time, unless this this file is
827 ;;; being preloaded, in which case it is added to after-init-hook.
828 ;;; Thanks to Richard Caley for this scheme.
829
830 (defun shadow-initialize ()
831   (if (null shadow-homedir)
832       (setq shadow-homedir
833             (file-name-as-directory (shadow-expand-file-name "~"))))
834   (if (null shadow-info-file)
835       (setq shadow-info-file 
836             (shadow-expand-file-name "~/.shadows")))
837   (if (null shadow-todo-file)
838       (setq shadow-todo-file 
839             (shadow-expand-file-name "~/.shadow_todo")))
840   (if (not (shadow-read-files))
841       (progn
842         (message "Shadowfile information files not found - aborting")
843         (beep)
844         (sit-for 3))
845     (shadow-when (and (not shadow-inhibit-overload)
846                       (not (fboundp 'shadow-orig-save-buffers-kill-emacs)))
847       (fset 'shadow-orig-save-buffers-kill-emacs 
848             (symbol-function 'save-buffers-kill-emacs))
849       (fset 'save-buffers-kill-emacs
850             (symbol-function 'shadow-save-buffers-kill-emacs)))
851     (add-hook 'write-file-hooks 'shadow-add-to-todo)
852     (define-key ctl-x-4-map "s" 'shadow-copy-files)))
853
854 (if noninteractive
855     (add-hook 'after-init-hook 'shadow-initialize)
856   (shadow-initialize))
857
858 ;;;Local Variables:
859 ;;;eval:(put 'shadow-when 'lisp-indent-hook 1)
860 ;;;End:
861
862 ;;; shadowfile.el ends here