Remove non-free old and crusty clearcase pkg
[packages] / xemacs-packages / semantic / semanticdb-file.el
1 ;;; semanticdb-file.el --- Save a semanticdb to a cache file.
2
3 ;;; Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007 Eric M. Ludlam
4
5 ;; Author: Eric M. Ludlam <zappo@gnu.org>
6 ;; Keywords: tags
7 ;; X-RCS: $Id: semanticdb-file.el,v 1.1 2007-11-26 15:10:46 michaels Exp $
8
9 ;; This file is not part of GNU Emacs.
10
11 ;; Semanticdb is free software; you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; any later version.
15
16 ;; This software is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
23 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
24 ;; Boston, MA 02110-1301, USA.
25 ;; 
26 ;;; Commentary:
27 ;;
28 ;; A set of semanticdb classes for persistently saving caches on disk.
29 ;;
30
31 (require 'semanticdb)
32 (require 'inversion)
33 (require 'cedet-files)
34
35 (defvar semanticdb-file-version semantic-version
36   "Version of semanticdb we are writing files to disk with.")
37 (defvar semanticdb-file-incompatible-version "1.4"
38   "Version of semanticdb we are not reverse compatible with.")
39
40 ;;; Settings
41 ;;
42 ;;;###autoload
43 (defcustom semanticdb-default-file-name "semantic.cache"
44   "*File name of the semantic tag cache."
45   :group 'semanticdb
46   :type 'string)
47
48 ;;;###autoload
49 (defcustom semanticdb-default-save-directory nil
50   "*Directory name where semantic cache files are stored.
51 If this value is nil, files are saved in the current directory.  If the value
52 is a valid directory, then it overrides `semanticdb-default-file-name' and
53 stores caches in a coded file name in this directory."
54   :group 'semanticdb
55   :type '(choice :tag "Default-Directory"
56                  :menu-tag "Default-Directory"
57                  (const :tag "Use current directory" :value nil)
58                  (directory)))
59
60 ;;;###autoload
61 (defcustom semanticdb-persistent-path '(project)
62   "*List of valid paths that semanticdb will cache tags to.
63 When `global-semanticdb-minor-mode' is active, tag lists will
64 be saved to disk when Emacs exits.  Not all directories will have
65 tags that should be saved.
66 The value should be a list of valid paths.  A path can be a string,
67 indicating a directory in which to save a variable.  An element in the
68 list can also be a symbol.  Valid symbols are `never', which will
69 disable any saving anywhere, `always', which enables saving
70 everywhere, or `project', which enables saving in any directory that
71 passes a list of predicates in `semanticdb-project-predicate-functions'."
72   :group 'semanticdb
73   :type nil)
74
75 (defcustom semanticdb-save-database-hooks nil
76   "*Hooks run after a database is saved.
77 Each function is called with one argument, the object representing
78 the database recently written."
79   :group 'semanticdb
80   :type 'hook)
81
82 (defvar semanticdb-dir-sep-char (if (boundp 'directory-sep-char)
83                                     (symbol-value 'directory-sep-char)
84                                   ?/)
85   "Character used for directory separation.
86 Obsoleted in some versions of Emacs.  Needed in others.
87 NOTE: This should get deleted from semantic soon.")
88
89 (defun semanticdb-fix-pathname (dir)
90   "If DIR is broken, fix it.
91 Force DIR to end with a /.
92 Note: Same as `file-name-as-directory'.
93 NOTE: This should get deleted from semantic soon."
94   (file-name-as-directory dir))
95 ;; I didn't initially know about the above fcn.  Keep the below as a
96 ;; reference.  Delete it someday once I've proven everything is the same.
97 ;;  (if (not (= semanticdb-dir-sep-char (aref path (1- (length path)))))
98 ;;      (concat path (list semanticdb-dir-sep-char))
99 ;;    path))
100
101 ;;; Classes
102 ;;
103 ;;;###autoload
104 (defclass semanticdb-project-database-file (semanticdb-project-database
105                                             eieio-persistent)
106   ((file-header-line :initform ";; SEMANTICDB Tags save file")
107    (semantic-tag-version :initarg :semantic-tag-version
108                          :initform "1.4"
109                          :documentation
110                          "The version of the tags saved.
111 The default value is 1.4.  In semantic 1.4 there was no versioning, so
112 when those files are loaded, this becomes the version number.
113 To save the version number, we must hand-set this version string.")
114    (semanticdb-version :initarg :semanticdb-version
115                        :initform "1.4"
116                        :documentation
117                        "The version of the object system saved.
118 The default value is 1.4.  In semantic 1.4, there was no versioning,
119 so when those files are loaded, this becomes the version number.
120 To save the version number, we must hand-set this version string.")
121    )
122   "Database of file tables saved to disk.")
123
124 ;;; Code:
125 ;;
126 (defmethod semanticdb-create-database :STATIC ((dbc semanticdb-project-database-file)
127                                                directory)
128   "Create a new semantic database for DIRECTORY and return it.
129 If a database for DIRECTORY has already been loaded, return it.
130 If a database for DIRECTORY exists, then load that database, and return it.
131 If DIRECTORY doesn't exist, create a new one."
132   (let* ((fn (semanticdb-cache-filename dbc directory))
133          (db (or (semanticdb-file-loaded-p fn)
134                  (if (file-exists-p fn)
135                      (progn
136                        (semanticdb-load-database fn))))))
137     (unless db
138       (setq db (make-instance
139                 dbc  ; Create the database requested.  Perhaps
140                 (concat (file-name-nondirectory
141                          (directory-file-name
142                           (file-name-directory fn)))
143                         "/")
144                 :file fn :tables nil
145                 :semantic-tag-version semantic-version
146                 :semanticdb-version semanticdb-file-version)))
147     ;; Set this up here.   We can't put it in the constructor because it
148     ;; would be saved, and we want DB files to be portable.
149     (oset db reference-directory directory)
150     db))
151
152 ;;; File IO
153 (defun semanticdb-load-database (filename)
154   "Load the database FILENAME."
155   (condition-case foo
156       (let* ((r (eieio-persistent-read filename))
157              (c (semanticdb-get-database-tables r))
158              (tv (oref r semantic-tag-version))
159              (fv (oref r semanticdb-version))
160              )
161         ;; Restore the parent-db connection
162         (while c
163           (oset (car c) parent-db r)
164           (setq c (cdr c)))
165         (if (not (inversion-test 'semanticdb-file fv))
166             (when (inversion-test 'semantic-tag tv)
167               ;; Incompatible version.  Flush tables.
168               (semanticdb-flush-database-tables r)
169               ;; Reset the version to new version.
170               (oset r semantic-tag-version semantic-tag-version)
171               ;; Warn user
172               (message "Semanticdb file is old.  Starting over for %s"
173                        filename)
174               )
175           ;; Version is not ok.  Flush whole system
176           (message "semanticdb file is old.  Starting over for %s"
177                    filename)
178           ;; This database is so old, we need to replace it.
179           ;; We also need to delete it from the instance tracker.
180           (delete-instance r)
181           (setq r nil))
182         r)
183     (error (message "Cache Error: %s, Restart" foo)
184            nil)))
185
186 ;;;###autoload
187 (defun semanticdb-file-loaded-p (filename)
188   "Return the project belonging to FILENAME if it was already loaded."
189   (eieio-instance-tracker-find filename 'file 'semanticdb-database-list))
190
191 (defmethod semanticdb-save-db ((DB semanticdb-project-database-file))
192   "Write out the database DB to its file.
193 If DB is not specified, then use the current database."
194   (let ((objname (oref DB file)))
195     (when (and (semanticdb-live-p DB)
196                (semanticdb-write-directory-p DB))
197       (message "Saving tag summary for %s..." objname)
198       (condition-case foo
199           (eieio-persistent-save (or DB semanticdb-current-database))
200         (file-error ; System error saving?  Ignore it.
201          (message "Error saving %s" objname))
202         (error
203          (cond
204           ((and (listp foo)
205                 (stringp (nth 1 foo))
206                 (string-match "write[- ]protected" (nth 1 foo)))
207            (message (nth 1 foo)))
208           ((and (listp foo)
209                 (stringp (nth 1 foo))
210                 (string-match "no such directory" (nth 1 foo)))
211            (message (nth 1 foo)))
212           (t
213            (if (y-or-n-p (format "Skip Error: %S ?" (car (cdr foo))))
214                nil
215              (error "%S" (car (cdr foo))))))))
216       (run-hook-with-args 'semanticdb-save-database-hooks
217                           (or DB semanticdb-current-database))
218       (message "Saving tag summary for %s...done" objname))
219     ))
220
221 ;;;###autoload
222 (defmethod semanticdb-live-p ((obj semanticdb-project-database))
223   "Return non-nil if the file associated with OBJ is live.
224 Live databases are objects associated with existing directories."
225   (and (slot-boundp obj 'reference-directory)
226        (file-exists-p (oref obj reference-directory))))
227
228 (defmethod semanticdb-live-p ((obj semanticdb-table))
229   "Return non-nil if the file associated with OBJ is live.
230 Live files are either buffers in Emacs, or files existing on the filesystem."
231   (let ((full-filename (semanticdb-full-filename obj)))
232     (or (get-file-buffer full-filename)
233         (file-exists-p full-filename))))
234
235 (defmethod object-write ((obj semanticdb-table))
236   "When writing a table, we have to make sure we deoverlay it first.
237 Restore the overlays after writting.
238 Argument OBJ is the object to write."
239   (if (semanticdb-live-p obj)
240       (let ((b (get-file-buffer (semanticdb-full-filename obj))))
241         (save-excursion
242           (if b (progn (set-buffer b)
243                        ;; Try to get an accurate unmatched syntax table.
244                        (when (and (boundp semantic-show-unmatched-syntax-mode)
245                                   semantic-show-unmatched-syntax-mode)
246                          ;; Only do this if the user runs unmatched syntax
247                          ;; mode display enties.
248                          (oset obj unmatched-syntax
249                                (semantic-show-unmatched-lex-tokens-fetch))
250                          )
251                        ;; Unlink the cache.  When there are arrors,
252                        ;; reset the master cache.
253                        (condition-case nil
254                            (semantic--tag-unlink-cache-from-buffer)
255                          (error
256                           (condition-case nil
257                               (semantic-clear-toplevel-cache)
258                             (error
259                              (semantic--set-buffer-cache nil)))))
260                        (oset obj pointmax (point-max)))))
261         (call-next-method)
262         (save-excursion
263           (if b (progn (set-buffer b) (semantic--tag-link-cache-to-buffer)))
264           (oset obj unmatched-syntax nil))
265         )))
266
267 ;;; State queries
268 ;;
269 (defmethod semanticdb-write-directory-p ((obj semanticdb-project-database-file))
270   "Return non-nil if OBJ should be written to disk.
271 Uses `semanticdb-persistent-path' to determine the return value."
272   (let ((path semanticdb-persistent-path))
273     (catch 'found
274       (while path
275         (cond ((stringp (car path))
276                (if (string= (oref obj reference-directory) (car path))
277                    (throw 'found t)))
278               ((eq (car path) 'project)
279                (if semanticdb-project-predicate-functions
280                    (if (run-hook-with-args-until-success
281                         'semanticdb-project-predicate-functions
282                         (oref obj reference-directory))
283                        (throw 'found t))
284                  ;; If the mode is 'project, and there are no project
285                  ;; modes, then just always save the file.  If users
286                  ;; wish to restrict the search, modify
287                  ;; `semanticdb-persistent-path' to include desired paths.
288                  (if (= (length semanticdb-persistent-path) 1)
289                      (throw 'found t))
290                  ))
291               ((eq (car path) 'never)
292                (throw 'found nil))
293               ((eq (car path) 'always)
294                (throw 'found t))
295               (t (error "Invalid path %S" (car path))))
296         (setq path (cdr path)))
297       (call-next-method))
298     ))
299
300 ;;; Filename manipulation
301 ;;
302 (defmethod semanticdb-file-name-non-directory :STATIC
303   ((dbclass semanticdb-project-database-file))
304   "Return the file name DBCLASS will use.
305 File name excludes any directory part."
306   semanticdb-default-file-name)
307
308 (defmethod semanticdb-file-name-directory :STATIC
309   ((dbclass semanticdb-project-database-file) directory)
310   "Return the relative directory to where DBCLASS will save its cache file.
311 The returned path is related to DIRECTORY."
312   (if semanticdb-default-save-directory
313       (let ((file (cedet-directory-name-to-file-name directory)))
314         ;; Now create a filename for the cache file in
315         ;; ;`semanticdb-default-save-directory'.
316         (expand-file-name
317          (concat (file-name-as-directory semanticdb-default-save-directory)
318                  file)))
319     directory))
320
321 (defmethod semanticdb-cache-filename :STATIC
322   ((dbclass semanticdb-project-database-file) path)
323   "For DBCLASS, return a file to a cache file belonging to PATH.
324 This could be a cache file in the current directory, or an encoded file
325 name in a secondary directory."
326   (concat (semanticdb-file-name-directory dbclass path)
327           (semanticdb-file-name-non-directory dbclass)))
328
329 ;;;###autoload
330 (defmethod semanticdb-full-filename ((obj semanticdb-project-database-file))
331   "Fetch the full filename that OBJ refers to."
332   (oref obj file))
333
334 (defmethod semanticdb-full-filename ((obj semanticdb-table))
335   "Fetch the full filename that OBJ refers to."
336   (concat (file-name-as-directory
337            (oref (oref obj parent-db) reference-directory))
338           (oref obj file)))
339
340 ;;; Compatibility
341 ;;
342 ;; replace-regexp-in-string is in subr.el in Emacs 21.  Provide
343 ;; here for compatibility.
344
345 (if (not (fboundp 'replace-regexp-in-string))
346
347 (defun replace-regexp-in-string (regexp rep string &optional
348                                         fixedcase literal subexp start)
349   "Replace all matches for REGEXP with REP in STRING.
350
351 Return a new string containing the replacements.
352
353 Optional arguments FIXEDCASE, LITERAL and SUBEXP are like the
354 arguments with the same names of function `replace-match'.  If START
355 is non-nil, start replacements at that index in STRING.
356
357 REP is either a string used as the NEWTEXT arg of `replace-match' or a
358 function.  If it is a function it is applied to each match to generate
359 the replacement passed to `replace-match'; the match-data at this
360 point are such that match 0 is the function's argument.
361
362 To replace only the first match (if any), make REGEXP match up to \\'
363 and replace a sub-expression, e.g.
364   (replace-regexp-in-string \"\\(foo\\).*\\'\" \"bar\" \" foo foo\" nil nil 1)
365     => \" bar foo\""
366
367   ;; To avoid excessive consing from multiple matches in long strings,
368   ;; don't just call `replace-match' continually.  Walk down the
369   ;; string looking for matches of REGEXP and building up a (reversed)
370   ;; list MATCHES.  This comprises segments of STRING which weren't
371   ;; matched interspersed with replacements for segments that were.
372   ;; [For a `large' number of replacements it's more efficient to
373   ;; operate in a temporary buffer; we can't tell from the function's
374   ;; args whether to choose the buffer-based implementation, though it
375   ;; might be reasonable to do so for long enough STRING.]
376   (let ((l (length string))
377         (start (or start 0))
378         matches str mb me)
379     (save-match-data
380       (while (and (< start l) (string-match regexp string start))
381         (setq mb (match-beginning 0)
382               me (match-end 0))
383         ;; If we matched the empty string, make sure we advance by one char
384         (when (= me mb) (setq me (min l (1+ mb))))
385         ;; Generate a replacement for the matched substring.
386         ;; Operate only on the substring to minimize string consing.
387         ;; Set up match data for the substring for replacement;
388         ;; presumably this is likely to be faster than munging the
389         ;; match data directly in Lisp.
390         (string-match regexp (setq str (substring string mb me)))
391         (setq matches
392               (cons (replace-match (if (stringp rep)
393                                        rep
394                                      (funcall rep (match-string 0 str)))
395                                    fixedcase literal str subexp)
396                     (cons (substring string start mb) ; unmatched prefix
397                           matches)))
398         (setq start me))
399       ;; Reconstruct a string from the pieces.
400       (setq matches (cons (substring string start l) matches)) ; leftover
401       (apply #'concat (nreverse matches)))))
402
403 )
404
405 (provide 'semanticdb-file)
406
407 ;;; semanticdb-file.el ends here