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