]> git.rkrishnan.org Git - .emacs.d.git/blob - emacs/nxhtml/web-vcs.el
remove toolbar and menubar
[.emacs.d.git] / emacs / nxhtml / web-vcs.el
1 ;;; web-vcs.el --- Download file trees from VCS web pages
2 ;;
3 ;; Author: Lennart Borgman (lennart O borgman A gmail O com)
4 ;; Created: 2009-11-26 Thu
5 (defconst web-vcs:version "0.61") ;; Version:
6 ;; Last-Updated: 2009-12-11 Fri
7 ;; URL:
8 ;; Keywords:
9 ;; Compatibility:
10 ;;
11 ;; Features that might be required by this library:
12 ;;
13 ;;   None
14 ;;
15 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
16 ;;
17 ;;; Commentary:
18 ;;
19 ;; Update file trees within Emacs from VCS systems using information
20 ;; on their web pages.
21 ;;
22 ;; Available download commands are currently:
23 ;;
24 ;;    `web-vcs-nxhtml'
25 ;;
26 ;;
27 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;
29 ;;; Change log:
30 ;;
31 ;;
32 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
33 ;;
34 ;; This program is free software; you can redistribute it and/or
35 ;; modify it under the terms of the GNU General Public License as
36 ;; published by the Free Software Foundation; either version 3, or
37 ;; (at your option) any later version.
38 ;;
39 ;; This program is distributed in the hope that it will be useful,
40 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
41 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
42 ;; General Public License for more details.
43 ;;
44 ;; You should have received a copy of the GNU General Public License
45 ;; along with this program; see the file COPYING.  If not, write to
46 ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
47 ;; Floor, Boston, MA 02110-1301, USA.
48 ;;
49 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
50 ;;
51 ;;; Code:
52
53 (eval-when-compile (require 'cl))
54 (eval-and-compile  (require 'cus-edit))
55 (eval-and-compile  (require 'mm-decode))
56 (eval-when-compile (require 'url-http))
57
58 (require 'advice)
59 (require 'web-autoload nil t)
60 ;; (require 'url-util)
61 ;; (require 'url)
62 ;;(require 'url-parse)
63
64 (defvar web-vcs-comp-dir nil)
65
66 (defgroup web-vcs nil
67   "Customization group for web-vcs."
68   :group 'nxhtml)
69
70 (defcustom web-vcs-links-regexp
71   `(
72     (lp ;; Id
73      ;; Comment:
74      "http://www.launchpad.com/ uses this 2009-11-29 with Loggerhead 1.10 (generic?)"
75      ;; Files URL regexp:
76      ;;
77      ;; Extend this format to catch date/time too.
78      ;;
79      ;; ((patt (rx ...))
80      ;;  ;; use subexp numbers
81      ;;  (url 1)
82      ;;  (time 2)
83      ;;  (rev 3))
84
85      ((time 1)
86       (url 2)
87       (patt ,(rx "<td class=\"date\">"
88                  (submatch (regexp "[^<]*"))
89                  "</td>"
90                  (0+ space)
91                  "<td class=\"timedate2\">"
92                  (regexp ".+")
93                  "</td>"
94                  (*? (regexp ".\\|\n"))
95                  "href=\""
96                  (submatch (regexp ".*/download/[^\"]*"))
97                  "\"")))
98
99      ;; ,(rx "href=\""
100      ;;      (submatch (regexp ".*/download/[^\"]*"))
101      ;;      "\"")
102
103      ;; Dirs URL regexp:
104      ,(rx "href=\""
105           (submatch (regexp ".*%3A/[^\"]*/"))
106           "\"")
107      ;; File name URL part regexp:
108      "\\([^\/]*\\)$"
109      ;; Page revision regexp:
110      ,(rx "for revision"
111           (+ whitespace)
112           "<span>"
113           (submatch (+ digit))
114           "</span>")
115      ;; Release revision regexp:
116      ,(rx "/"
117           (submatch (+ digit))
118           "\"" (+ (not (any ">"))) ">"
119           (optional "Release ")
120           (+ digit) "." (+ digit) "<")
121      )
122     )
123   "Regexp patterns for matching links on a VCS web page.
124 The patterns are grouped by VCS web system type.
125
126 *Note: It is always sub match 1 from these patterns that are
127        used."
128   :type '(repeat
129           (list
130            (symbol :tag "VCS web system type specifier")
131            (string :tag "Description")
132            (regexp :tag "Files URL regexp")
133            (regexp :tag "Dirs URL regexp")
134            (regexp :tag "File name URL part regexp")
135            (regexp :tag "Page revision regexp")
136            (regexp :tag "Release revision regexp")
137            ))
138   :group 'web-vcs)
139
140 (defface web-vcs-mode-line
141   '((t (:foreground "black" :background "OrangeRed")))
142   "Mode line face during download."
143   :group 'web-vcs)
144
145 (defface web-vcs-mode-line-inactive
146   '((t (:foreground "black" :background "Orange")))
147   "Mode line face during download."
148   :group 'web-vcs)
149
150 (defface web-vcs-gold
151   '((t (:foreground "black" :background "gold")))
152   "Face for web-vcs messages."
153   :group 'web-vcs)
154
155 (defface web-vcs-red
156   '((t (:foreground "black" :background "#f86")))
157   "Face for web-vcs messages."
158   :group 'web-vcs)
159
160 (defface web-vcs-green
161   '((t (:foreground "black" :background "#8f6")))
162   "Face for web-vcs messages."
163   :group 'web-vcs)
164
165 (defface web-vcs-yellow
166   '((t (:foreground "black" :background "yellow")))
167   "Face for web-vcs messages."
168   :group 'web-vcs)
169
170 (defface web-vcs-pink
171   '((t (:foreground "black" :background "pink")))
172   "Face for web-vcs messages."
173   :group 'web-vcs)
174
175 (defcustom web-vcs-default-download-directory
176   '~/.emacs.d/
177   "Default download directory."
178   :type '(choice (const :tag "~/.emacs.d/" '~/.emacs.d/)
179                  (const :tag "Fist site-lisp in `load-path'" 'site-lisp-dir)
180                  (const :tag "Directory where `site-run-file' lives" 'site-run-dir)
181                  (string :tag "Specify directory"))
182   :group 'web-vcs)
183
184 ;;(web-vcs-default-download-directory)
185 ;;;###autoload
186 (defun web-vcs-default-download-directory ()
187   "Try to find a suitable place.
188 Considers site-start.el, site-
189 "
190   (let ((site-run-dir (when site-run-file
191                         (file-name-directory (locate-library site-run-file))))
192         (site-lisp-dir (catch 'first-site-lisp
193                          (dolist (d load-path)
194                            (let ((dir (file-name-nondirectory (directory-file-name d))))
195                              (when (string= dir "site-lisp")
196                                (throw 'first-site-lisp (file-name-as-directory d)))))))
197         )
198     (message "site-run-dir=%S site-lisp-dir=%S" site-run-dir site-lisp-dir)
199     (case web-vcs-default-download-directory
200       ('~/.emacs.d/ "~/.emacs.d/")
201       ('site-lisp-dir site-lisp-dir)
202       ('site-run-dir site-run-dir)
203       (t web-vcs-default-download-directory))
204     ))
205
206
207
208 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
209 ;;; Logging
210
211 (defcustom web-vcs-log-file "~/.emacs.d/web-vcs-log.org"
212   "Log file for web-vcs."
213   :type 'file
214   :group 'web-vcs)
215
216 ;;;###autoload
217 (defun web-vcs-log-edit ()
218   "Open log file."
219   (interactive)
220   (find-file web-vcs-log-file))
221
222 (defvar web-vcs-log-save-timer nil)
223
224 (defun web-vcs-log-save-when-idle ()
225   (when (timerp web-vcs-log-save-timer) (cancel-timer web-vcs-log-save-timer))
226   (run-with-idle-timer 0 nil 'web-vcs-log-save))
227
228 (defun web-vcs-log-save ()
229   (let ((log-buf (find-buffer-visiting web-vcs-log-file)))
230     (when (and log-buf (buffer-modified-p log-buf))
231       (with-current-buffer log-buf
232           (basic-save-buffer)))
233     log-buf))
234
235 (defun web-vcs-log-close ()
236   (let ((log-buf (web-vcs-log-save)))
237     (when log-buf
238       (kill-buffer log-buf))))
239
240 ;; Fix-me: Add some package descriptor to log
241 (defun web-vcs-log (url dl-file msg)
242   (unless (file-exists-p web-vcs-log-file)
243     (let ((dir (file-name-directory web-vcs-log-file)))
244       (unless (file-directory-p dir)
245         (make-directory dir))))
246   (with-current-buffer (find-file-noselect web-vcs-log-file)
247     (setq buffer-save-without-query t)
248     (web-vcs-log-save-when-idle)
249     (save-restriction
250       (widen)
251       (let ((today-entries (format-time-string "* %Y-%m-%d"))
252             (now (format-time-string "%H:%M:%S GMT" nil t)))
253         (goto-char (point-max))
254         (unless (re-search-backward (concat "^" today-entries) nil t)
255           (goto-char (point-max))
256           (insert "\n" today-entries "\n"))
257         (goto-char (point-max))
258         (when url
259           (insert "** Downloading file " now "\n"
260                   (format "   file [[file:%s][%s]]\n   from %s\n" dl-file dl-file url)
261                   ))
262         (cond
263          ((stringp msg)
264           (goto-char (point-max))
265           (insert msg "\n"))
266          (msg (basic-save-buffer)))))))
267
268
269
270 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
271 ;;; Finding and downloading files
272
273 ;;;###autoload
274 (defun web-vcs-get-files-from-root (web-vcs url dl-dir)
275   "Download a file tree from VCS system using the web interface.
276 Use WEB-VCS entry in variable `web-vcs-links-regexp' to download
277 files via http from URL to directory DL-DIR.
278
279 Show URL first and offer to visit the page.  That page will give
280 you information about version control system \(VCS) system used
281 etc."
282   (unless (web-vcs-contains-moved-files dl-dir)
283     (when (if (not (y-or-n-p (concat "Download files from \"" url "\".\n"
284                                      "You can see on that page which files will be downloaded.\n\n"
285                                      "Visit that page before downloading? ")))
286               t
287             (browse-url url)
288             (if (y-or-n-p "Start downloading? ")
289                 t
290               (message "Aborted")
291               nil))
292       (message "")
293       (web-vcs-get-files-on-page web-vcs url t (file-name-as-directory dl-dir) nil)
294       t)))
295
296 (defun web-vcs-get-files-on-page (web-vcs url recursive dl-dir test)
297   "Download files listed by WEB-VCS on web page URL.
298 WEB-VCS is a specifier in `web-vcs-links-regexp'.
299
300 If RECURSIVE go into sub folders on the web page and download
301 files from them too.
302
303 Place the files under DL-DIR.
304
305 Before downloading check if the downloaded revision already is
306 the same as the one on the web page.  This is stored in the file
307 web-vcs-revision.txt.  After downloading update this file.
308
309 If TEST is non-nil then do not download, just list the files."
310   (unless (string= dl-dir (file-name-as-directory (expand-file-name dl-dir)))
311     (error "Download dir dl-dir=%S must be a full directory path" dl-dir))
312   (catch 'command-level
313     (when (web-vcs-contains-moved-files dl-dir)
314       (throw 'command-level nil))
315     (let ((vcs-rec (or (assq web-vcs web-vcs-links-regexp)
316                        (error "Does not know web-cvs %S" web-vcs)))
317           (start-time (current-time)))
318       (unless (file-directory-p dl-dir)
319         (if (yes-or-no-p (format "Directory %S does not exist, create it? "
320                                  (file-name-as-directory
321                                   (expand-file-name dl-dir))))
322             (make-directory dl-dir t)
323           (message "Can't download then")
324           (throw 'command-level nil)))
325       ;; (let ((old-win (selected-window)))
326       ;;   (unless (eq (get-buffer "*Messages*") (window-buffer old-win))
327       ;;     (switch-to-buffer-other-window "*Messages*"))
328       ;;   (goto-char (point-max))
329       ;;   (insert "\n")
330       ;;   (insert (propertize (format "\n\nWeb-Vcs Download: %S\n" url) 'face 'web-vcs-gold))
331       ;;   (insert "\n")
332       ;;   (redisplay t)
333       ;;   (set-window-point (selected-window) (point-max))
334       ;;   (select-window old-win))
335       (web-vcs-message-with-face 'web-vcs-gold "\n\nWeb-Vcs Download: %S\n" url)
336       (web-vcs-display-messages nil)
337       (let* ((rev-file (expand-file-name "web-vcs-revision.txt" dl-dir))
338              (rev-buf (find-file-noselect rev-file))
339              ;; Fix-me: Per web vcs speficier.
340              (old-rev-range (with-current-buffer rev-buf
341                               (widen)
342                               (goto-char (point-min))
343                               (when (re-search-forward (format "%s:\\(.*\\)\n" web-vcs) nil t)
344                                 ;;(buffer-substring-no-properties (point-min) (line-end-position))
345                                 ;;(match-string 1)
346                                 (cons (match-beginning 1) (match-end 1))
347                                 )))
348              (old-revision (when old-rev-range
349                              (with-current-buffer rev-buf
350                                (buffer-substring-no-properties (car old-rev-range)
351                                                                (cdr old-rev-range)))))
352              (dl-revision (web-vcs-get-revision-on-page vcs-rec url))
353              ret
354              moved)
355         (when (and old-revision (string= old-revision dl-revision))
356           (when (y-or-n-p (format "You already have revision %s.  Quit? " dl-revision))
357             (message "Aborted")
358             (kill-buffer rev-buf)
359             (throw 'command-level nil)))
360         ;; We do not have a revision number once we start download.
361         (with-current-buffer rev-buf
362           (when old-rev-range
363             (delete-region (car old-rev-range) (cdr old-rev-range))
364             (basic-save-buffer)))
365         (setq ret (web-vcs-get-files-on-page-1
366                    vcs-rec url
367                    dl-dir
368                    ""
369                    nil
370                    (if recursive 0 nil)
371                    dl-revision test))
372         (setq moved       (nth 1 ret))
373         ;; Now we have a revision number again.
374         (with-current-buffer rev-buf
375           (when (= 0 (buffer-size))
376             (insert "WEB VCS Revisions\n\n"))
377           (goto-char (point-max))
378           (unless (eolp) (insert "\n"))
379           (insert (format "%s:%s\n" web-vcs dl-revision))
380           (basic-save-buffer)
381           (kill-buffer))
382         (message "-----------------")
383         (web-vcs-message-with-face 'web-vcs-gold "Web-Vcs Download Ready: %S" url)
384         (web-vcs-message-with-face 'web-vcs-gold "  Time elapsed: %S"
385                                    (web-vcs-nice-elapsed start-time (current-time)))
386         (when (> moved 0)
387           (web-vcs-message-with-face 'web-vcs-yellow
388                                      "  %i files updated (old versions renamed to *.moved)"
389                                      moved))))))
390
391 (defun web-vcs-get-files-on-page-1 (vcs-rec url dl-root dl-relative file-mask recursive dl-revision test)
392   "Download files listed by VCS-REC on web page URL.
393 VCS-REC should be an entry like the entries in the list
394 `web-vcs-links-regexp'.
395
396 If FILE-MASK is non nil then it is used to match a file path.
397 Only matching files will be downloaded.  FILE-MASK can have two
398 forms, a regular expression or a function.
399
400 If FILE-MASK is a regular expression then each part of the path
401 may be a regular expresion \(not containing /).
402
403 If FILE-MASK is a function then this function is called in each
404 directory under DL-ROOT.  The function is called with the
405 directory as a parameter and should return a cons. The first
406 element of the cons should be a regular expression matching file
407 names in that directory that should be downloaded.  The cdr
408 should be t if subdirectories should be visited.
409
410 If RECURSIVE go into sub folders on the web page and download
411 files from them too.
412
413 Place the files under DL-DIR.
414
415 The revision on the page URL should match DL-REVISION if this is non-nil.
416
417 If TEST is non-nil then do not download, just list the files"
418   ;;(web-vcs-message-with-face 'font-lock-comment-face "web-vcs-get-files-on-page-1 %S %S %S %S" url dl-root dl-relative file-mask)
419   (let* ((files-matcher      (nth 2 vcs-rec))
420          (dirs-href-regexp   (nth 3 vcs-rec))
421          (revision-regexp    (nth 5 vcs-rec))
422          (dl-dir (file-name-as-directory (expand-file-name dl-relative dl-root)))
423          (lst-dl-relative (web-vcs-file-name-as-list dl-relative))
424          (lst-file-mask   (when (stringp file-mask) (web-vcs-file-name-as-list file-mask)))
425          ;;(url-buf (url-retrieve-synchronously url))
426          this-page-revision
427          files
428          suburls
429          (moved 0)
430          (temp-file-base (expand-file-name "web-vcs-temp-list.tmp" dl-dir))
431          temp-list-file
432          temp-list-buf
433          folder-res
434          http-sts)
435     ;; Fix-me: It looks like there is maybe a bug in url-copy-file so
436     ;; that it runs synchronously. Try to workaround the problem by
437     ;; making a new file temp file name.
438     (web-vcs-display-messages nil)
439     (unless (file-directory-p dl-dir) (make-directory dl-dir t))
440     ;;(message "TRACE: dl-dir=%S" dl-dir)
441     (setq temp-list-file (make-temp-name temp-file-base))
442     (setq temp-list-buf (web-vcs-ass-folder-cache url))
443     (unless temp-list-buf
444       ;;(setq temp-list-buf (generate-new-buffer "web-wcs-folder"))
445       ;;(web-vcs-url-copy-file-and-check url temp-list-file nil)
446       (setq folder-res (web-vcs-url-retrieve-synch url))
447       ;; (with-current-buffer temp-list-buf
448       ;;   (insert-file-contents temp-list-file))
449       (unless (memq (cdr folder-res) '(200 201))
450         (web-vcs-message-with-face 'web-vcs-red "Could not get %S" url)
451           (web-vcs-display-messages t)
452         (throw 'command-level nil)))
453     ;;(with-current-buffer temp-list-buf
454     (with-current-buffer (car folder-res)
455       ;;(delete-file temp-list-file)
456       ;;(find-file-noselect temp-list-file)
457       (when dl-revision
458         (setq this-page-revision (web-vcs-get-revision-from-url-buf vcs-rec (current-buffer) url)))
459       (when dl-revision
460         (unless (string= dl-revision this-page-revision)
461           (web-vcs-message-with-face 'web-vcs-red "Revision on %S is %S, but should be %S"
462                                      url this-page-revision dl-revision)
463           (web-vcs-display-messages t)
464           (throw 'command-level nil)))
465       ;; Find files
466       (goto-char (point-min))
467       (let ((files-href-regexp (nth 1 (assq 'patt files-matcher)))
468             (url-num           (nth 1 (assq 'url  files-matcher)))
469             (time-num          (nth 1 (assq 'time files-matcher))))
470         (while (re-search-forward files-href-regexp nil t)
471           (let ((file (match-string url-num))
472                 (time (match-string time-num)))
473             (add-to-list 'files (list file time)))))
474       ;; Find subdirs
475       (when recursive
476         (goto-char (point-min))
477         (while (re-search-forward dirs-href-regexp nil t)
478           (let ((suburl (match-string 1))
479                 (lenurl (length url)))
480             (when (and (> (length suburl) lenurl)
481                        (string= (substring suburl 0 lenurl) url))
482               (add-to-list 'suburls suburl)))))
483       (kill-buffer))
484     ;; Download files
485     ;;(message "TRACE: files=%S" files)
486     (web-vcs-download-files vcs-rec files dl-dir dl-root file-mask)
487     ;; Download subdirs
488     (when suburls
489       (dolist (suburl (reverse suburls))
490         (let* ((dl-sub-dir (substring suburl (length url)))
491                (full-dl-sub-dir (file-name-as-directory
492                                  (expand-file-name dl-sub-dir dl-dir)))
493                (rel-dl-sub-dir (file-relative-name full-dl-sub-dir dl-root)))
494           ;;(message "web-vcs-get-revision-from-url-buf dir: %S %S" file-mask rel-dl-sub-dir)
495           (when (or (not file-mask)
496                     (not (stringp file-mask))
497                     (web-vcs-match-folderwise file-mask rel-dl-sub-dir))
498             ;;(message "matched dir %S" rel-dl-sub-dir)
499             (unless (web-vcs-contains-file dl-dir full-dl-sub-dir)
500               (error "Subdir %S not in %S" dl-sub-dir dl-dir))
501             (let* ((ret (web-vcs-get-files-on-page-1 vcs-rec
502                                                      suburl
503                                                      dl-root
504                                                      rel-dl-sub-dir
505                                                      file-mask
506                                                      (1+ recursive)
507                                                      this-page-revision
508                                                      test)))
509               (setq moved (+ moved (nth 1 ret))))))))
510     (list this-page-revision moved)))
511
512 (defun web-vcs-get-missing-matching-files (web-vcs url dl-dir file-mask)
513   "Download missing files from VCS system using the web interface.
514 Use WEB-VCS entry in variable `web-vcs-links-regexp' to download
515 files via http from URL to directory DL-DIR.
516
517 Before downloading offer to visit the page from which the
518 downloading will be made.
519 "
520   (let ((vcs-rec (or (assq web-vcs web-vcs-links-regexp)
521                      (error "Does not know web-cvs %S" web-vcs))))
522     (web-vcs-get-files-on-page-1 vcs-rec url dl-dir "" file-mask 0 nil nil)))
523
524
525 ;; (web-vcs-get-files-on-page 'lp "http://bazaar.launchpad.net/%7Enxhtml/nxhtml/main/files/head%3A/" t "c:/test/temp13/" t)
526
527 (defvar web-vcs-folder-cache nil) ;; dyn var
528 (defun web-vcs-add-folder-cache (url buf)
529   (add-to-list 'web-vcs-folder-cache (list url buf)))
530 (defun web-vcs-ass-folder-cache (url)
531   (assoc url web-vcs-folder-cache))
532 (defun web-vcs-clear-folder-cache ()
533   (while web-vcs-folder-cache
534     (let ((ub (car web-vcs-folder-cache)))
535       (setq web-vcs-folder-cache (cdr web-vcs-folder-cache))
536       (kill-buffer (nth 1 ub)))))
537
538 (defun web-vcs-url-copy-file-and-check (url dl-file dest-file)
539   "Copy URL to DL-FILE.
540 Log what happened. Use DEST-FILE in the log, not DL-FILE which is
541 a temporary file."
542   (let ((http-sts nil)
543         (file-nonempty nil)
544         (fail-reason nil))
545     (when dest-file (web-vcs-log url dest-file nil))
546     (web-vcs-display-messages nil)
547     ;;(message "before url-copy-file %S" dl-file)
548     (setq http-sts (web-vcs-url-copy-file url dl-file nil t)) ;; don't overwrite, keep time
549     ;;(message "after  url-copy-file %S" dl-file)
550     (if (and (file-exists-p dl-file)
551              (setq file-nonempty (< 0 (nth 7 (file-attributes dl-file)))) ;; file size 0
552              (memq http-sts '(200 201)))
553         (when dest-file
554           (web-vcs-log nil nil "   Done.\n"))
555       (setq fail-reason
556             (cond
557              (http-sts (format "HTTP %s" http-sts))
558              (file-nonempty "File looks bad")
559              (t "Server did not respond")))
560       (unless dest-file (web-vcs-log url dl-file "TEMP FILE"))
561       (web-vcs-log nil nil (format "   *Failed:* %s\n" fail-reason))
562       ;; Requires user attention and intervention
563       (web-vcs-message-with-face 'web-vcs-red "Download failed: %s, %S" fail-reason url)
564       (web-vcs-display-messages t)
565       (message "\n")
566       (web-vcs-message-with-face 'web-vcs-yellow "Please retry what you did before!\n")
567       (throw 'command-level nil))))
568
569 (defvar web-autoload-temp-file-prefix "TEMPORARY-WEB-AUTO-LOAD-")
570 (defvar web-autoload-active-file-sub-url) ;; Dyn var, active during file download check
571 (defun web-autoload-acvtive ()
572   (and (boundp 'web-autoload-active-file-sub-url)
573        web-autoload-active-file-sub-url))
574
575 (defun web-vcs-download-files (vcs-rec files dl-dir dl-root file-mask)
576   (dolist (file (reverse files))
577     (let* ((url-file          (nth 0 file))
578            (url-file-time-str (nth 1 file))
579            ;; date-to-time assumes GMT so this is ok:
580            (url-file-time     (when url-file-time-str (date-to-time url-file-time-str)))
581            (url-file-name-regexp  (nth 4 vcs-rec))
582            (url-file-rel-name (progn
583                                 (when (string-match url-file-name-regexp url-file)
584                                   (match-string 1 url-file))))
585            (dl-file-name (expand-file-name url-file-rel-name dl-dir))
586            (dl-file-time (nth 5 (file-attributes dl-file-name)))
587            (file-rel-name (file-relative-name dl-file-name dl-root))
588            (file-name (file-name-nondirectory dl-file-name))
589            (temp-file (expand-file-name (concat web-autoload-temp-file-prefix file-name) dl-dir))
590            temp-buf)
591       (cond
592        ((and file-mask (not (web-vcs-match-folderwise file-mask file-rel-name))))
593        ((and dl-file-time
594              url-file-time
595              (progn
596                ;;(message "dl-file-time =%s" (when dl-file-time (current-time-string dl-file-time)))
597                ;;(message "url-file-time=%s" (when url-file-time (current-time-string url-file-time)))
598                ;;(message "url-file-tstr=%s" (when url-file-time url-file-time-str))
599                t)
600              (time-less-p url-file-time
601                           (time-add dl-file-time (seconds-to-time 1))))
602         (web-vcs-message-with-face 'web-vcs-green "Local file %s is newer or same age" file-rel-name))
603        ;;(test (progn (message "TEST url-file=%S" url-file) (message "TEST url-file-rel-name=%S" url-file-rel-name) (message "TEST dl-file-name=%S" dl-file-name) ))
604        (t
605         ;; Avoid trouble with temp file
606         (while (setq temp-buf (find-buffer-visiting temp-file))
607           (set-buffer-modified-p nil) (kill-buffer temp-buf))
608         (when (file-exists-p temp-file) (delete-file temp-file))
609         ;;(web-vcs-message-with-face 'font-lock-comment-face "Starting url-copy-file %S %S t t" url-file temp-file)
610         (web-vcs-url-copy-file-and-check url-file temp-file dl-file-name)
611         ;;(web-vcs-message-with-face 'font-lock-comment-face "Finished url-copy-file %S %S t t" url-file temp-file)
612         (let* ((time-after-url-copy (current-time))
613                (old-buf-open (find-buffer-visiting dl-file-name)))
614           (when (and old-buf-open (buffer-modified-p old-buf-open))
615             (save-excursion
616               (switch-to-buffer old-buf-open)
617               (when (y-or-n-p (format "Buffer %S is modified, save to make a backup? " dl-file-name))
618                 (save-buffer))))
619           (if (and dl-file-time (web-vcs-equal-files dl-file-name temp-file))
620               (progn
621                 (delete-file temp-file)
622                 (when url-file-time (set-file-times dl-file-name url-file-time))
623                 (web-vcs-message-with-face 'web-vcs-green "File %S was ok" dl-file-name))
624             (when dl-file-time
625               (let ((backup (concat dl-file-name ".moved")))
626                 (rename-file dl-file-name backup t)))
627             ;; Be paranoid and let user check here. I actually
628             ;; believe that is a very good thing here.
629             (web-vcs-be-paranoid temp-file dl-file-name file-rel-name)
630             (rename-file temp-file dl-file-name)
631             (when url-file-time (set-file-times dl-file-name url-file-time))
632             ;; (let ((buf (find-buffer-visiting dl-file-name)))
633             ;;   (when buf
634             ;;     (with-current-buffer buf
635             ;;       (message "before revert-buffer")
636             ;;       (revert-buffer nil t t)
637             ;;       (message "after revert-buffer")
638             ;;       )))
639             (if dl-file-time
640                 (web-vcs-message-with-face 'web-vcs-yellow "Updated %S" dl-file-name)
641               (web-vcs-message-with-face 'web-vcs-green "Downloaded %S" dl-file-name))
642             (when old-buf-open
643               (with-current-buffer old-buf-open
644                 (set-buffer-modified-p nil)
645                 (revert-buffer nil t t)))
646             (with-current-buffer (find-file-noselect dl-file-name)
647               (setq header-line-format
648                     (propertize (format-time-string "This file was downloaded %Y-%m-%d %H:%M")
649                                 'face 'web-vcs-green))))
650           (web-vcs-display-messages nil)
651           ;; This is both for user and remote server load.  Do not remove this.
652           (redisplay t) (sit-for (- 1.0 (float-time (time-subtract (current-time) time-after-url-copy))))
653           ;; (unless old-buf-open
654           ;;   (when old-buf
655           ;;     (kill-buffer old-buf)))
656           )))
657       (redisplay t))))
658
659 (defun web-vcs-get-revision-on-page (vcs-rec url)
660   "Get revision number using VCS-REC on page URL.
661 VCS-REC should be an entry like the entries in the list
662 `web-vcs-links-regexp'."
663   ;; url-insert-file-contents
664   (let ((url-buf (url-retrieve-synchronously url)))
665     (web-vcs-get-revision-from-url-buf vcs-rec url-buf url)))
666
667 (defun web-vcs-get-revision-from-url-buf (vcs-rec url-buf url)
668   "Get revision number using VCS-REC.
669 VCS-REC should be an entry in the list `web-vcs-links-regexp'.
670 The buffer URL-BUF should contain the content on page URL."
671   (let ((revision-regexp    (nth 5 vcs-rec)))
672     ;; Get revision number
673     (with-current-buffer url-buf
674       (goto-char (point-min))
675       (if (not (re-search-forward revision-regexp nil t))
676           (progn
677             (web-vcs-message-with-face 'web-vcs-red "Can't find revision number on %S" url)
678             (web-vcs-display-messages t)
679             (throw 'command-level nil))
680         (match-string 1)))))
681
682
683
684 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
685 ;;; Auto Download
686
687
688 ;; fix-me: To emulation-mode-map
689 ;; Fix-me: put this on better keys
690 (defvar web-vcs-paranoid-state-mode-map
691   (let ((map (make-sparse-keymap)))
692     (define-key map [(control ?c)(control ?c)] 'exit-recursive-edit)
693     (define-key map [(control ?c)(control ?n)] 'web-autoload-continue-no-stop)
694     (define-key map [(control ?c)(control ?r)] 'web-vcs-investigate-elisp-file)
695     (define-key map [(control ?c)(control ?q)] 'web-vcs-quit-auto-download)
696     map))
697
698 (defun web-vcs-quit-auto-download ()
699   "Quit download process.
700 This stops the current web autoload processing."
701   (interactive)
702   ;; Fix-me.
703   (when (y-or-n-p "Stop web autoload processing? You can resume it later. ")
704     (web-vcs-message-with-face 'web-vcs-red
705                                "Stopped autoloading in process. It will be resumed when necessary again.")
706     (web-vcs-log nil nil "User stopped autoloading")
707     (throw 'top-level 'web-autoload-stop)))
708
709 (define-minor-mode web-vcs-paranoid-state-mode
710   "Mode used temporarily during user check of downloaded file.
711 Do not turn on this yourself."
712   :lighter (concat " " (propertize "Download file check" 'face 'font-lock-warning-face))
713   :global t
714   :group 'web-vcs
715   (or (not web-vcs-paranoid-state-mode)
716       (web-autoload-acvtive)
717       (error "This mode can't be used when not downloading")))
718
719 (defcustom web-autoload-paranoid t
720   "Be paranoid and break to check each file after download."
721   :type 'boolean
722   :group 'web-vcs)
723
724 (defun web-autoload-continue-no-stop ()
725   "Continue web auto download.
726 This is used after inspecting downloaded elisp files.  Set
727 `web-autoload-paranoid' to nil before contiuning to avoid further
728 breaks to check downloaded files."
729   (interactive)
730   (setq web-autoload-paranoid nil)
731   (web-autoload-continue))
732
733 (defun web-autoload-continue ()
734   "Continue web auto download.
735 This is used after inspecting downloaded elisp files."
736   (interactive)
737   (if (< 0 (recursion-depth))
738       (exit-recursive-edit)
739     (web-autoload-byte-compile-queue)))
740
741 (defun web-vcs-be-paranoid (temp-file file-dl-name file-sub-url)
742   "Be paranoid and check FILE-DL-NAME."
743   (when (or (not (boundp 'web-autoload-paranoid))
744             web-autoload-paranoid)
745     (save-window-excursion
746       (let* ((comp-buf (get-buffer "*Compilation*"))
747              (comp-win (and comp-buf
748                             (get-buffer-window comp-buf)))
749              (msg-win (web-vcs-display-messages nil))
750              temp-buf
751              (kf-desc (lambda (fun)
752                         (let* ((key (where-is-internal fun nil t))
753                                (k-desc (when key (key-description key)))
754                                (fmt-kf "\n    %s (or %s)")
755                                (fmt-f  "\n    %s"))
756                           (if key
757                               (format fmt-kf k-desc fun)
758                             (format fmt-f fun)
759                             )))))
760         (if comp-win
761             (progn
762               (select-window comp-win)
763               (find-file file-dl-name))
764           (select-window msg-win)
765           (find-file-other-window temp-file))
766         (setq temp-buf (current-buffer))
767         (web-vcs-log-save)
768         (message "-")
769         (message "")
770         (with-selected-window msg-win
771           (goto-char (point-max)))
772         (let ((proceed nil)
773               (web-autoload-active-file-sub-url file-sub-url)) ;; Dyn var, active during file download check
774           (web-vcs-paranoid-state-mode 1)
775           (web-vcs-message-with-face
776            'secondary-selection
777            (concat "Please check the downloaded file and then continue by doing"
778                    (funcall kf-desc 'exit-recursive-edit)
779                    (if (fboundp 'web-autoload-continue-no-stop)
780                        (concat
781                         "\n\nOr, for no more breaks to check files do"
782                         (funcall kf-desc 'web-autoload-continue-no-stop))
783                      "")
784                    "\n\nTo stop the web autoloading process for now do"
785                    (funcall kf-desc 'web-autoload-quit-download)
786                    "\n\nTo see the log file you can do"
787                    (funcall kf-desc 'web-vcs-log-edit)
788                    "\n"))
789           (message "")
790           (while (not proceed)
791             (condition-case err
792                 (when (eq 'web-autoload-stop
793                           (catch 'top-level
794                             ;; Fix-me: review file before rename!
795                             (setq header-line-format
796                                   (propertize
797                                    (format "Review for downloading. Continue: C-c C-c%s. Destination: %S"
798                                            (if (string= "el" (file-name-extension file-dl-name))
799                                                ", Check: C-c C-r"
800                                              "")
801                                            file-dl-name)
802                                    'face 'web-vcs-red))
803                             (unwind-protect
804                                 (progn
805                                   (recursive-edit))
806                               (web-vcs-paranoid-state-mode -1))
807                             (with-current-buffer temp-buf
808                               (set-buffer-modified-p nil)
809                               (kill-buffer temp-buf))
810                             (setq proceed t)))
811                   (throw 'top-level t))
812               (error (message "%s" (error-message-string err))))))
813         (web-vcs-display-messages t)
814         ))))
815
816
817 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
818 ;;; Auto Download Compile Queue
819 ;;
820 ;; Downloaded elisp files are placed in a compile queue. They are not
821 ;; compiled until all required elisp files are downloaded (and
822 ;; optionally compiled).
823 ;;
824 ;; This mechanism works through
825 ;; - reading (eval-when-compile ...) etc in the files
826 ;; - a defadviced require that is the driver of the process
827
828 (defvar web-autoload-compile-queue nil)
829
830 (defvar web-autoload-byte-compile-queue-active nil) ;; Dyn var
831
832 (defun web-autoload-byte-compile-file (file load comp-fun)
833   (if nil ;;(file-exists-p file)
834       (byte-compile-file file load)
835     (let ((added-entry (list file load comp-fun nil)))
836       (if (member added-entry web-autoload-compile-queue)
837           (setq added-entry nil)
838         (web-vcs-message-with-face 'web-vcs-gold "Add to compile queue (%S %s)" file load)
839         (setq web-autoload-compile-queue (cons added-entry
840                                                web-autoload-compile-queue)))
841       (when added-entry
842         (if web-autoload-byte-compile-queue-active
843             (throw 'web-autoload-comp-restart t)
844           (web-autoload-byte-compile-queue))))))
845
846 ;;(web-autoload-byte-compile-queue)
847 (defun web-autoload-byte-compile-queue ()
848   (let ((top-entry)
849         (web-autoload-byte-compile-queue-active t))
850     (while (and web-autoload-compile-queue
851                 (not (equal top-entry
852                             (car web-autoload-compile-queue))))
853       (setq top-entry (car web-autoload-compile-queue))
854       (catch 'web-autoload-comp-restart
855         (web-autoload-byte-compile-first)
856         (setq web-autoload-compile-queue (cdr web-autoload-compile-queue))))))
857
858 (defun web-autoload-byte-compile-first ()
859   "Compile first file on compile queue and maybe load it.
860 Compile the car of `web-autoload-compile-queue' and load if this
861 entry says so."
862   (let* ((compiled-it nil)
863          (first-entry (car web-autoload-compile-queue))
864          (el-file  (nth 0 first-entry))
865          (load     (nth 1 first-entry))
866          (comp-fun (nth 2 first-entry))
867          (req-done (nth 3 first-entry))
868          (elc-file (byte-compile-dest-file el-file))
869          (need-compile (or (not (file-exists-p elc-file))
870                            (file-newer-than-file-p el-file elc-file))))
871     (if (not need-compile)
872         nil ;;(when load (load elc-file))
873       (unless req-done
874         (web-autoload-do-eval-requires el-file)
875         (setcar (nthcdr 3 first-entry) t))
876       (when (catch 'web-autoload-comp-restart
877               (condition-case err
878                   (progn
879                     (web-vcs-message-with-face 'font-lock-comment-face "Start byte compiling %S" el-file)
880                     (web-vcs-message-with-face 'web-vcs-pink "Compiling QUEUE: %S" web-autoload-compile-queue)
881                     (let ((web-autoload-skip-require-advice t)) (funcall comp-fun el-file load))
882                     (web-vcs-message-with-face 'font-lock-comment-face "Ready byte compiling %S" el-file)
883                     ;; Return nil to tell there are no known problems
884                     (if (file-exists-p elc-file)
885                         nil
886                       (web-vcs-message-with-face
887                        'web-vcs-red "Error: byte compiling did not produce %S" elc-file)
888                       (web-vcs-display-messages nil)
889                       ;; Clean up before restart
890                       (web-autoload-try-cleanup-after-failed-compile first-entry)
891                       t))
892                 (error
893                  (web-vcs-message-with-face
894                   'web-vcs-red "Error in byte compiling %S: %s" el-file (error-message-string err))
895                  (web-vcs-display-messages nil)
896                  ;; Clean up before restart
897                  (web-autoload-try-cleanup-after-failed-compile first-entry)
898                  t ;; error
899                  )))
900         (throw 'web-autoload-comp-restart t)
901         ))))
902
903 (defun web-autoload-do-eval-requires (el-file)
904   "Do eval-when-compile and eval-and-compile."
905   ;;(message "web-autoload-do-eval-requires %S" el-file)
906   (let ((old-buf (find-buffer-visiting el-file)))
907     (with-current-buffer (or old-buf (find-file-noselect el-file))
908       (let ((here (point))
909             (web-autoload-require-skip-noerror-entries t))
910         (save-restriction
911           (widen)
912           (goto-char (point-min))
913           ;;(message "web-autoload-do-eval-requires cb=%s" (current-buffer))
914           (while (progn
915                    (while (progn (skip-chars-forward " \t\n\^l")
916                                  (looking-at ";"))
917                      (forward-line 1))
918                    (not (eobp)))
919             (let ((form (read (current-buffer))))
920               (when (memq (car form) '(eval-when-compile eval-and-compile))
921                 (web-vcs-message-with-face 'web-vcs-gold "  eval %S" form)
922                 (eval form))
923               )))
924         (if old-buf (kill-buffer) (goto-char here))))))
925
926
927 ;; Fix-me: protect against deep nesting
928 (defun web-autoload-do-require (feature filename noerror)
929   (let* ((feat-name (symbol-name feature))
930          (lib (or filename feat-name)))
931     (if (load lib noerror t)
932         (progn
933           (unless (featurep feature)
934             (error "web-autoload: Required feature `%s' was not provided" feature))
935           feature)
936       nil
937       )))
938
939 (defvar web-autoload-require-skip-noerror-entries nil)
940
941 (defadvice require (around
942                     web-autoload-ad-require)
943   (let ((feature  (ad-get-arg 0))
944         (filename (ad-get-arg 1))
945         (noerror  (ad-get-arg 2)))
946     (if (featurep feature)
947         feature
948       (if (or filename
949               (and noerror
950                    (or (not (boundp 'web-autoload-skip-require-advice))
951                        web-autoload-skip-require-advice)))
952           (progn
953             (message "Doing nearly original require %s, because skipping" (ad-get-arg 0))
954             ;; Can't ad-do-it because defadviced functions in load
955             ;;(web-autoload-do-require feature filename noerror)
956             ;;
957             ;; Fix-me: Implement lazy loading here? Could it be done with while-no-input?
958             ;;
959             ;;(when (assq feature web-autoload-require-list) )
960             ad-do-it)
961         (unless (and noerror
962                      web-autoload-require-skip-noerror-entries)
963           (let* ((auto-rec (assq feature web-autoload-require-list))
964                  (web-vcs      (nth 1 auto-rec))
965                  (base-url     (nth 2 auto-rec))
966                  (relative-url (nth 3 auto-rec))
967                  (base-dir     (nth 4 auto-rec))
968                  (comp-fun     (nth 5 auto-rec)))
969             (if (not auto-rec)
970                 ad-do-it
971               (let* ((full-el      (concat (expand-file-name relative-url base-dir) ".el"))
972                      (full-elc     (byte-compile-dest-file full-el))
973                      (our-buffer   (current-buffer)) ;; Need to come back here
974                      (our-wcfg     (current-window-configuration))
975                      (mode-line-old          (web-vcs-redefine-face 'mode-line 'web-vcs-mode-line))
976                      (mode-line-inactive-old (web-vcs-redefine-face 'mode-line-inactive 'web-vcs-mode-line-inactive))
977                      (header-line-format-old (with-current-buffer "*Messages*"
978                                                (prog1
979                                                    header-line-format
980                                                  (setq header-line-format
981                                                        (propertize "Downloading needed files..."
982                                                                    'face 'web-vcs-mode-line
983                                                                    ;;'face '(:height 1.5) ;; does not work
984                                                                    ))))))
985                 ;; Fix-me: can't update while accessing the menus
986                 ;;(message "trying (redisplay t) ;; mode line")
987                 ;;(sit-for 1) (redisplay t) ;; mode line
988                 (unwind-protect
989                     (progn
990                       (web-vcs-message-with-face 'web-vcs-gold "Doing the really adviced require for %s" feature)
991                       ;; Check if already downloaded first
992                       (unless (file-exists-p full-el)
993                         (setq base-url (eval base-url))
994                         ;; Download and try again
995                         (setq relative-url (concat relative-url ".el"))
996                         (web-vcs-message-with-face 'web-vcs-green "Need to download feature '%s" feature)
997                         (catch 'web-autoload-comp-restart
998                           (web-vcs-get-missing-matching-files web-vcs base-url base-dir relative-url)))
999                       (set-buffer our-buffer) ;; Before we load..
1000                       (when web-autoload-autocompile
1001                         (unless (file-exists-p full-elc)
1002                           ;; Byte compile the downloaded file
1003                           (web-autoload-byte-compile-file full-el t comp-fun)))
1004                       (web-vcs-message-with-face 'web-vcs-gold "Doing finally require for %s" feature)
1005                       (set-buffer our-buffer) ;; ... and after we load
1006                       (set-window-configuration our-wcfg))
1007                   (with-current-buffer "*Messages*" (setq header-line-format header-line-format-old))
1008                   (web-vcs-redefine-face 'mode-line mode-line-old)
1009                   (web-vcs-redefine-face 'mode-line-inactive mode-line-inactive-old)))
1010               ad-do-it)))))))
1011
1012 ;; (setq x (web-vcs-redefine-face 'mode-line (setq z (face-all-attributes 'web-vcs-mode-line (selected-frame)))))
1013 ;; (setq x (web-vcs-redefine-face 'mode-line 'web-vcs-mode-line))
1014 ;; (setq y (web-vcs-redefine-face 'mode-line x))
1015 ;; (describe-face 'web-vcs-mode-line)
1016 (defun web-vcs-redefine-face (face as-new)
1017   "Redefine FACE to use the attributes in AS-NEW.
1018 AS-NEW may be either a face or a list returned by `face-all-attributes'.
1019 Return an alist with old attributes."
1020   (let ((ret (face-all-attributes face (selected-frame)))
1021         (new-face-att (if (facep as-new)
1022                           (face-all-attributes as-new (selected-frame))
1023                         as-new))
1024         new-at-prop-list
1025         )
1026     (dolist (at new-face-att)
1027       (let ((sym (car at))
1028             (val (cdr at)))
1029         (unless (eq val 'unspecified)
1030           (setq new-at-prop-list (cons sym
1031                                        (cons val
1032                                              new-at-prop-list)))
1033           ;;(message "new=%S" new-at-prop-list)
1034           )))
1035     (apply 'set-face-attribute face (selected-frame) new-at-prop-list)
1036     ret
1037     ))
1038
1039 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1040 ;;; Web Autoload Define
1041
1042 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1043 ;;; Helpers
1044
1045 ;;(web-vcs-file-name-as-list "/a/b/c.el")
1046 ;;(web-vcs-file-name-as-list "a/b/c.el")
1047 ;;(web-vcs-file-name-as-list "c:/a/b/c.el")
1048 ;;(web-vcs-file-name-as-list ".*/a/c/")
1049 ;;(web-vcs-file-name-as-list "[^/]*/a/c/") ;; Just avoid this.
1050 (defun web-vcs-file-name-as-list (filename)
1051   "Split file name FILENAME into a list with file names."
1052   ;; We can't use the primitives since they converts \ to / and
1053   ;; therefore damages the reg exps.  Just use our knowledge of the
1054   ;; internal file name representation instead.
1055   (split-string filename "/"))
1056 ;; (let ((lst-name nil)
1057 ;;       (head filename)
1058 ;;       (old-head ""))
1059 ;;   (while (and (not (string= old-head head))
1060 ;;               (> (length head) 0))
1061 ;;     (let* ((file-head (directory-file-name head))
1062 ;;            (tail (file-name-nondirectory (directory-file-name head))))
1063 ;;       (setq old-head head)
1064 ;;       (setq head (file-name-directory file-head))
1065 ;;       ;; For an abs path the final tail is "", use root instead:
1066 ;;       (when (= 0 (length tail))
1067 ;;         (setq tail head))
1068 ;;       (setq lst-name (cons tail lst-name))))
1069 ;;   lst-name))
1070
1071 ;;(web-vcs-match-folderwise ".*/util/mum.el" "top/util/mum.el")
1072 ;;(web-vcs-match-folderwise ".*/util/mu.el" "top/util/mum.el")
1073 ;;(web-vcs-match-folderwise ".*/ut/mum.el" "top/util/mum.el")
1074 ;;(web-vcs-match-folderwise ".*/ut../mum.el" "top/util/mum.el")
1075 ;;(web-vcs-match-folderwise ".*/ut../mum.el" "top/util")
1076 ;;(web-vcs-match-folderwise ".*/ut../mum.el" "top")
1077 ;;(web-vcs-match-folderwise "top/ut../mum.el" "top")
1078 (defun web-vcs-match-folderwise (regex file)
1079   "Split REGEXP as a file path and match against FILE parts."
1080   ;;(message "folderwise %S %S" regex file)
1081   (let ((lst-regex (web-vcs-file-name-as-list regex))
1082         (lst-file  (web-vcs-file-name-as-list file)))
1083     (when (>= (length lst-regex) (length lst-file))
1084       (catch 'match
1085         (while lst-file
1086           (let ((head-file  (car lst-file))
1087                 (head-regex (car lst-regex)))
1088             (unless (or (= 0 (length head-file)) ;; Last /, if present, gives ""
1089                         (string-match-p (concat "^" head-regex "$") head-file))
1090               (throw 'match nil)))
1091           (setq lst-file  (cdr lst-file))
1092           (setq lst-regex (cdr lst-regex)))
1093         t))))
1094
1095 (defun web-vcs-contains-file (dir file)
1096   "Return t if DIR contain FILE."
1097   (assert (string= dir (file-name-as-directory (expand-file-name dir))) t)
1098   (assert (or (string= file (file-name-as-directory (expand-file-name file)))
1099               (string= file (expand-file-name file))) t)
1100   (let ((dir-len (length dir)))
1101     (assert (string= "/" (substring dir (1- dir-len))))
1102     (when (> (length file) dir-len)
1103       (string= dir (substring file 0 dir-len)))))
1104
1105 (defun web-vcs-nice-elapsed (start-time end-time)
1106   "Format elapsed time between START-TIME and END-TIME nicely.
1107 Those times should have the same format as time returned by
1108 `current-time'."
1109   (format-seconds "%h h %m m %z%s s" (float-time (time-subtract end-time start-time))))
1110
1111 ;; (web-vcs-equal-files "web-vcs.el" "temp.tmp")
1112 ;; (web-vcs-equal-files "../.nosearch" "temp.tmp")
1113 (defun web-vcs-equal-files (file-a file-b)
1114   "Return t if files FILE-A and FILE-B are equal."
1115   (let* ((cmd (if (eq system-type 'windows-nt)
1116                   (list "fc" nil nil nil
1117                         "/B" "/OFF"
1118                         (convert-standard-filename file-a)
1119                         (convert-standard-filename file-b))
1120                 (list diff-command nil nil nil
1121                       "--binary" "-q" file-a file-b)))
1122          (ret (apply 'call-process cmd)))
1123     ;;(message "ret=%s, cmd=%S" ret cmd) (sit-for 2)
1124     (cond
1125      ((= 1 ret)
1126       nil)
1127      ((= 0 ret)
1128       t)
1129      (t
1130       (error "%S returned %d" cmd ret)))))
1131
1132 (defun web-vcs-display-messages (select)
1133   "Display *Messages* buffer. Select its window if SELECT."
1134   (let ((msg-win (display-buffer "*Messages*")))
1135     (with-selected-window msg-win (goto-char (point-max)))
1136     (when select (select-window msg-win))
1137     msg-win))
1138
1139 ;; (web-vcs-message-with-face 'secondary-selection "I am saying: %s and %s" "Hi" "Farwell!")
1140 ;;;###autoload
1141 (defun web-vcs-message-with-face (face format-string &rest args)
1142   "Display a colored message at the bottom of the string.
1143 FACE is the face to use for the message.
1144 FORMAT-STRING and ARGS are the same as for `message'.
1145
1146 Also put FACE on the message in *Messages* buffer."
1147   (with-current-buffer "*Messages*"
1148     (save-restriction
1149       (widen)
1150       (let* ((start (let ((here (point)))
1151                       (goto-char (point-max))
1152                       (prog1
1153                           (copy-marker
1154                            (if (bolp) (point-max)
1155                              (1+ (point-max))))
1156                         (goto-char here))))
1157              (msg-with-face (propertize (apply 'format format-string args)
1158                                         'face face)))
1159         ;; This is for the echo area:
1160         (message "%s" msg-with-face)
1161         ;; This is for the buffer:
1162         (when (< 0 (length msg-with-face))
1163           (goto-char (1- (point-max)))
1164           ;;(backward-char)
1165           ;;(unless (eolp) (goto-char (line-end-position)))
1166           (put-text-property start (point)
1167                              'face face))))))
1168
1169 (defun web-vcs-num-moved (root)
1170   "Return nof files matching *.moved inside directory ROOT."
1171   (let* ((file-regexp ".*\\.moved$")
1172          (files (directory-files root t file-regexp))
1173          (subdirs (directory-files root t)))
1174     (dolist (subdir subdirs)
1175       (when (and (file-directory-p subdir)
1176                  (not (or (string= "/." (substring subdir -2))
1177                           (string= "/.." (substring subdir -3)))))
1178         (setq files (append files (web-vcs-rdir-get-files subdir file-regexp) nil))))
1179     (length files)))
1180
1181 ;; Copy of rdir-get-files in ourcomment-util.el
1182 (defun web-vcs-rdir-get-files (root file-regexp)
1183   (let ((files (directory-files root t file-regexp))
1184         (subdirs (directory-files root t)))
1185     (dolist (subdir subdirs)
1186       (when (and (file-directory-p subdir)
1187                  (not (or (string= "/." (substring subdir -2))
1188                           (string= "/.." (substring subdir -3)))))
1189         (setq files (append files (web-vcs-rdir-get-files subdir file-regexp) nil))))
1190     files))
1191
1192 (defun web-vcs-contains-moved-files (dl-dir)
1193   "Return t if there are *.moved files in DL-DIR."
1194   (let ((num-moved (web-vcs-num-moved dl-dir)))
1195     (when (> num-moved 0)
1196       (web-vcs-message-with-face 'font-lock-warning-face
1197                                  (concat "There are %d *.moved files (probably from prev download)\n"
1198                                          "in %S.\nPlease delete them first.")
1199                                  num-moved dl-dir)
1200       t)))
1201
1202
1203 (defun web-vcs-set&save-option (symbol value)
1204   (customize-set-variable symbol value)
1205   (customize-set-value symbol value)
1206   (when (condition-case nil (custom-file) (error nil))
1207     (customize-mark-to-save symbol)
1208     (custom-save-all)
1209     (message "web-vcs: Saved option %s with value %s" symbol value)))
1210
1211 (defvar web-vcs-el-this (or load-file-name
1212                             (when (boundp 'bytecomp-filename) bytecomp-filename)
1213                             buffer-file-name))
1214
1215
1216 (require 'bytecomp)
1217 (defun web-vcs-byte-compile-newer-file (el-file load)
1218   (let ((elc-file (byte-compile-dest-file el-file)))
1219     (when (or (not (file-exists-p elc-file))
1220               (file-newer-than-file-p el-file elc-file))
1221       (byte-compile-file el-file load))))
1222
1223 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1224 ;;; Compiling
1225
1226 ;;;###autoload
1227 (defun web-vcs-byte-compile-file (file &optional load extra-load-path comp-dir)
1228   "Byte compile FILE in a new Emacs sub process.
1229 EXTRA-LOAD-PATH is added to the front of `load-path' during
1230 compilation.
1231
1232 FILE is set to `buffer-file-name' when called interactively.
1233 If LOAD"
1234   (interactive (list (buffer-file-name)
1235                      t))
1236   (when (with-no-warnings (called-interactively-p))
1237     (unless (eq major-mode 'emacs-lisp-mode)
1238       (error "Must be in emacs-lisp-mode")))
1239   (let* ((old-env-load-path (getenv "EMACSLOADPATH"))
1240          (sub-env-load-path (or old-env-load-path
1241                                 ;;(mapconcat 'identity load-path ";")))
1242                                 (mapconcat 'identity load-path path-separator)))
1243          ;; Fix-me: name of compile log buffer. When should it be
1244          ;; deleted? How do I bind it to byte-compile-file? Or do I?
1245          (file-buf (find-buffer-visiting file))
1246          (out-buf (get-buffer-create "*Compile-Log*"))
1247          (elc-file (byte-compile-dest-file file))
1248          (this-emacs-exe (locate-file invocation-name
1249                                       (list invocation-directory)
1250                                       exec-suffixes))
1251          (default-directory (or comp-dir default-directory))
1252          (debug-on-error t)
1253          start)
1254     ;; (when (and file-buf
1255     ;;            (buffer-modified-p file-buf))
1256     ;;   (switch-to-buffer file-buf)
1257     ;;   (error "Buffer must be saved first: %S" file-buf))
1258     (dolist (full-p extra-load-path)
1259       ;;(setq sub-env-load-path (concat full-p ";" sub-env-load-path)))
1260       (setq sub-env-load-path (concat full-p path-separator sub-env-load-path)))
1261     (unless (get-buffer-window out-buf (selected-frame))
1262       (if (string= file (buffer-file-name))
1263           (display-buffer out-buf)
1264         (unless (eq (current-buffer) out-buf)
1265           (switch-to-buffer out-buf))))
1266     (with-selected-window (get-buffer-window out-buf)
1267       (with-current-buffer out-buf
1268         (unless (local-variable-p 'web-vcs-comp-dir)
1269           (set (make-local-variable 'web-vcs-comp-dir) (or comp-dir default-directory)))
1270         (setq default-directory web-vcs-comp-dir)
1271         (widen)
1272         (goto-char (point-max))
1273         (when (or (= 0 (buffer-size))
1274                   (not (derived-mode-p 'compilation-mode)))
1275           (insert (propertize "\nWeb VCS compilation output" 'font-lock-face 'font-lock-comment-face))
1276           (compilation-mode)
1277           (setq font-lock-verbose nil)
1278           (font-lock-add-keywords nil
1279                                   '(("\\<Compile\\>" . 'compilation-info))))
1280         (let ((inhibit-read-only t)
1281               (rel-file (file-relative-name file)))
1282           (insert "\n\n")
1283           (insert "** Compile " rel-file "\n"))
1284         (setq start (point))
1285         (when (file-exists-p elc-file) (delete-file elc-file))
1286         (if (or (not window-system)
1287                 (< emacs-major-version 23))
1288             (byte-compile-file file)
1289           ;;(message "web-vcs-byte-compile-file:sub-env-load-path=%s" sub-env-load-path)
1290           (unless (file-exists-p this-emacs-exe)
1291             (error "Can't find this-emacs-exe=%s" this-emacs-exe))
1292           (unless (stringp sub-env-load-path) (error "I did it again, sub-env-load-path=%S" sub-env-load-path))
1293           (setenv "EMACSLOADPATH" sub-env-load-path)
1294           ;; Fix-me: status
1295           (let* ((inhibit-read-only t)
1296                  (ret (apply 'call-process this-emacs-exe nil out-buf t
1297                             "-Q" "--batch"
1298                             "--eval" "(setq debug-on-error t)"
1299                             "--eval" "(remove-hook 'find-file-hook 'vc-find-file-hook)"
1300                             "--file" file
1301                             "-f" "emacs-lisp-byte-compile"
1302                              nil)))
1303             ;;(insert (format "call-process returned: %s\n" ret))
1304             )
1305           (setenv "EMACSLOADPATH" old-env-load-path))
1306         (goto-char start)
1307         (while (re-search-forward "^\\([a-zA-Z0-9/\._-]+\\):[0-9]+:[0-9]+:" nil t)
1308           (let ((rel-file (file-relative-name file))
1309                 (inhibit-read-only t))
1310             (replace-match rel-file nil nil nil 1)))
1311         (goto-char (point-max))))
1312     (when (file-exists-p elc-file)
1313       (when (and load window-system) (load elc-file))
1314       t)))
1315
1316
1317 ;;;;;;;;;;;;;;;;;;;;;;;;
1318 ;;; Temporary helpers, possibly included in Emacs
1319
1320 ;; (setq x (web-vcs-url-retrieve-synch "http://emacswiki.org/"))
1321 (defun web-vcs-url-retrieve-synch (url)
1322   "Retrieve URL, return cons with buffer and http status."
1323   (let* ((url-show-status nil) ;; just annoying showing status here
1324          (buffer (url-retrieve-synchronously url))
1325          (handle nil)
1326          (http-status nil))
1327     (if (not buffer)
1328         (error "Retrieving url %s gave no buffer" url))
1329     (with-current-buffer buffer
1330       (if (= 0 (buffer-size))
1331           (progn
1332             (kill-buffer)
1333             nil)
1334         (require 'url-http)
1335         (setq http-status (url-http-parse-response))
1336         (if (memq http-status '(200 201))
1337             (progn
1338               (goto-char (point-min))
1339               (unless (search-forward "\n\n" nil t)
1340                 (error "Could not find header end in buffer for %s" url))
1341               (delete-region (point-min) (point))
1342               (set-buffer-modified-p nil)
1343               (goto-char (point-min)))
1344           (kill-buffer buffer)
1345           (setq buffer nil))))
1346     (cons buffer http-status)))
1347
1348 ;; Modified just to return http status
1349 (defun web-vcs-url-copy-file (url newname &optional ok-if-already-exists
1350                                   keep-time preserve-uid-gid)
1351   "Copy URL to NEWNAME.  Both args must be strings.
1352 Signals a `file-already-exists' error if file NEWNAME already exists,
1353 unless a third argument OK-IF-ALREADY-EXISTS is supplied and non-nil.
1354 A number as third arg means request confirmation if NEWNAME already exists.
1355 This is what happens in interactive use with M-x.
1356 Fourth arg KEEP-TIME non-nil means give the new file the same
1357 last-modified time as the old one.  (This works on only some systems.)
1358 Fifth arg PRESERVE-UID-GID is ignored.
1359 A prefix arg makes KEEP-TIME non-nil."
1360   (if (and (file-exists-p newname)
1361            (not ok-if-already-exists))
1362       (error "Opening output file: File already exists, %s" newname))
1363   (let ((buffer (url-retrieve-synchronously url))
1364         (handle nil)
1365         (ret nil))
1366     (if (not buffer)
1367         (error "Retrieving url %s gave no buffer" url))
1368     (with-current-buffer buffer
1369       (if (= 0 (buffer-size))
1370           (progn
1371             (kill-buffer)
1372             nil)
1373         (require 'url-http)
1374         (setq ret (url-http-parse-response))
1375         (setq handle (mm-dissect-buffer t))
1376         (mm-save-part-to-file handle newname)
1377         (kill-buffer buffer)
1378         (mm-destroy-parts handle)))
1379     ret))
1380
1381 (defun web-vcs-read-and-accept-key (prompt accepted &optional reject-message help-function)
1382   (let ((key nil)
1383         rejected)
1384     (while (not (member key accepted))
1385       (if (and help-function
1386                (or (member key help-event-list)
1387                    (eq key ??)))
1388           (funcall help-function)
1389         (unless rejected
1390           (setq rejected t)
1391           (setq prompt (concat (or reject-message "Please answer with one of the alternatives.")
1392                                "\n\n"
1393                                prompt))
1394           (setq key (web-vcs-read-key prompt)))))
1395     key))
1396
1397 (defconst web-vcs-read-key-empty-map (make-sparse-keymap))
1398
1399 (defvar web-vcs-read-key-delay 0.01) ;Fast enough for 100Hz repeat rate, hopefully.
1400
1401 (defun web-vcs-read-key (&optional prompt)
1402   "Read a key from the keyboard.
1403 Contrary to `read-event' this will not return a raw event but instead will
1404 obey the input decoding and translations usually done by `read-key-sequence'.
1405 So escape sequences and keyboard encoding are taken into account.
1406 When there's an ambiguity because the key looks like the prefix of
1407 some sort of escape sequence, the ambiguity is resolved via `web-vcs-read-key-delay'."
1408   (let ((overriding-terminal-local-map web-vcs-read-key-empty-map)
1409         (overriding-local-map nil)
1410         (old-global-map (current-global-map))
1411         (timer (run-with-idle-timer
1412                 ;; Wait long enough that Emacs has the time to receive and
1413                 ;; process all the raw events associated with the single-key.
1414                 ;; But don't wait too long, or the user may find the delay
1415                 ;; annoying (or keep hitting more keys which may then get
1416                 ;; lost or misinterpreted).
1417                 ;; This is only relevant for keys which Emacs perceives as
1418                 ;; "prefixes", such as C-x (because of the C-x 8 map in
1419                 ;; key-translate-table and the C-x @ map in function-key-map)
1420                 ;; or ESC (because of terminal escape sequences in
1421                 ;; input-decode-map).
1422                 web-vcs-read-key-delay t
1423                 (lambda ()
1424                   (let ((keys (this-command-keys-vector)))
1425                     (unless (zerop (length keys))
1426                       ;; `keys' is non-empty, so the user has hit at least
1427                       ;; one key; there's no point waiting any longer, even
1428                       ;; though read-key-sequence thinks we should wait
1429                       ;; for more input to decide how to interpret the
1430                       ;; current input.
1431                       (throw 'read-key keys)))))))
1432     (unwind-protect
1433         (progn
1434           (use-global-map web-vcs-read-key-empty-map)
1435           (message (concat (apply 'propertize prompt (member 'face minibuffer-prompt-properties))
1436                            (propertize " " 'face 'cursor)))
1437           (aref (catch 'read-key (read-key-sequence-vector nil nil t)) 0))
1438       (cancel-timer timer)
1439       (use-global-map old-global-map))))
1440
1441 ;; End temp helpers
1442 ;;;;;;;;;;;;;;;;;;;;;;;;
1443
1444 ;;(web-vcs-existing-files-matcher default-directory)
1445 (defun web-vcs-existing-files-matcher (dir)
1446   (let ((files-and-dirs (directory-files dir nil "[^#~]$"))
1447         files
1448         (default-directory dir))
1449     (dolist (df files-and-dirs)
1450       (unless (file-directory-p df)
1451         (setq files (cons df files))))
1452     (cons (regexp-opt files) t)))
1453
1454 (defun web-vcs-update-existing-files (vcs base-url dl-dir this-dir)
1455   (let ((files-and-dirs (directory-files this-dir nil "\\(?:\\.elc\\|\\.moved\\|[^#~]\\)$"))
1456         files
1457         dirs
1458         (this-rel (file-relative-name this-dir dl-dir))
1459         file-mask)
1460     (when (string= "./" this-rel) (setq this-rel ""))
1461     (dolist (df files-and-dirs)
1462       (if (and (file-directory-p df)
1463                (not (member df '("." ".."))))
1464           (setq dirs (cons df dirs))
1465         (setq files (cons df files))))
1466     ;;(web-vcs-message-with-face 'hi-blue "this-rel=%S  %S %S" this-rel  dl-dir this-dir)
1467     (setq file-mask (concat this-rel (regexp-opt files)))
1468     ;;(web-vcs-message-with-face 'hi-blue "r=%S" file-mask)
1469     (web-vcs-get-missing-matching-files vcs base-url dl-dir file-mask)
1470     (dolist (d dirs)
1471       (web-vcs-update-existing-files vcs base-url dl-dir
1472                                        (file-name-as-directory
1473                                         (expand-file-name d this-dir))))))
1474
1475
1476
1477 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1478 ;; Some small bits for security and just overview.
1479
1480 (defun web-vcs-fontify-as-ps-print()
1481   (save-restriction
1482     (widen)
1483     (let ((start (point-min))
1484           (end   (point-max)))
1485       (cond ((and (boundp 'jit-lock-mode) (symbol-value 'jit-lock-mode))
1486              (jit-lock-fontify-now start end))
1487             ((and (boundp 'lazy-lock-mode) (symbol-value 'lazy-lock-mode))
1488              (lazy-lock-fontify-region start end))))))
1489
1490
1491 ;;(web-vcs-get-fun-details 'describe-function)
1492 ;;(web-vcs-get-fun-details 'require)
1493 ;;(describe-function 'describe-function)
1494 (defun web-vcs-get-fun-details (function)
1495   (unless (symbolp function) (error "Not a symbol: %s" function))
1496   (unless (functionp function) (error "Not a function: %s" function))
1497   ;; Do as in `describe-function':
1498   (let* ((advised (and (symbolp function) (featurep 'advice)
1499                        (ad-get-advice-info function)))
1500          ;; If the function is advised, use the symbol that has the
1501          ;; real definition, if that symbol is already set up.
1502          (real-function
1503           (or (and advised
1504                    (let ((origname (cdr (assq 'origname advised))))
1505                      (and (fboundp origname) origname)))
1506               function))
1507          ;; Get the real definition.
1508          (def (if (symbolp real-function)
1509                       (symbol-function real-function)
1510                     function))
1511          errtype file-name (beg "") string)
1512     ;; Just keep this as it is to more easily compare with `describe-function-1'.
1513     (setq string
1514           (cond ((or (stringp def)
1515                      (vectorp def))
1516                  "a keyboard macro")
1517                 ((subrp def)
1518                  (if (eq 'unevalled (cdr (subr-arity def)))
1519                      (concat beg "special form")
1520                    (concat beg "built-in function")))
1521                 ((byte-code-function-p def)
1522                  (concat beg "compiled Lisp function"))
1523                 ((symbolp def)
1524                  (while (and (fboundp def)
1525                              (symbolp (symbol-function def)))
1526                    (setq def (symbol-function def)))
1527                  ;; Handle (defalias 'foo 'bar), where bar is undefined.
1528                  (or (fboundp def) (setq errtype 'alias))
1529                  (format "an alias for `%s'" def))
1530                 ((eq (car-safe def) 'lambda)
1531                  (concat beg "Lisp function"))
1532                 ((eq (car-safe def) 'macro)
1533                  "a Lisp macro")
1534                 ((eq (car-safe def) 'autoload)
1535                  ;;(setq file-name-auto (nth 1 def))
1536                  ;;(setq file-name-auto (find-lisp-object-file-name function def))
1537                  ;;(setq file-auto-noext (file-name-sans-extension file-name-auto))
1538                  (format "%s autoloaded %s"
1539                          (if (commandp def) "an interactive" "an")
1540                          (if (eq (nth 4 def) 'keymap) "keymap"
1541                            (if (nth 4 def) "Lisp macro" "Lisp function"))))
1542                 ((keymapp def)
1543                  (let ((is-full nil)
1544                        (elts (cdr-safe def)))
1545                    (while elts
1546                      (if (char-table-p (car-safe elts))
1547                          (setq is-full t
1548                                elts nil))
1549                      (setq elts (cdr-safe elts)))
1550                    (if is-full
1551                        "a full keymap"
1552                      "a sparse keymap")))
1553                 (t "")))
1554     (setq file-name (find-lisp-object-file-name function def))
1555     (list errtype advised file-name string)
1556     ))
1557
1558 ;;(web-vcs-investigate-read "c:/emacsw32/nxhtml/nxhtml/nxhtml-autoload.el" "*Messages*")
1559 (defun web-vcs-investigate-read (elisp out-buf)
1560   "Check forms in buffer by reading it."
1561   (let* ((here (point))
1562         unsafe-eval re-fun re-var
1563         elisp-el-file
1564         (is-same-file (lambda (file)
1565                         (when file
1566                           (setq file (concat (file-name-sans-extension file) ".el"))
1567                           (string= (file-truename file) elisp-el-file)))))
1568     (with-current-buffer elisp
1569       (setq elisp-el-file (when (buffer-file-name)
1570                             (file-truename (buffer-file-name))))
1571       (save-restriction
1572         (widen)
1573         (web-vcs-fontify-as-ps-print)
1574         (goto-char (point-min))
1575         (while (progn
1576                  (while (progn (skip-chars-forward " \t\n\^l")
1577                                (looking-at ";"))
1578                    (forward-line 1))
1579                  (not (eobp)))
1580           (let* ((pos (point))
1581                  (form (read (current-buffer)))
1582                  (def (nth 0 form))
1583                  (sym (and (listp form)
1584                            (symbolp (nth 1 form))
1585                            (nth 1 form)))
1586                  (form-fun (and sym
1587                                 (functionp sym)
1588                                 (symbol-function sym)))
1589                  (form-var (boundp sym))
1590                  (safe-forms '( defun defmacro
1591                                 define-minor-mode define-globalized-minor-mode
1592                                 defvar defconst
1593                                 defcustom
1594                                 defface defgroup
1595                                 ;; fix-me: check if these do re-fun too:
1596                                 define-derived-mode
1597                                 define-global-minor-mode
1598                                 define-globalized-minor-mode
1599
1600                                 make-local-variable make-variable-buffer-local
1601                                 provide
1602                                 require
1603                                 message))
1604                  (safe-eval (or (memq def safe-forms)
1605                                 (and (memq def '( eval-when-compile eval-and-compile))
1606                                      (or (not (consp (nth 1 form)))
1607                                          (memq (car (nth 1 form)) safe-forms)))))
1608                  )
1609             (cond
1610              ((not safe-eval)
1611               (setq unsafe-eval
1612                     (cons (list form (copy-marker pos) (buffer-substring pos (point)))
1613                           unsafe-eval)))
1614              ((and form-fun
1615                    (memq def '( defun defmacro define-minor-mode define-globalized-minor-mode)))
1616               (setq re-fun (cons (cons sym pos) re-fun)))
1617              ((and form-var
1618                    (memq def '( defvar defconst defcustom))
1619                    (or (not (eq sym 'defvar))
1620                        (< 2 (length form))))
1621               (setq re-var (cons sym re-var)))))))
1622       (goto-char here))
1623     (with-current-buffer out-buf
1624       (save-restriction
1625         (widen)
1626         (goto-char (point-max))
1627         (unless (bobp) (insert "\n\n"))
1628         (insert (propertize "Found these possible problems when reading the file:\n"
1629                             'face '(:height 1.5)))
1630         (or unsafe-eval
1631             re-fun
1632             (insert "\n"
1633                     "Found no problems (but there may still be)"
1634                     "\n"))
1635
1636         ;; Fix-me: Link
1637         (when unsafe-eval
1638           (insert (propertize
1639                    (format "\n* Forms that are executed when loading the file (found %s):\n\n"
1640                           (length unsafe-eval))
1641                    'face '(:height 1.2)))
1642           (dolist (u unsafe-eval)
1643             (insert-text-button "Go to form below"
1644                                 'action
1645                                 `(lambda (button)
1646                                    (let* ((marker ,(nth 1 u))
1647                                           (buf (marker-buffer marker)))
1648                                      (switch-to-buffer-other-window buf)
1649                                      (unless (and (< marker (point-max))
1650                                                   (> marker (point-min)))
1651                                        (widen))
1652                                      (goto-char marker))))
1653             (insert "\n")
1654             (insert (nth 2 u) "\n\n"))
1655           (insert "\n"))
1656         (when re-fun
1657           (insert (propertize
1658                    (format "\n* The file will possibly redefine these functions that are currently defined (%s):\n"
1659                           (length re-fun))
1660                    'face '(:height 1.2)))
1661           (setq re-fun (sort re-fun (lambda (a b) (string< (symbol-name (car a)) (symbol-name (car b))))))
1662           (let ((row 0)
1663                 (re-fun-with-info (mapcar (lambda (fun)
1664                                             (cons fun (web-vcs-get-fun-details (car fun))))
1665                                             re-fun))
1666                 re-fun-other-files
1667                 (n-same 0)
1668                 (n-web-auto 0))
1669             ;; Check same file
1670             (dolist (info re-fun-with-info)
1671               (let* ((file-name (nth 3 info))
1672                      (fun (car (nth 0 info)))
1673                      (web-auto (get fun 'web-autoload)))
1674                 (cond ((funcall is-same-file file-name)
1675                        (setq n-same (1+ n-same)))
1676                       (web-auto
1677                        (setq n-web-auto (1+ n-web-auto))
1678                        (setq re-fun-other-files (cons info re-fun-other-files)))
1679                       (t
1680                        (setq re-fun-other-files (cons info re-fun-other-files))))))
1681
1682             (when (< 0 n-same)
1683               (insert "\n  "
1684                       (propertize (format "%s functions alreay defined by this file (which seems ok)" n-same)
1685                                   'face 'web-vcs-green)
1686                       "\n"))
1687
1688             (dolist (info re-fun-other-files)
1689               (let* ((fun-rec   (nth 0 info))
1690                      (errtype   (nth 1 info))
1691                      (advised   (nth 2 info))
1692                      (file-name (nth 3 info))
1693                      (string    (nth 4 info))
1694                      (fun     (car fun-rec))
1695                      (fun-pos (cdr fun-rec))
1696                      (fun-web-auto (get fun 'web-autoload))
1697                      )
1698                 (when (= 0 (% row 5)) (insert "\n"))
1699                 (setq row (1+ row))
1700                 (insert "  `")
1701                 (insert-text-button (format "%s" fun)
1702                                     'action
1703                                     `(lambda (button)
1704                                        (describe-function ',fun)))
1705                 (insert "'")
1706                 (insert " (" string)
1707                 (when fun-web-auto
1708                   (insert " autoloaded from web, ")
1709                   (insert-text-button "info"
1710                                       'action
1711                                       `(lambda (button)
1712                                          ;; Fix-me: maybe a bit more informative ... ;-)
1713                                          (message "%S" ',fun-web-auto))))
1714                 (insert ")")
1715                 (when advised (insert ", " (propertize "adviced" 'face 'font-lock-warning-face)))
1716                 (insert ", "
1717                         (cond
1718                          ((funcall is-same-file file-name)
1719                           (propertize "defined in this file" 'face 'web-vcs-green)
1720                           )
1721                          (fun-web-auto
1722                           (if (not (web-autoload-acvtive))
1723                               (propertize "web download not active" 'face 'web-vcs-yellow)
1724                             ;; See if file matches
1725                             (let ((active-sub-url web-autoload-active-file-sub-url)
1726                                   (fun-sub-url (nth 2 fun-web-auto)))
1727                               (setq active-sub-url (file-name-sans-extension active-sub-url))
1728                               (if (string-match-p fun-sub-url active-sub-url)
1729                                   (propertize "web download, matches" 'face 'web-vcs-yellow)
1730                                 (propertize "web download, doesn't matches" 'face 'web-vcs-red)
1731                                 ))))
1732                          (t
1733                           (propertize "defined in other file" 'face 'web-vcs-red))))
1734                 (unless (funcall is-same-file file-name)
1735                   (insert " (")
1736                   (insert-text-button "go to new definition"
1737                                       'action
1738                                       `(lambda (button)
1739                                          (interactive)
1740                                          (let ((m-pos ,(with-current-buffer elisp
1741                                                          (copy-marker fun-pos))))
1742                                            (switch-to-buffer-other-window (marker-buffer m-pos))
1743                                            (goto-char m-pos))))
1744                   (insert ")"))
1745                 (insert "\n")
1746                 ))))))))
1747
1748 ;; I am quite tired of doing this over and over again. Why is this not
1749 ;; in Emacs?
1750 (defvar web-vcs-button-mode-map
1751   (let ((map (make-sparse-keymap)))
1752     (define-key map [tab] 'forward-button)
1753     (define-key map [(shift tab)] 'backward-button)
1754     map))
1755 (define-minor-mode web-vcs-button-mode
1756   "Just to bind `forward-button' etc"
1757   :lighter nil)
1758
1759 (defvar web-vcs-eval-output-start nil)
1760
1761 ;;(web-vcs-investigate-file)
1762 ;;;###autoload
1763 (defun web-vcs-investigate-elisp-file (file-or-buffer)
1764   (interactive (list
1765                 (if (derived-mode-p 'emacs-lisp-mode)
1766                     (current-buffer)
1767                   (read-file-name "Elisp file to check: "))))
1768   (let* ((elisp (if (bufferp file-or-buffer)
1769                     file-or-buffer
1770                   (find-file-noselect file-or-buffer)))
1771          (elisp-file (with-current-buffer elisp (buffer-file-name)))
1772          (out-buf (get-buffer-create "Web VCS Sec Inv")))
1773     (if (not (with-current-buffer elisp (derived-mode-p 'emacs-lisp-mode)))
1774         (progn
1775           (unless (eq (current-buffer) elisp)
1776             (display-buffer elisp))
1777           (message "Buffer %s is not in emacs-lisp-mode" (buffer-name elisp)))
1778       (switch-to-buffer-other-window out-buf)
1779       (let ((inhibit-read-only t))
1780         (erase-buffer)
1781         (setq buffer-read-only t)
1782         (web-vcs-button-mode 1)
1783         (insert "A quick look for problems in ")
1784         (if elisp-file
1785             (progn
1786               (insert "file\n    ")
1787               (insert-text-button elisp-file
1788                                   'action
1789                                   `(lambda (button)
1790                                      (interactive)
1791                                      (find-file-other-window ,elisp-file))))
1792           (insert "buffer ")
1793           (insert-text-button (buffer-name elisp)
1794                               'action
1795                               `(lambda (button)
1796                                  (interactive)
1797                                  (switch-to-buffer-other-window ,elisp))))
1798         (insert "\n")
1799         (let ((here (point)))
1800           (insert
1801            "\n"
1802            (propertize
1803             (concat "Note that this is just a quick look at the file."
1804                     " You have to investigate the file more carefully yourself"
1805                     " (or be sure someone else has done it for you)."
1806                     " The following are checked for here:"
1807                     "\n")
1808             'face font-lock-comment-face))
1809           (fill-region here (point)))
1810         (insert
1811          (propertize
1812           (concat
1813            "- Top level forms that might be executed when loading the file.\n"
1814            "- Redefinition of functions.\n")
1815           'face font-lock-comment-face))
1816         (web-vcs-investigate-read elisp out-buf)
1817         (when elisp-file
1818           (insert "\n\n\n")
1819           (let ((here (point)))
1820             (insert "If you want to see what will actually be added to `load-history'"
1821                     " and which functions will be defined you can\n")
1822             (insert-text-button "click here to try to eval the file"
1823                                 'action `(lambda (button) (interactive)
1824                                            (if (y-or-n-p "Load the file in a batch Emacs session? ")
1825                                                (web-vcs-investigate-eval ,elisp-file ,out-buf)
1826                                              (message "Aborted"))))
1827             (insert ".\n\nThis will load the file in a batch Emacs"
1828                     " which runs the same init files as you have run now"
1829                     (cond
1830                      ((not init-file-user) " (with -Q, ie no init files will run)")
1831                      ((not site-run-file) " (with -q, ie .emacs will not furn)")
1832                      (t " (your normal setup files will be run)"
1833                       ))
1834                     " and send back that information."
1835                     " The variable `load-path' is set to match the downloading"
1836                     " to make the loading possible before your setup is ready."
1837                     "\n\nYour current Emacs will not be affected by the loading,"
1838                     " but please be aware that this does not mean your computer can not be."
1839                     " So please look at the file first.")
1840             (fill-region here (point))
1841             (setq web-vcs-eval-output-start (point))
1842             ))
1843         (set-buffer-modified-p nil)
1844         (goto-char (point-min))))))
1845
1846 (make-variable-buffer-local 'web-vcs-eval-output-start)
1847
1848 ;;(web-vcs-investigate-eval "c:/emacsw32/nxhtml/nxhtml/nxhtml-autoload.el" "*Messages*")
1849 ;;(web-vcs-investigate-eval "c:/emacsw32/nxhtml/autostart.el" "*Messages*")
1850 (defun web-vcs-investigate-eval (elisp-file out-buf)
1851   "Get compile loads when evaling buffer.
1852 For security reasons do this in a fresh Emacs and return the
1853 resulting load-history entry."
1854   (let* ((emacs-exe (locate-file invocation-name
1855                                  (list invocation-directory)
1856                                  exec-suffixes))
1857          ;; see custom-load-symbol
1858          (get-lhe '(let ((lhe (or (assoc buffer-file-name load-history)
1859                                   (assoc (concat (file-name-sans-extension buffer-file-name) ".elc")
1860                                          load-history))))
1861                      (prin1 "STARTHERE\n")
1862                      (prin1 lhe)))
1863          (elisp-file-name (file-name-sans-extension (file-name-nondirectory elisp-file)))
1864          (elisp-el-file (file-truename (concat (file-name-sans-extension elisp-file) ".el")))
1865          (temp-prefix web-autoload-temp-file-prefix)
1866          (temp-prefix-len (length temp-prefix))
1867          (is-downloading (and (boundp 'web-autoload-paranoid)
1868                               web-autoload-paranoid))
1869          (is-temp-file (and is-downloading
1870                             (< (length temp-prefix) (length elisp-file-name))
1871                             (string= temp-prefix
1872                                      (substring elisp-file-name 0 temp-prefix-len))))
1873          (elisp-feature-name (if is-temp-file
1874                                  (substring elisp-file-name temp-prefix-len)
1875                                elisp-file-name))
1876          (is-same-file (lambda (file)
1877                          (when file ;; self protecting
1878                            (setq file (concat (file-name-sans-extension file) ".el"))
1879                            (string= (file-truename file) elisp-el-file))))
1880          (active-sub-url (when (web-autoload-acvtive)
1881                            (file-name-sans-extension web-autoload-active-file-sub-url)))
1882          whole-result
1883          batch-error
1884          result)
1885     (with-current-buffer out-buf
1886       (let ((here (point))
1887             (inhibit-read-only t))
1888         (save-restriction
1889           (widen)
1890           (goto-char (point-max))
1891           (delete-region web-vcs-eval-output-start (point)))
1892         (goto-char here)))
1893     ;; Fix-me: do not use temp buffer so we can check errors
1894     (with-temp-buffer
1895       (let ((old-loadpath (getenv "EMACSLOADPATH"))
1896             ;;(new-loadpath (mapconcat 'identity load-path ";"))
1897             (new-loadpath (mapconcat 'identity load-path path-separator))
1898             ret-val)
1899         (setenv new-loadpath)
1900         (message "Loading file in batch Emacs...")
1901         (setq ret-val
1902               (call-process emacs-exe nil
1903                             (current-buffer)
1904                             t "--batch"
1905                             ;; fix-me: "-Q" - should be run in the users current environment.
1906                             ;; init-file-user nil => -Q
1907                             ;; site-run-file nil => -q
1908                             (cond
1909                              ((not init-file-user) "-Q")
1910                              ((not site-run-file) "-q")
1911                              (t "--debug-init")) ;; have to have something here...
1912                             "-l" elisp-file
1913                             elisp-file
1914                             "-eval" (format "%S" get-lhe)))
1915         (message "Loading file in batch Emacs... done, returned %S" ret-val)
1916         (setenv old-loadpath))
1917       ;; Fix-me: how do you check the exit status on different platforms?
1918       (setq whole-result (buffer-substring-no-properties (point-min) (point-max)))
1919       (condition-case err
1920           (progn
1921             (goto-char (point-min))
1922             (search-forward "STARTHERE")
1923             (search-forward "(")
1924             (backward-char)
1925             (setq result (read (current-buffer))))
1926         (error (message "")
1927                ;; Process should probably have failed if we are here,
1928                ;; but anyway... ;-)
1929                (setq batch-error
1930                      (concat "Sorry, batch Emacs failed. It returned this message:\n\n"
1931                              whole-result
1932                              (if is-downloading
1933                                  (concat
1934                                   "\n--------\n"
1935                                   "The error may depend on that not all needed files are yet downloaded.\n")
1936                                "\n")))
1937                )))
1938     (with-current-buffer out-buf
1939       (let ((here (point))
1940             (inhibit-read-only t))
1941         (save-restriction
1942           (widen)
1943           (goto-char (point-max))
1944           (if batch-error
1945               (progn
1946                 (insert "\n\n")
1947                 (insert (propertize batch-error 'face 'web-vcs-red)))
1948           (insert (propertize "\n\nThis file added the following to `load-history':\n\n"
1949                               'face '(:height 1.5)))
1950           (insert "   (\"" (car result) "\"\n")
1951           (dolist (e (cdr result))
1952             (insert (format "    %S" e))
1953             (cond ((stringp e)) ;; Should not happen...
1954                   ;; Variables
1955                   ((symbolp e)
1956                    (insert "  - ")
1957                    (insert (if (not (boundp e))
1958                                (propertize "New" 'face 'web-vcs-yellow)
1959                              (let ((e-file (symbol-file e)))
1960                                (if (funcall is-same-file e-file)
1961                                    (propertize "Same file now" 'face 'web-vcs-green)
1962                                  (let* ((fun-web-auto (get e 'web-autoload))
1963                                         (fun-sub-url (nth 2 fun-web-auto)))
1964                                    (if (and fun-sub-url
1965                                             (string= fun-sub-url active-sub-url))
1966                                        (propertize "Web download, matches current download"
1967                                                    'face 'web-vcs-yellow)
1968                                      (propertize (format "Loaded from %S now" e-file)
1969                                                  'face 'web-vcs-red))))))))
1970                   ;; provide
1971                   ((eq (car e) 'provide)
1972                    (insert "  - ")
1973                    (let* ((feat (car e))
1974                           (feat-name (symbol-name feat)))
1975                      (insert (cond
1976                               ((not (featurep feat))
1977                                (if (or (string= elisp-feature-name
1978                                                 (symbol-name (cdr e))))
1979                                    (propertize "Web download, matches file name" 'face 'web-vcs-green)
1980                                  (propertize "Does not match file name" 'face 'web-vcs-red)))
1981                               (t
1982                                ;; symbol-file will be where it is loaded
1983                                ;; so check load-path instead.
1984                                (let ((file (locate-library feat-name)))
1985                                  (if (funcall is-same-file file)
1986                                      (propertize "Probably loaded from same file now" 'face 'web-vcs-yellow)
1987                                    (propertize (format "Probably loaded from %S now" file)
1988                                                'face 'web-vcs-yellow))))))))
1989                   ;; require
1990                   ((eq (car e) 'require)
1991                    (if (featurep (cdr e))
1992                        (insert "  - " (propertize "Loaded now" 'face 'web-vcs-green))
1993                      (insert "  - " (propertize "Not loaded now" 'face 'web-vcs-yellow))))
1994                   ;; Functions
1995                   ((memq (car e) '( defun macro))
1996                    (insert "  - ")
1997                    (let ((fun (cdr e)))
1998                      (insert (if (functionp fun)
1999                                  (let ((e-file (symbol-file e)))
2000                                    (if (funcall is-same-file e-file)
2001                                        (propertize "Same file now" 'face 'web-vcs-green)
2002                                      (let* ((fun-web-auto (get fun 'web-autoload))
2003                                             (fun-sub-url (nth 2 fun-web-auto)))
2004                                        ;; Fix-me: check for temp download file.
2005                                        (if (string= fun-sub-url active-sub-url)
2006                                            (propertize "Web download, matches current download"
2007                                                        'face 'web-vcs-yellow)
2008                                          (propertize (format "Loaded from %S now" e-file)
2009                                                      'face 'web-vcs-yellow)))))
2010                                ;; Note that web autoloaded functions are already defined.
2011                                (propertize "New" 'face 'web-vcs-yellow))))))
2012             (insert "\n"))
2013           (insert "    )\n")
2014           (goto-char here))))
2015       (set-buffer-modified-p nil))))
2016
2017
2018 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2019 ;;; Specific for nXhtml
2020
2021 (defvar nxhtml-web-vcs-base-url "http://bazaar.launchpad.net/%7Enxhtml/nxhtml/main/")
2022
2023 ;; Fix-me: make gen for 'lp etc
2024 (defun nxhtml-download-root-url (revision)
2025   (let* ((base-url nxhtml-web-vcs-base-url)
2026          (files-url (concat base-url "files/"))
2027          (rev-part (if revision (number-to-string revision) "head%3A/")))
2028     (concat files-url rev-part)))
2029
2030 (defun web-vcs-nxhtml ()
2031   "Install nXhtml.
2032 Download and install nXhtml."
2033   (interactive)
2034   (catch 'command-level
2035     (setq debug-on-error t)
2036     (let* ((this-dir (file-name-directory web-vcs-el-this))
2037            (root-url (nxhtml-download-root-url nil))
2038            ;;(files '("nxhtml-web-vcs.el" "nxhtml-base.el"))
2039            (files '("nxhtml-web-vcs.el"))
2040            (files2 (mapcar (lambda (file)
2041                              (cons file (expand-file-name file this-dir)))
2042                            files))
2043            need-dl)
2044       (dolist (file files2)
2045         (unless (file-exists-p (cdr file))
2046           (setq need-dl t)))
2047       (when need-dl
2048         (let ((prompt
2049                (concat "Welcome to install nXhtml."
2050                        "\nFirst the nXhtml specific web install file must be downloaded."
2051                        "\nYou will get a chance to review it before it is used."
2052                        "\n\nDo you want to continue? ")))
2053           (unless (y-or-n-p prompt)
2054             (message "Aborted")
2055             (throw 'command-level nil))))
2056       (message nil)
2057       (unless (get-buffer-window "*Messages*")
2058         (web-vcs-display-messages t)
2059         (delete-other-windows))
2060       (dolist (file files2)
2061         (unless (file-exists-p (cdr file))
2062           (web-vcs-get-missing-matching-files 'lp root-url this-dir (car file))))
2063       (load (cdr (car files2))))
2064     (call-interactively 'nxhtml-setup-install)))
2065
2066
2067 (provide 'web-vcs)
2068 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
2069 ;;; web-vcs.el ends here