]> matita.cs.unibo.it Git - helm.git/blob - matita/matitaScript.ml
types2006 patch
[helm.git] / matita / matitaScript.ml
1 (* Copyright (C) 2004-2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 open Printf
29 open GrafiteTypes
30
31 module TA = GrafiteAst
32
33 let debug = false
34 let debug_print = if debug then prerr_endline else ignore
35
36   (** raised when one of the script margins (top or bottom) is reached *)
37 exception Margin
38 exception NoUnfinishedProof
39 exception ActionCancelled of string
40
41 let safe_substring s i j =
42   try String.sub s i j with Invalid_argument _ -> assert false
43
44 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*"
45 let heading_nl_RE' = Pcre.regexp "^(\\s*\n\\s*)"
46 let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$"
47 let multiline_RE = Pcre.regexp "^\n[^\n]+$"
48 let newline_RE = Pcre.regexp "\n"
49  
50 let comment str =
51   if Pcre.pmatch ~rex:multiline_RE str then
52     "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " *)"
53   else
54     "\n(**\n" ^ str ^ "\n*)"
55                      
56 let first_line s =
57   let s = Pcre.replace ~rex:heading_nl_RE s in
58   try
59     let nl_pos = String.index s '\n' in
60     String.sub s 0 nl_pos
61   with Not_found -> s
62
63   (** creates a statement AST for the Goal tactic, e.g. "goal 7" *)
64 let goal_ast n =
65   let module A = GrafiteAst in
66   let loc = HExtlib.dummy_floc in
67   A.Executable (loc, A.Tactical (loc,
68     A.Tactic (loc, A.Goal (loc, n)),
69     Some (A.Dot loc)))
70
71 type guistuff = {
72   mathviewer:MatitaTypes.mathViewer;
73   urichooser: UriManager.uri list -> UriManager.uri list;
74   ask_confirmation: title:string -> message:string -> [`YES | `NO | `CANCEL];
75   develcreator: containing:string option -> unit;
76   mutable filenamedata: string option * MatitamakeLib.development option
77 }
78
79 let eval_with_engine guistuff lexicon_status grafite_status user_goal
80  skipped_txt nonskipped_txt st
81 =
82   let module TAPp = GrafiteAstPp in
83   let module DTE = DisambiguateTypes.Environment in
84   let module DP = DisambiguatePp in
85   let parsed_text_length =
86     String.length skipped_txt + String.length nonskipped_txt 
87   in
88   let text = skipped_txt ^ nonskipped_txt in
89   let prefix_len = MatitaGtkMisc.utf8_string_length skipped_txt in
90   let enriched_history_fragment =
91    MatitaEngine.eval_ast ~do_heavy_checks:true
92     lexicon_status grafite_status (text,prefix_len,st)
93   in
94   let enriched_history_fragment = List.rev enriched_history_fragment in
95   (* really fragile *)
96   let res,_ = 
97     List.fold_left 
98       (fun (acc, to_prepend) (status,alias) ->
99        match alias with
100        | None -> (status,to_prepend ^ nonskipped_txt)::acc,""
101        | Some (k,((v,_) as value)) ->
102             let newtxt = DP.pp_environment (DTE.add k value DTE.empty) in
103             (status,to_prepend ^ newtxt ^ "\n")::acc, "")
104       ([],skipped_txt) enriched_history_fragment
105   in
106   res,parsed_text_length
107
108 let wrap_with_developments guistuff f arg = 
109   try 
110     f arg
111   with
112   | DependenciesParser.UnableToInclude what 
113   | LexiconEngine.IncludedFileNotCompiled what 
114   | GrafiteEngine.IncludedFileNotCompiled what as exc ->
115       let compile_needed_and_go_on d =
116         let target = Pcre.replace ~pat:"lexicon$" ~templ:"moo" what in
117         let refresh_cb () = 
118           while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
119         in
120         if not(MatitamakeLib.build_development_in_bg ~target refresh_cb d) then
121           raise exc
122         else
123           f arg
124       in
125       let do_nothing () = raise (ActionCancelled "Inclusion not performed") in
126       let handle_with_devel d =
127         let name = MatitamakeLib.name_for_development d in
128         let title = "Unable to include " ^ what in
129         let message = 
130           what ^ " is handled by development <b>" ^ name ^ "</b>.\n\n" ^
131           "<i>Should I compile it and Its dependencies?</i>"
132         in
133         (match guistuff.ask_confirmation ~title ~message with
134         | `YES -> compile_needed_and_go_on d
135         | `NO -> raise exc
136         | `CANCEL -> do_nothing ())
137       in
138       let handle_without_devel filename =
139         let title = "Unable to include " ^ what in
140         let message = 
141          what ^ " is <b>not</b> handled by a development.\n" ^
142          "All dependencies are automatically solved for a development.\n\n" ^
143          "<i>Do you want to set up a development?</i>"
144         in
145         (match guistuff.ask_confirmation ~title ~message with
146         | `YES -> 
147             (match filename with
148             | Some f -> 
149                 guistuff.develcreator ~containing:(Some (Filename.dirname f))
150             | None -> guistuff.develcreator ~containing:None);
151             do_nothing ()
152         | `NO -> raise exc
153         | `CANCEL -> do_nothing())
154       in
155       match guistuff.filenamedata with
156       | None,None -> handle_without_devel None
157       | None,Some d -> handle_with_devel d
158       | Some f,_ ->
159           match MatitamakeLib.development_for_dir (Filename.dirname f) with
160           | None -> handle_without_devel (Some f)
161           | Some d -> handle_with_devel d
162 ;;
163     
164 let eval_with_engine
165      guistuff lexicon_status grafite_status user_goal 
166        skipped_txt nonskipped_txt st
167 =
168   wrap_with_developments guistuff
169     (eval_with_engine 
170       guistuff lexicon_status grafite_status user_goal 
171         skipped_txt nonskipped_txt) st
172 ;;
173
174 let pp_eager_statement_ast =
175   GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
176     ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
177  
178 let rec eval_macro include_paths (buffer : GText.buffer) guistuff lexicon_status grafite_status user_goal unparsed_text parsed_text script mac =
179   let module TAPp = GrafiteAstPp in
180   let module MQ = MetadataQuery in
181   let module MDB = LibraryDb in
182   let module CTC = CicTypeChecker in
183   let module CU = CicUniv in
184   (* no idea why ocaml wants this *)
185   let parsed_text_length = String.length parsed_text in
186   let dbd = LibraryDb.instance () in
187   let pp_macro = 
188     let f t = ProofEngineReduction.replace 
189       ~equality:(fun _ t -> match t with Cic.Meta _ -> true | _ -> false)
190       ~what:[()] ~with_what:[Cic.Implicit None] ~where:t
191     in
192     let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
193     TAPp.pp_macro 
194       ~term_pp:(fun x -> 
195         ApplyTransformation.txt_of_cic_term max_int metasenv [] (f x))
196   in
197   match mac with
198   (* WHELP's stuff *)
199   | TA.WMatch (loc, term) -> 
200      let l =  Whelp.match_term ~dbd term in
201      let entry = `Whelp (pp_macro mac, l) in
202      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
203      [], parsed_text_length
204   | TA.WInstance (loc, term) ->
205      let l = Whelp.instance ~dbd term in
206      let entry = `Whelp (pp_macro mac, l) in
207      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
208      [], parsed_text_length
209   | TA.WLocate (loc, s) -> 
210      let l = Whelp.locate ~dbd s in
211      let entry = `Whelp (pp_macro mac, l) in
212      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
213      [], parsed_text_length
214   | TA.WElim (loc, term) ->
215      let uri =
216        match term with
217        | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
218        | _ -> failwith "Not a MutInd"
219      in
220      let l = Whelp.elim ~dbd uri in
221      let entry = `Whelp (pp_macro mac, l) in
222      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
223      [], parsed_text_length
224   | TA.WHint (loc, term) ->
225      let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
226      let l = List.map fst (MQ.experimental_hint ~dbd s) in
227      let entry = `Whelp (pp_macro mac, l) in
228      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
229      [], parsed_text_length
230   (* REAL macro *)
231   | TA.Hint loc -> 
232       let user_goal' =
233        match user_goal with
234           Some n -> n
235         | None -> raise NoUnfinishedProof
236       in
237       let proof = GrafiteTypes.get_current_proof grafite_status in
238       let proof_status = proof,user_goal' in
239       let l = List.map fst (MQ.experimental_hint ~dbd proof_status) in
240       let selected = guistuff.urichooser l in
241       (match selected with
242       | [] -> [], parsed_text_length
243       | [uri] -> 
244           let suri = UriManager.string_of_uri uri in
245           let ast loc =
246             TA.Executable (loc, (TA.Tactical (loc,
247               TA.Tactic (loc,
248                 TA.Apply (loc, CicNotationPt.Uri (suri, None))),
249                 Some (TA.Dot loc)))) in
250           let text =
251            comment parsed_text ^ "\n" ^
252             pp_eager_statement_ast (ast HExtlib.dummy_floc) in
253           let text_len = MatitaGtkMisc.utf8_string_length text in
254           let loc = HExtlib.floc_of_loc (0,text_len) in
255           let statement = `Ast (GrafiteParser.LSome (ast loc),text) in
256           let res,_parsed_text_len =
257            eval_statement include_paths buffer guistuff lexicon_status
258             grafite_status user_goal script statement
259           in
260            (* we need to replace all the parsed_text *)
261            res,String.length parsed_text
262       | _ -> 
263           HLog.error 
264             "The result of the urichooser should be only 1 uri, not:\n";
265           List.iter (
266             fun u -> HLog.error (UriManager.string_of_uri u ^ "\n")
267           ) selected;
268           assert false)
269   | TA.Check (_,term) ->
270       let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
271       let context =
272        match user_goal with
273           None -> []
274         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
275       let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
276       let t_and_ty = Cic.Cast (term,ty) in
277       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
278       [], parsed_text_length
279   (* TODO *)
280   | TA.Quit _ -> failwith "not implemented"
281   | TA.Print (_,kind) -> failwith "not implemented"
282   | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
283   | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
284                                 
285 and eval_executable include_paths (buffer : GText.buffer) guistuff
286 lexicon_status grafite_status user_goal unparsed_text skipped_txt nonskipped_txt
287 script ex loc
288 =
289  let module TAPp = GrafiteAstPp in
290  let module MD = GrafiteDisambiguator in
291  let module ML = MatitaMisc in
292   try
293    begin
294     match ex with
295      | TA.Command (_,TA.Set (_,"baseuri",u)) ->
296         if  Http_getter_storage.is_read_only u then
297           raise (ActionCancelled ("baseuri " ^ u ^ " is readonly"));
298         if not (Http_getter_storage.is_empty u) then
299          (match 
300             guistuff.ask_confirmation 
301               ~title:"Baseuri redefinition" 
302               ~message:(
303                 "Baseuri " ^ u ^ " already exists.\n" ^
304                 "Do you want to redefine the corresponding "^
305                 "part of the library?")
306           with
307            | `YES -> LibraryClean.clean_baseuris [u]
308            | `NO -> ()
309            | `CANCEL -> raise MatitaTypes.Cancel)
310      | _ -> ()
311    end;
312    eval_with_engine
313     guistuff lexicon_status grafite_status user_goal skipped_txt nonskipped_txt
314      (TA.Executable (loc, ex))
315   with
316      MatitaTypes.Cancel -> [], 0
317    | GrafiteEngine.Macro (_loc,lazy_macro) ->
318       let context =
319        match user_goal with
320           None -> []
321         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
322       let grafite_status,macro = lazy_macro context in
323        eval_macro include_paths buffer guistuff lexicon_status grafite_status
324         user_goal unparsed_text (skipped_txt ^ nonskipped_txt) script macro
325
326 and eval_statement include_paths (buffer : GText.buffer) guistuff lexicon_status
327  grafite_status user_goal script statement
328 =
329   let (lexicon_status,st), unparsed_text =
330     match statement with
331     | `Raw text ->
332         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
333         let ast = 
334           wrap_with_developments guistuff
335             (GrafiteParser.parse_statement 
336               (Ulexing.from_utf8_string text) ~include_paths) lexicon_status 
337         in
338           ast, text
339     | `Ast (st, text) -> (lexicon_status, st), text
340   in
341   let text_of_loc floc = 
342     let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
343     let start, stop = HExtlib.loc_of_floc floc in 
344     let floc = HExtlib.floc_of_loc (0, start) in
345     let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
346     let floc = HExtlib.floc_of_loc (0, stop) in
347     let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
348     txt,nonskipped_txt,skipped_txt,len
349   in 
350   match st with
351   | GrafiteParser.LNone loc ->
352       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
353        [(grafite_status,lexicon_status),parsed_text],
354         parsed_text_length
355   | GrafiteParser.LSome (GrafiteAst.Comment (loc, _)) -> 
356       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
357       let remain_len = String.length unparsed_text - parsed_text_length in
358       let s = String.sub unparsed_text parsed_text_length remain_len in
359       let s,len = 
360        try
361         eval_statement include_paths buffer guistuff lexicon_status
362          grafite_status user_goal script (`Raw s)
363        with
364           HExtlib.Localized (floc, exn) ->
365            HExtlib.raise_localized_exception 
366              ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
367         | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
368            raise
369             (GrafiteDisambiguator.DisambiguationError
370               (offset+parsed_text_length, errorll))
371       in
372       (match s with
373       | (statuses,text)::tl ->
374          (statuses,parsed_text ^ text)::tl,parsed_text_length + len
375       | [] -> [], 0)
376   | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) ->
377      let _, nonskipped, skipped, parsed_text_length = 
378        text_of_loc loc 
379      in
380       eval_executable include_paths buffer guistuff lexicon_status
381        grafite_status user_goal unparsed_text skipped nonskipped script ex loc
382   
383 let fresh_script_id =
384   let i = ref 0 in
385   fun () -> incr i; !i
386
387 class script  ~(source_view: GSourceView.source_view)
388               ~(mathviewer: MatitaTypes.mathViewer) 
389               ~set_star
390               ~ask_confirmation
391               ~urichooser 
392               ~develcreator 
393               () =
394 let buffer = source_view#buffer in
395 let source_buffer = source_view#source_buffer in
396 let initial_statuses () =
397  (* these include_paths are used only to load the initial notation *)
398  let include_paths =
399   Helm_registry.get_list Helm_registry.string "matita.includes" in
400  let lexicon_status =
401   CicNotation2.load_notation ~include_paths
402    BuildTimeConf.core_notation_script in
403  let grafite_status = GrafiteSync.init () in
404   grafite_status,lexicon_status
405 in
406 object (self)
407   val mutable include_paths =
408    Helm_registry.get_list Helm_registry.string "matita.includes"
409
410   val scriptId = fresh_script_id ()
411   
412   val guistuff = {
413     mathviewer = mathviewer;
414     urichooser = urichooser;
415     ask_confirmation = ask_confirmation;
416     develcreator = develcreator;
417     filenamedata = (None, None)} 
418   
419   method private getFilename =
420     match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
421
422   method filename = self#getFilename
423     
424   method private ppFilename =
425     match guistuff.filenamedata with 
426     | Some f,_ -> f 
427     | None,_ -> sprintf ".unnamed%d.ma" scriptId
428   
429   initializer 
430     ignore (GMain.Timeout.add ~ms:300000 
431        ~callback:(fun _ -> self#_saveToBackupFile ();true));
432     ignore (buffer#connect#modified_changed 
433       (fun _ -> set_star (Filename.basename self#ppFilename) buffer#modified))
434
435   val mutable statements = []    (** executed statements *)
436
437   val mutable history = [ initial_statuses () ]
438     (** list of states before having executed statements. Head element of this
439       * list is the current state, last element is the state at the beginning of
440       * the script.
441       * Invariant: this list length is 1 + length of statements *)
442
443   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
444   val mutable userGoal = None
445
446   (** text mark and tag representing locked part of a script *)
447   val locked_mark =
448     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
449   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
450   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
451
452   method locked_mark = locked_mark
453   method locked_tag = locked_tag
454   method error_tag = error_tag
455
456     (* history can't be empty, the invariant above grant that it contains at
457      * least the init grafite_status *)
458   method grafite_status = match history with (s,_)::_ -> s | _ -> assert false
459   method lexicon_status = match history with (_,ss)::_ -> ss | _ -> assert false
460
461   method private _advance ?statement () =
462    let s = match statement with Some s -> s | None -> self#getFuture in
463    HLog.debug ("evaluating: " ^ first_line s ^ " ...");
464    let (entries, parsed_len) = 
465     try
466      eval_statement include_paths buffer guistuff self#lexicon_status
467       self#grafite_status userGoal self (`Raw s)
468     with End_of_file -> raise Margin
469    in
470    let new_statuses, new_statements =
471      let statuses, texts = List.split entries in
472      statuses, texts
473    in
474    history <- new_statuses @ history;
475    statements <- new_statements @ statements;
476    let start = buffer#get_iter_at_mark (`MARK locked_mark) in
477    let new_text = String.concat "" (List.rev new_statements) in
478    if statement <> None then
479      buffer#insert ~iter:start new_text
480    else begin
481      let parsed_text = String.sub s 0 parsed_len in
482      if new_text <> parsed_text then begin
483        let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
484        buffer#delete ~start ~stop;
485        buffer#insert ~iter:start new_text;
486      end;
487    end;
488    self#moveMark (Glib.Utf8.length  new_text);
489    (* here we need to set the Goal in case we are going to cursor (or to
490       bottom) and we will face a macro *)
491    match self#grafite_status.proof_status with
492       Incomplete_proof p ->
493        userGoal <-
494          (try Some (Continuationals.Stack.find_goal p.stack)
495          with Failure _ -> None)
496     | _ -> userGoal <- None
497
498   method private _retract offset lexicon_status grafite_status new_statements
499    new_history
500   =
501    let cur_grafite_status,cur_lexicon_status =
502     match history with s::_ -> s | [] -> assert false
503    in
504     LexiconSync.time_travel ~present:cur_lexicon_status ~past:lexicon_status;
505     GrafiteSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
506     statements <- new_statements;
507     history <- new_history;
508     self#moveMark (- offset)
509
510   method advance ?statement () =
511     try
512       self#_advance ?statement ();
513       self#notify
514     with 
515     | Margin -> self#notify
516     | Not_found -> assert false
517     | exc -> self#notify; raise exc
518
519   method retract () =
520     try
521       let cmp,new_statements,new_history,(grafite_status,lexicon_status) =
522        match statements,history with
523           stat::statements, _::(status::_ as history) ->
524            assert (Glib.Utf8.validate stat);
525            Glib.Utf8.length stat, statements, history, status
526        | [],[_] -> raise Margin
527        | _,_ -> assert false
528       in
529        self#_retract cmp lexicon_status grafite_status new_statements
530         new_history;
531        self#notify
532     with 
533     | Margin -> self#notify
534     | exc -> self#notify; raise exc
535
536   method private getFuture =
537     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
538       ~stop:buffer#end_iter ()
539
540       
541   (** @param rel_offset relative offset from current position of locked_mark *)
542   method private moveMark rel_offset =
543     let mark = `MARK locked_mark in
544     let old_insert = buffer#get_iter_at_mark `INSERT in
545     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
546     let current_mark_pos = buffer#get_iter_at_mark mark in
547     let new_mark_pos =
548       match rel_offset with
549       | 0 -> current_mark_pos
550       | n when n > 0 -> current_mark_pos#forward_chars n
551       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
552     in
553     buffer#move_mark mark ~where:new_mark_pos;
554     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
555     buffer#move_mark `INSERT old_insert;
556     let mark_position = buffer#get_iter_at_mark mark in
557     if source_view#move_mark_onscreen mark then
558      begin
559       buffer#move_mark mark mark_position;
560       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
561      end;
562     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
563
564   method clean_dirty_lock =
565     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
566     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
567     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
568
569   val mutable observers = []
570
571   method addObserver (o: LexiconEngine.status -> GrafiteTypes.status -> unit) =
572     observers <- o :: observers
573
574   method private notify =
575     let lexicon_status = self#lexicon_status in
576     let grafite_status = self#grafite_status in
577     List.iter (fun o -> o lexicon_status grafite_status) observers
578
579   method loadFromFile f =
580     buffer#set_text (HExtlib.input_file f);
581     self#reset_buffer;
582     buffer#set_modified false
583     
584   method assignFileName file =
585     let abspath = MatitaMisc.absolute_path file in
586     let dirname = Filename.dirname abspath in
587     let devel = MatitamakeLib.development_for_dir dirname in
588     guistuff.filenamedata <- Some abspath, devel;
589     let include_ = 
590      match MatitamakeLib.development_for_dir dirname with
591         None -> []
592       | Some devel -> [MatitamakeLib.root_for_development devel] in
593     let include_ =
594      include_ @ (Helm_registry.get_list Helm_registry.string "matita.includes")
595     in
596      include_paths <- include_
597     
598   method saveToFile () =
599     let oc = open_out self#getFilename in
600     output_string oc (buffer#get_text ~start:buffer#start_iter
601                         ~stop:buffer#end_iter ());
602     close_out oc;
603     buffer#set_modified false
604   
605   method private _saveToBackupFile () =
606     if buffer#modified then
607       begin
608         let f = self#ppFilename ^ "~" in
609         let oc = open_out f in
610         output_string oc (buffer#get_text ~start:buffer#start_iter
611                             ~stop:buffer#end_iter ());
612         close_out oc;
613         HLog.debug ("backup " ^ f ^ " saved")                    
614       end
615   
616   method private goto_top =
617     let grafite_status,lexicon_status = 
618       let rec last x = function 
619       | [] -> x
620       | hd::tl -> last hd tl
621       in
622       last (self#grafite_status,self#lexicon_status) history
623     in
624     (* FIXME: this is not correct since there is no undo for 
625      * library_objects.set_default... *)
626     GrafiteSync.time_travel ~present:self#grafite_status ~past:grafite_status;
627     LexiconSync.time_travel ~present:self#lexicon_status ~past:lexicon_status
628
629   method private reset_buffer = 
630     statements <- [];
631     history <- [ initial_statuses () ];
632     userGoal <- None;
633     self#notify;
634     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
635     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
636
637   method reset () =
638     self#reset_buffer;
639     source_buffer#begin_not_undoable_action ();
640     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
641     source_buffer#end_not_undoable_action ();
642     buffer#set_modified false;
643   
644   method template () =
645     let template = HExtlib.input_file BuildTimeConf.script_template in 
646     buffer#insert ~iter:(buffer#get_iter `START) template;
647     let development = MatitamakeLib.development_for_dir (Unix.getcwd ()) in
648     guistuff.filenamedata <- (None,development);
649     let include_ = 
650      match development with
651         None -> []
652       | Some devel -> [MatitamakeLib.root_for_development devel ]
653     in
654     let include_ =
655      include_ @ (Helm_registry.get_list Helm_registry.string "matita.includes")
656     in
657      include_paths <- include_ ;
658      buffer#set_modified false;
659      set_star (Filename.basename self#ppFilename) false
660
661   method goto (pos: [`Top | `Bottom | `Cursor]) () =
662     let old_locked_mark =
663      `MARK
664        (buffer#create_mark ~name:"old_locked_mark"
665          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
666     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
667     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
668     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
669     match pos with
670     | `Top -> 
671         dispose_old_locked_mark (); 
672         self#goto_top; 
673         self#reset_buffer;
674         self#notify
675     | `Bottom ->
676         (try 
677           let rec dowhile () =
678             self#_advance ();
679             let newpos = getpos () in
680             if (getoldpos ())#compare newpos < 0 then
681               begin
682                 buffer#move_mark old_locked_mark newpos;
683                 dowhile ()
684               end
685           in
686           dowhile ();
687           dispose_old_locked_mark ();
688           self#notify 
689         with 
690         | Margin -> dispose_old_locked_mark (); self#notify
691         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
692     | `Cursor ->
693         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
694         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
695         let remember =
696          `MARK
697            (buffer#create_mark ~name:"initial_insert"
698              ~left_gravity:true (cursor_iter ())) in
699         let dispose_remember () = buffer#delete_mark remember in
700         let remember_iter () =
701          buffer#get_iter_at_mark (`NAME "initial_insert") in
702         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
703         let icmp = cmp () in
704         let forward_until_cursor () = (* go forward until locked > cursor *)
705           let rec aux () =
706             self#_advance ();
707             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
708             then
709              begin
710               buffer#move_mark old_locked_mark (getpos ());
711               aux ()
712              end
713           in
714           aux ()
715         in
716         let rec back_until_cursor len = (* go backward until locked < cursor *)
717          function
718             statements, ((grafite_status,lexicon_status)::_ as history)
719             when len <= 0 ->
720              self#_retract (icmp - len) lexicon_status grafite_status statements
721               history
722           | statement::tl1, _::tl2 ->
723              back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
724           | _,_ -> assert false
725         in
726         (try
727           begin
728            if icmp < 0 then       (* locked < cursor *)
729              (forward_until_cursor (); self#notify)
730            else if icmp > 0 then  (* locked > cursor *)
731              (back_until_cursor icmp (statements,history); self#notify)
732            else                  (* cursor = locked *)
733                ()
734           end ;
735           dispose_remember ();
736           dispose_old_locked_mark ();
737         with 
738         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
739         | exc -> dispose_remember (); dispose_old_locked_mark ();
740                  self#notify; raise exc)
741               
742   method onGoingProof () =
743     match self#grafite_status.proof_status with
744     | No_proof | Proof _ -> false
745     | Incomplete_proof _ -> true
746     | Intermediate _ -> assert false
747
748 (*   method proofStatus = MatitaTypes.get_proof_status self#status *)
749   method proofMetasenv = GrafiteTypes.get_proof_metasenv self#grafite_status
750
751   method proofContext =
752    match userGoal with
753       None -> []
754     | Some n -> GrafiteTypes.get_proof_context self#grafite_status n
755
756   method proofConclusion =
757    match userGoal with
758       None -> assert false
759     | Some n ->
760        GrafiteTypes.get_proof_conclusion self#grafite_status n
761
762   method stack = GrafiteTypes.get_stack self#grafite_status
763   method setGoal n = userGoal <- n
764   method goal = userGoal
765
766   method eos = 
767     let rec is_there_only_comments lexicon_status s = 
768       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
769       let lexicon_status,st =
770        GrafiteParser.parse_statement (Ulexing.from_utf8_string s)
771         ~include_paths lexicon_status
772       in
773       match st with
774       | GrafiteParser.LSome (GrafiteAst.Comment (loc,_)) -> 
775           let _,parsed_text_length = 
776             MatitaGtkMisc.utf8_parsed_text s loc 
777           in
778           let remain_len = String.length s - parsed_text_length in
779           let next = String.sub s parsed_text_length remain_len in
780           is_there_only_comments lexicon_status next
781       | GrafiteParser.LNone _
782       | GrafiteParser.LSome (GrafiteAst.Executable _) -> false
783     in
784     try
785       is_there_only_comments self#lexicon_status self#getFuture
786     with 
787     | HExtlib.Localized _
788     | CicNotationParser.Parse_error _ -> false
789     | Margin | End_of_file -> true
790
791   (* debug *)
792   method dump () =
793     HLog.debug "script status:";
794     HLog.debug ("history size: " ^ string_of_int (List.length history));
795     HLog.debug (sprintf "%d statements:" (List.length statements));
796     List.iter HLog.debug statements;
797     HLog.debug ("Current file name: " ^
798       (match guistuff.filenamedata with 
799       |None,_ -> "[ no name ]" 
800       | Some f,_ -> f));
801
802 end
803
804 let _script = ref None
805
806 let script ~source_view ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
807 =
808   let s = new script 
809     ~source_view ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
810   in
811   _script := Some s;
812   s
813
814 let current () = match !_script with None -> assert false | Some s -> s
815