]> matita.cs.unibo.it Git - helm.git/blob - matita/matitaScript.ml
attributes now in the proof status: commit 1
[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   let compile_needed_and_go_on lexiconfile d exc =
110     let target = Pcre.replace ~pat:"lexicon$" ~templ:"moo" lexiconfile in
111     let target = Pcre.replace ~pat:"metadata$" ~templ:"moo" target in
112     let refresh_cb () = 
113       while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
114     in
115     if not(MatitamakeLib.build_development_in_bg ~target refresh_cb d) then
116       raise exc
117     else
118       f arg
119   in
120   let do_nothing () = raise (ActionCancelled "Inclusion not performed") in
121   let check_if_file_is_exists f =
122     assert(Pcre.pmatch ~pat:"ma$" f);
123     let pwd = Sys.getcwd () in
124     let f_pwd = pwd ^ "/" ^ f in
125     if not (HExtlib.is_regular f_pwd) then
126       raise (ActionCancelled ("File "^f_pwd^" does not exists!"))
127     else
128       raise 
129         (ActionCancelled 
130           ("Internal error: "^f_pwd^" exists but I'm unable to include it!"))
131   in
132   let handle_with_devel d lexiconfile mafile exc =
133     let name = MatitamakeLib.name_for_development d in
134     let title = "Unable to include " ^ lexiconfile in
135     let message = 
136       mafile ^ " is handled by development <b>" ^ name ^ "</b>.\n\n" ^
137       "<i>Should I compile it and Its dependencies?</i>"
138     in
139     (match guistuff.ask_confirmation ~title ~message with
140     | `YES -> compile_needed_and_go_on lexiconfile d exc
141     | `NO -> raise exc
142     | `CANCEL -> do_nothing ())
143   in
144   let handle_without_devel mafilename exc =
145     let title = "Unable to include " ^ mafilename in
146     let message = 
147      mafilename ^ " is <b>not</b> handled by a development.\n" ^
148      "All dependencies are automatically solved for a development.\n\n" ^
149      "<i>Do you want to set up a development?</i>"
150     in
151     (match guistuff.ask_confirmation ~title ~message with
152     | `YES -> 
153         guistuff.develcreator ~containing:(Some (Filename.dirname mafilename));
154         do_nothing ()
155     | `NO -> raise exc
156     | `CANCEL -> do_nothing())
157   in
158   try 
159     f arg
160   with
161   | DependenciesParser.UnableToInclude mafilename -> 
162       assert (Pcre.pmatch ~pat:"ma$" mafilename);
163       check_if_file_is_exists mafilename
164   | LexiconEngine.IncludedFileNotCompiled (xfilename,mafilename) 
165   | GrafiteEngine.IncludedFileNotCompiled (xfilename,mafilename) as exn ->
166       assert (Pcre.pmatch ~pat:"ma$" mafilename);
167       assert (Pcre.pmatch ~pat:"lexicon$" xfilename || 
168               Pcre.pmatch ~pat:"mo$" xfilename );
169       (* we know that someone was able to include the .ma, get the baseuri
170        * but was unable to get the compilation output 'xfilename' *)
171       match MatitamakeLib.development_for_dir (Filename.dirname mafilename) with
172       | None -> handle_without_devel mafilename exn
173       | Some d -> handle_with_devel d xfilename mafilename exn
174 ;;
175     
176 let eval_with_engine
177      guistuff lexicon_status grafite_status user_goal 
178        skipped_txt nonskipped_txt st
179 =
180   wrap_with_developments guistuff
181     (eval_with_engine 
182       guistuff lexicon_status grafite_status user_goal 
183         skipped_txt nonskipped_txt) st
184 ;;
185
186 let pp_eager_statement_ast =
187   GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
188     ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
189  
190 let rec eval_macro include_paths (buffer : GText.buffer) guistuff lexicon_status grafite_status user_goal unparsed_text parsed_text script mac =
191   let module TAPp = GrafiteAstPp in
192   let module MQ = MetadataQuery in
193   let module MDB = LibraryDb in
194   let module CTC = CicTypeChecker in
195   let module CU = CicUniv in
196   (* no idea why ocaml wants this *)
197   let parsed_text_length = String.length parsed_text in
198   let dbd = LibraryDb.instance () in
199   let pp_macro = 
200     let f t = ProofEngineReduction.replace 
201       ~equality:(fun _ t -> match t with Cic.Meta _ -> true | _ -> false)
202       ~what:[()] ~with_what:[Cic.Implicit None] ~where:t
203     in
204     let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
205     TAPp.pp_macro 
206       ~term_pp:(fun x -> 
207         ApplyTransformation.txt_of_cic_term max_int metasenv [] (f x))
208   in
209   match mac with
210   (* WHELP's stuff *)
211   | TA.WMatch (loc, term) -> 
212      let l =  Whelp.match_term ~dbd term in
213      let entry = `Whelp (pp_macro mac, l) in
214      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
215      [], "", parsed_text_length
216   | TA.WInstance (loc, term) ->
217      let l = Whelp.instance ~dbd term in
218      let entry = `Whelp (pp_macro mac, l) in
219      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
220      [], "", parsed_text_length
221   | TA.WLocate (loc, s) -> 
222      let l = Whelp.locate ~dbd s in
223      let entry = `Whelp (pp_macro mac, l) in
224      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
225      [], "", parsed_text_length
226   | TA.WElim (loc, term) ->
227      let uri =
228        match term with
229        | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
230        | _ -> failwith "Not a MutInd"
231      in
232      let l = Whelp.elim ~dbd uri in
233      let entry = `Whelp (pp_macro mac, l) in
234      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
235      [], "", parsed_text_length
236   | TA.WHint (loc, term) ->
237      let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term, []),0) in
238      let l = List.map fst (MQ.experimental_hint ~dbd s) in
239      let entry = `Whelp (pp_macro mac, l) in
240      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
241      [], "", parsed_text_length
242   (* REAL macro *)
243   | TA.Hint loc -> 
244       let user_goal' =
245        match user_goal with
246           Some n -> n
247         | None -> raise NoUnfinishedProof
248       in
249       let proof = GrafiteTypes.get_current_proof grafite_status in
250       let proof_status = proof,user_goal' in
251       let l = List.map fst (MQ.experimental_hint ~dbd proof_status) in
252       let selected = guistuff.urichooser l in
253       (match selected with
254       | [] -> [], "", parsed_text_length
255       | [uri] -> 
256           let suri = UriManager.string_of_uri uri in
257           let ast loc =
258             TA.Executable (loc, (TA.Tactical (loc,
259               TA.Tactic (loc,
260                 TA.Apply (loc, CicNotationPt.Uri (suri, None))),
261                 Some (TA.Dot loc)))) in
262           let text =
263            comment parsed_text ^ "\n" ^
264             pp_eager_statement_ast (ast HExtlib.dummy_floc) in
265           let text_len = MatitaGtkMisc.utf8_string_length text in
266           let loc = HExtlib.floc_of_loc (0,text_len) in
267           let statement = `Ast (GrafiteParser.LSome (ast loc),text) in
268           let res,_,_parsed_text_len =
269            eval_statement include_paths buffer guistuff lexicon_status
270             grafite_status user_goal script statement
271           in
272            (* we need to replace all the parsed_text *)
273            res,"",String.length parsed_text
274       | _ -> 
275           HLog.error 
276             "The result of the urichooser should be only 1 uri, not:\n";
277           List.iter (
278             fun u -> HLog.error (UriManager.string_of_uri u ^ "\n")
279           ) selected;
280           assert false)
281   | TA.Check (_,term) ->
282       let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
283       let context =
284        match user_goal with
285           None -> []
286         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
287       let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
288       let t_and_ty = Cic.Cast (term,ty) in
289       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
290       [], "", parsed_text_length
291   | TA.Inline (_,style,suri,prefix) ->
292      let dbd = LibraryDb.instance () in
293      let uris =
294       let sql_pat =
295        (Pcre.replace ~rex:(Pcre.regexp "_") ~templ:"\\_" suri) ^ "%" in
296       let query =
297        sprintf ("SELECT source FROM %s WHERE source LIKE \"%s\" UNION "^^
298                 "SELECT source FROM %s WHERE source LIKE \"%s\"")
299          (MetadataTypes.name_tbl ()) sql_pat
300          MetadataTypes.library_name_tbl sql_pat in
301       let result = HMysql.exec dbd query in
302        HMysql.map result
303         (function cols ->
304           match cols.(0) with
305              Some s -> UriManager.uri_of_string s
306            | _ -> assert false)
307      in
308 prerr_endline "Inizio sorting";
309       let sorted_uris = MetadataDeps.topological_sort ~dbd uris in
310 prerr_endline "Fine sorting";
311       let sorted_uris_without_xpointer =
312        HExtlib.filter_map
313         (function uri ->
314           let s =
315            Pcre.replace ~rex:(Pcre.regexp "#xpointer\\(1/1\\)") ~templ:""
316             (UriManager.string_of_uri uri) in
317           try
318            ignore (Pcre.exec ~rex:(Pcre.regexp"#xpointer") s);
319            None
320           with
321            Not_found ->
322             Some (UriManager.uri_of_string s)
323         ) sorted_uris
324       in
325       let declarative =
326        String.concat "\n\n"
327         (List.map
328           (fun uri ->
329 prerr_endline ("Stampo " ^ UriManager.string_of_uri uri);
330             try
331              ObjPp.obj_to_string 78 style prefix (* FG: mi pare meglio 78 *)
332               (fst (CicEnvironment.get_obj CicUniv.empty_ugraph uri))
333             with
334              | e (* BRRRRRRRRR *) -> 
335                 Printf.sprintf "\n(* ERRORE IN STAMPA DI %s\nEXCEPTION: %s *)\n" 
336                 (UriManager.string_of_uri uri) (Printexc.to_string e)
337           ) sorted_uris_without_xpointer)
338       in
339        [],declarative,String.length parsed_text
340                                 
341 and eval_executable include_paths (buffer : GText.buffer) guistuff
342 lexicon_status grafite_status user_goal unparsed_text skipped_txt nonskipped_txt
343 script ex loc
344 =
345  let module TAPp = GrafiteAstPp in
346  let module MD = GrafiteDisambiguator in
347  let module ML = MatitaMisc in
348   try
349    begin
350     match ex with
351      | TA.Command (_,TA.Set (_,"baseuri",u)) ->
352         if  Http_getter_storage.is_read_only u then
353           raise (ActionCancelled ("baseuri " ^ u ^ " is readonly"));
354         if not (Http_getter_storage.is_empty u) then
355          (match 
356             guistuff.ask_confirmation 
357               ~title:"Baseuri redefinition" 
358               ~message:(
359                 "Baseuri " ^ u ^ " already exists.\n" ^
360                 "Do you want to redefine the corresponding "^
361                 "part of the library?")
362           with
363            | `YES -> LibraryClean.clean_baseuris [u]
364            | `NO -> ()
365            | `CANCEL -> raise MatitaTypes.Cancel)
366      | _ -> ()
367    end;
368    ignore (buffer#move_mark (`NAME "beginning_of_statement")
369     ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
370        (Glib.Utf8.length skipped_txt))) ;
371    eval_with_engine
372     guistuff lexicon_status grafite_status user_goal skipped_txt nonskipped_txt
373      (TA.Executable (loc, ex))
374   with
375      MatitaTypes.Cancel -> [], "", 0
376    | GrafiteEngine.Macro (_loc,lazy_macro) ->
377       let context =
378        match user_goal with
379           None -> []
380         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
381       let grafite_status,macro = lazy_macro context in
382        eval_macro include_paths buffer guistuff lexicon_status grafite_status
383         user_goal unparsed_text (skipped_txt ^ nonskipped_txt) script macro
384
385 and eval_statement include_paths (buffer : GText.buffer) guistuff lexicon_status
386  grafite_status user_goal script statement
387 =
388   let (lexicon_status,st), unparsed_text =
389     match statement with
390     | `Raw text ->
391         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
392         let ast = 
393           wrap_with_developments guistuff
394             (GrafiteParser.parse_statement 
395               (Ulexing.from_utf8_string text) ~include_paths) lexicon_status 
396         in
397           ast, text
398     | `Ast (st, text) -> (lexicon_status, st), text
399   in
400   let text_of_loc floc = 
401     let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
402     let start, stop = HExtlib.loc_of_floc floc in 
403     let floc = HExtlib.floc_of_loc (0, start) in
404     let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
405     let floc = HExtlib.floc_of_loc (0, stop) in
406     let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
407     txt,nonskipped_txt,skipped_txt,len
408   in 
409   match st with
410   | GrafiteParser.LNone loc ->
411       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
412        [(grafite_status,lexicon_status),parsed_text],"",
413         parsed_text_length
414   | GrafiteParser.LSome (GrafiteAst.Comment (loc, _)) -> 
415       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
416       let remain_len = String.length unparsed_text - parsed_text_length in
417       let s = String.sub unparsed_text parsed_text_length remain_len in
418       let s,text,len = 
419        try
420         eval_statement include_paths buffer guistuff lexicon_status
421          grafite_status user_goal script (`Raw s)
422        with
423           HExtlib.Localized (floc, exn) ->
424            HExtlib.raise_localized_exception 
425              ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
426         | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
427            raise
428             (GrafiteDisambiguator.DisambiguationError
429               (offset+parsed_text_length, errorll))
430       in
431       assert (text=""); (* no macros inside comments, please! *)
432       (match s with
433       | (statuses,text)::tl ->
434          (statuses,parsed_text ^ text)::tl,"",parsed_text_length + len
435       | [] -> [], "", 0)
436   | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) ->
437      let _, nonskipped, skipped, parsed_text_length = 
438        text_of_loc loc 
439      in
440       eval_executable include_paths buffer guistuff lexicon_status
441        grafite_status user_goal unparsed_text skipped nonskipped script ex loc
442   
443 let fresh_script_id =
444   let i = ref 0 in
445   fun () -> incr i; !i
446
447 class script  ~(source_view: GSourceView.source_view)
448               ~(mathviewer: MatitaTypes.mathViewer) 
449               ~set_star
450               ~ask_confirmation
451               ~urichooser 
452               ~develcreator 
453               () =
454 let buffer = source_view#buffer in
455 let source_buffer = source_view#source_buffer in
456 let initial_statuses () =
457  (* these include_paths are used only to load the initial notation *)
458  let include_paths =
459   Helm_registry.get_list Helm_registry.string "matita.includes" in
460  let lexicon_status =
461   CicNotation2.load_notation ~include_paths
462    BuildTimeConf.core_notation_script in
463  let grafite_status = GrafiteSync.init () in
464   grafite_status,lexicon_status
465 in
466 object (self)
467   val mutable include_paths =
468    Helm_registry.get_list Helm_registry.string "matita.includes"
469
470   val scriptId = fresh_script_id ()
471   
472   val guistuff = {
473     mathviewer = mathviewer;
474     urichooser = urichooser;
475     ask_confirmation = ask_confirmation;
476     develcreator = develcreator;
477     filenamedata = (None, None)} 
478   
479   method private getFilename =
480     match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
481
482   method filename = self#getFilename
483     
484   method private ppFilename =
485     match guistuff.filenamedata with 
486     | Some f,_ -> f 
487     | None,_ -> sprintf ".unnamed%d.ma" scriptId
488   
489   initializer 
490     ignore (GMain.Timeout.add ~ms:300000 
491        ~callback:(fun _ -> self#_saveToBackupFile ();true));
492     ignore (buffer#connect#modified_changed 
493       (fun _ -> set_star (Filename.basename self#ppFilename) buffer#modified))
494
495   val mutable statements = []    (** executed statements *)
496
497   val mutable history = [ initial_statuses () ]
498     (** list of states before having executed statements. Head element of this
499       * list is the current state, last element is the state at the beginning of
500       * the script.
501       * Invariant: this list length is 1 + length of statements *)
502
503   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
504   val mutable userGoal = None
505
506   (** text mark and tag representing locked part of a script *)
507   val locked_mark =
508     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
509   val beginning_of_statement_mark =
510     buffer#create_mark ~name:"beginning_of_statement"
511      ~left_gravity:true buffer#start_iter
512   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
513   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
514
515   method locked_mark = locked_mark
516   method locked_tag = locked_tag
517   method error_tag = error_tag
518
519     (* history can't be empty, the invariant above grant that it contains at
520      * least the init grafite_status *)
521   method grafite_status = match history with (s,_)::_ -> s | _ -> assert false
522   method lexicon_status = match history with (_,ss)::_ -> ss | _ -> assert false
523
524   method private _advance ?statement () =
525    let s = match statement with Some s -> s | None -> self#getFuture in
526    HLog.debug ("evaluating: " ^ first_line s ^ " ...");
527    let entries, newtext, parsed_len = 
528     try
529      eval_statement include_paths buffer guistuff self#lexicon_status
530       self#grafite_status userGoal self (`Raw s)
531     with End_of_file -> raise Margin
532    in
533    let new_statuses, new_statements =
534      let statuses, texts = List.split entries in
535      statuses, texts
536    in
537    history <- new_statuses @ history;
538    statements <- new_statements @ statements;
539    let start = buffer#get_iter_at_mark (`MARK locked_mark) in
540    let new_text = String.concat "" (List.rev new_statements) in
541    if statement <> None then
542      buffer#insert ~iter:start new_text
543    else begin
544      let parsed_text = String.sub s 0 parsed_len in
545      if new_text <> parsed_text then begin
546        let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
547        buffer#delete ~start ~stop;
548        buffer#insert ~iter:start new_text;
549      end;
550    end;
551    self#moveMark (Glib.Utf8.length new_text);
552    buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext;
553    (* here we need to set the Goal in case we are going to cursor (or to
554       bottom) and we will face a macro *)
555    match self#grafite_status.proof_status with
556       Incomplete_proof p ->
557        userGoal <-
558          (try Some (Continuationals.Stack.find_goal p.stack)
559          with Failure _ -> None)
560     | _ -> userGoal <- None
561
562   method private _retract offset lexicon_status grafite_status new_statements
563    new_history
564   =
565    let cur_grafite_status,cur_lexicon_status =
566     match history with s::_ -> s | [] -> assert false
567    in
568     LexiconSync.time_travel ~present:cur_lexicon_status ~past:lexicon_status;
569     GrafiteSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
570     statements <- new_statements;
571     history <- new_history;
572     self#moveMark (- offset)
573
574   method advance ?statement () =
575     try
576       self#_advance ?statement ();
577       self#notify
578     with 
579     | Margin -> self#notify
580     | Not_found -> assert false
581     | exc -> self#notify; raise exc
582
583   method retract () =
584     try
585       let cmp,new_statements,new_history,(grafite_status,lexicon_status) =
586        match statements,history with
587           stat::statements, _::(status::_ as history) ->
588            assert (Glib.Utf8.validate stat);
589            Glib.Utf8.length stat, statements, history, status
590        | [],[_] -> raise Margin
591        | _,_ -> assert false
592       in
593        self#_retract cmp lexicon_status grafite_status new_statements
594         new_history;
595        self#notify
596     with 
597     | Margin -> self#notify
598     | exc -> self#notify; raise exc
599
600   method private getFuture =
601     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
602       ~stop:buffer#end_iter ()
603
604       
605   (** @param rel_offset relative offset from current position of locked_mark *)
606   method private moveMark rel_offset =
607     let mark = `MARK locked_mark in
608     let old_insert = buffer#get_iter_at_mark `INSERT in
609     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
610     let current_mark_pos = buffer#get_iter_at_mark mark in
611     let new_mark_pos =
612       match rel_offset with
613       | 0 -> current_mark_pos
614       | n when n > 0 -> current_mark_pos#forward_chars n
615       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
616     in
617     buffer#move_mark mark ~where:new_mark_pos;
618     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
619     buffer#move_mark `INSERT old_insert;
620     let mark_position = buffer#get_iter_at_mark mark in
621     if source_view#move_mark_onscreen mark then
622      begin
623       buffer#move_mark mark mark_position;
624       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
625      end;
626     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
627
628   method clean_dirty_lock =
629     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
630     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
631     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
632
633   val mutable observers = []
634
635   method addObserver (o: LexiconEngine.status -> GrafiteTypes.status -> unit) =
636     observers <- o :: observers
637
638   method private notify =
639     let lexicon_status = self#lexicon_status in
640     let grafite_status = self#grafite_status in
641     List.iter (fun o -> o lexicon_status grafite_status) observers
642
643   method loadFromString s =
644     buffer#set_text s;
645     self#reset_buffer;
646     buffer#set_modified true
647
648   method loadFromFile f =
649     buffer#set_text (HExtlib.input_file f);
650     self#reset_buffer;
651     buffer#set_modified false
652     
653   method assignFileName file =
654     let abspath = MatitaMisc.absolute_path file in
655     let dirname = Filename.dirname abspath in
656     let devel = MatitamakeLib.development_for_dir dirname in
657     guistuff.filenamedata <- Some abspath, devel;
658     let include_ = 
659      match MatitamakeLib.development_for_dir dirname with
660         None -> []
661       | Some devel -> [MatitamakeLib.root_for_development devel] in
662     let include_ =
663      include_ @ (Helm_registry.get_list Helm_registry.string "matita.includes")
664     in
665      include_paths <- include_
666     
667   method saveToFile () =
668     let oc = open_out self#getFilename in
669     output_string oc (buffer#get_text ~start:buffer#start_iter
670                         ~stop:buffer#end_iter ());
671     close_out oc;
672     buffer#set_modified false
673   
674   method private _saveToBackupFile () =
675     if buffer#modified then
676       begin
677         let f = self#ppFilename ^ "~" in
678         let oc = open_out f in
679         output_string oc (buffer#get_text ~start:buffer#start_iter
680                             ~stop:buffer#end_iter ());
681         close_out oc;
682         HLog.debug ("backup " ^ f ^ " saved")                    
683       end
684   
685   method private goto_top =
686     let grafite_status,lexicon_status = 
687       let rec last x = function 
688       | [] -> x
689       | hd::tl -> last hd tl
690       in
691       last (self#grafite_status,self#lexicon_status) history
692     in
693     (* FIXME: this is not correct since there is no undo for 
694      * library_objects.set_default... *)
695     GrafiteSync.time_travel ~present:self#grafite_status ~past:grafite_status;
696     LexiconSync.time_travel ~present:self#lexicon_status ~past:lexicon_status
697
698   method private reset_buffer = 
699     statements <- [];
700     history <- [ initial_statuses () ];
701     userGoal <- None;
702     self#notify;
703     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
704     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
705
706   method reset () =
707     self#reset_buffer;
708     source_buffer#begin_not_undoable_action ();
709     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
710     source_buffer#end_not_undoable_action ();
711     buffer#set_modified false;
712   
713   method template () =
714     let template = HExtlib.input_file BuildTimeConf.script_template in 
715     buffer#insert ~iter:(buffer#get_iter `START) template;
716     let development = MatitamakeLib.development_for_dir (Unix.getcwd ()) in
717     guistuff.filenamedata <- (None,development);
718     let include_ = 
719      match development with
720         None -> []
721       | Some devel -> [MatitamakeLib.root_for_development devel ]
722     in
723     let include_ =
724      include_ @ (Helm_registry.get_list Helm_registry.string "matita.includes")
725     in
726      include_paths <- include_ ;
727      buffer#set_modified false;
728      set_star (Filename.basename self#ppFilename) false
729
730   method goto (pos: [`Top | `Bottom | `Cursor]) () =
731     let old_locked_mark =
732      `MARK
733        (buffer#create_mark ~name:"old_locked_mark"
734          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
735     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
736     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
737     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
738     match pos with
739     | `Top -> 
740         dispose_old_locked_mark (); 
741         self#goto_top; 
742         self#reset_buffer;
743         self#notify
744     | `Bottom ->
745         (try 
746           let rec dowhile () =
747             self#_advance ();
748             let newpos = getpos () in
749             if (getoldpos ())#compare newpos < 0 then
750               begin
751                 buffer#move_mark old_locked_mark newpos;
752                 dowhile ()
753               end
754           in
755           dowhile ();
756           dispose_old_locked_mark ();
757           self#notify 
758         with 
759         | Margin -> dispose_old_locked_mark (); self#notify
760         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
761     | `Cursor ->
762         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
763         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
764         let remember =
765          `MARK
766            (buffer#create_mark ~name:"initial_insert"
767              ~left_gravity:true (cursor_iter ())) in
768         let dispose_remember () = buffer#delete_mark remember in
769         let remember_iter () =
770          buffer#get_iter_at_mark (`NAME "initial_insert") in
771         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
772         let icmp = cmp () in
773         let forward_until_cursor () = (* go forward until locked > cursor *)
774           let rec aux () =
775             self#_advance ();
776             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
777             then
778              begin
779               buffer#move_mark old_locked_mark (getpos ());
780               aux ()
781              end
782           in
783           aux ()
784         in
785         let rec back_until_cursor len = (* go backward until locked < cursor *)
786          function
787             statements, ((grafite_status,lexicon_status)::_ as history)
788             when len <= 0 ->
789              self#_retract (icmp - len) lexicon_status grafite_status statements
790               history
791           | statement::tl1, _::tl2 ->
792              back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
793           | _,_ -> assert false
794         in
795         (try
796           begin
797            if icmp < 0 then       (* locked < cursor *)
798              (forward_until_cursor (); self#notify)
799            else if icmp > 0 then  (* locked > cursor *)
800              (back_until_cursor icmp (statements,history); self#notify)
801            else                  (* cursor = locked *)
802                ()
803           end ;
804           dispose_remember ();
805           dispose_old_locked_mark ();
806         with 
807         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
808         | exc -> dispose_remember (); dispose_old_locked_mark ();
809                  self#notify; raise exc)
810               
811   method onGoingProof () =
812     match self#grafite_status.proof_status with
813     | No_proof | Proof _ -> false
814     | Incomplete_proof _ -> true
815     | Intermediate _ -> assert false
816
817 (*   method proofStatus = MatitaTypes.get_proof_status self#status *)
818   method proofMetasenv = GrafiteTypes.get_proof_metasenv self#grafite_status
819
820   method proofContext =
821    match userGoal with
822       None -> []
823     | Some n -> GrafiteTypes.get_proof_context self#grafite_status n
824
825   method proofConclusion =
826    match userGoal with
827       None -> assert false
828     | Some n ->
829        GrafiteTypes.get_proof_conclusion self#grafite_status n
830
831   method stack = GrafiteTypes.get_stack self#grafite_status
832   method setGoal n = userGoal <- n
833   method goal = userGoal
834
835   method eos = 
836     let rec is_there_only_comments lexicon_status s = 
837       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
838       let lexicon_status,st =
839        GrafiteParser.parse_statement (Ulexing.from_utf8_string s)
840         ~include_paths lexicon_status
841       in
842       match st with
843       | GrafiteParser.LSome (GrafiteAst.Comment (loc,_)) -> 
844           let _,parsed_text_length = MatitaGtkMisc.utf8_parsed_text s loc in
845           (* CSC: why +1 in the following lines ???? *)
846           let parsed_text_length = parsed_text_length + 1 in
847 prerr_endline ("## " ^ string_of_int parsed_text_length);
848           let remain_len = String.length s - parsed_text_length in
849           let next = String.sub s parsed_text_length remain_len in
850           is_there_only_comments lexicon_status next
851       | GrafiteParser.LNone _
852       | GrafiteParser.LSome (GrafiteAst.Executable _) -> false
853     in
854     try
855       is_there_only_comments self#lexicon_status self#getFuture
856     with 
857     | LexiconEngine.IncludedFileNotCompiled _
858     | HExtlib.Localized _
859     | CicNotationParser.Parse_error _ -> false
860     | Margin | End_of_file -> true
861
862   (* debug *)
863   method dump () =
864     HLog.debug "script status:";
865     HLog.debug ("history size: " ^ string_of_int (List.length history));
866     HLog.debug (sprintf "%d statements:" (List.length statements));
867     List.iter HLog.debug statements;
868     HLog.debug ("Current file name: " ^
869       (match guistuff.filenamedata with 
870       |None,_ -> "[ no name ]" 
871       | Some f,_ -> f));
872
873 end
874
875 let _script = ref None
876
877 let script ~source_view ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
878 =
879   let s = new script 
880     ~source_view ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
881   in
882   _script := Some s;
883   s
884
885 let current () = match !_script with None -> assert false | Some s -> s
886