]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaScript.ml
added #proofConclusion
[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 MatitaTypes
28
29 let debug = true
30 let debug_print = if  debug then prerr_endline else ignore
31
32   (** raised when one of the script margins (top or bottom) is reached *)
33 exception Margin
34
35 let safe_substring s i j =
36   try String.sub s i j with Invalid_argument _ -> assert false
37
38 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*"
39 let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$"
40 let multiline_RE = Pcre.regexp "^\n[^\n]+$"
41 let newline_RE = Pcre.regexp "\n"
42  
43 let comment str =
44   if Pcre.pmatch ~rex:multiline_RE str then
45     "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " **)"
46   else
47     "\n(**\n" ^ str ^ "\n**)"
48                      
49 let first_line s =
50   let s = Pcre.replace ~rex:heading_nl_RE s in
51   try
52     let nl_pos = String.index s '\n' in
53     String.sub s 0 nl_pos
54   with Not_found -> s
55
56 let prepend_text header base =
57   if Pcre.pmatch ~rex:heading_nl_RE base then
58     sprintf "\n%s%s" header base
59   else
60     sprintf "\n%s\n%s" header base
61
62   (** creates a statement AST for the Goal tactic, e.g. "goal 7" *)
63 let goal_ast n =
64   let module A = GrafiteAst in
65   let loc = Disambiguate.dummy_floc in
66   A.Executable (loc, A.Tactical (loc, A.Tactic (loc, A.Goal (loc, n))))
67
68 type guistuff = {
69   mathviewer:MatitaTypes.mathViewer;
70   urichooser: UriManager.uri list -> UriManager.uri list;
71   ask_confirmation: title:string -> message:string -> [`YES | `NO | `CANCEL];
72   develcreator: containing:string option -> unit;
73   mutable filenamedata: string option * MatitamakeLib.development option
74 }
75
76 let eval_with_engine guistuff status user_goal parsed_text st =
77   let module TA = GrafiteAst in
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 parsed_text_length = String.length parsed_text in
89   let loc, ex = 
90     match st with TA.Executable (loc,ex) -> loc, ex | _ -> assert false 
91   in
92   let goal_changed = ref false in
93   let status =
94     match status.proof_status with
95       | Incomplete_proof (_, goal) when goal <> user_goal ->
96           goal_changed := true;
97           MatitaEngine.eval_ast ~include_paths:include_
98             ~do_heavy_checks:true status (goal_ast user_goal)
99       | _ -> status
100   in
101   let new_status = 
102     MatitaEngine.eval_ast 
103       ~include_paths:include_ ~do_heavy_checks:true status st 
104   in
105   let new_aliases =
106     match ex with
107       | TA.Command (_, TA.Alias _)
108       | TA.Command (_, TA.Include _) -> DisambiguateTypes.Environment.empty
109       | _ -> MatitaSync.alias_diff ~from:status new_status
110   in
111   (* we remove the defined object since we consider them "automatic aliases" *)
112   let new_aliases = 
113     let module DTE = DisambiguateTypes.Environment in
114     let module UM = UriManager in
115     DTE.fold (
116       fun k ((v,_) as value) acc -> 
117         let b = 
118           try
119             let v = UM.strip_xpointer (UM.uri_of_string v) in
120             List.exists (fun (s,_) -> s = v) new_status.objects 
121           with UM.IllFormedUri _ -> false
122         in
123         if b then 
124           acc
125         else
126           DTE.add k value acc
127     ) new_aliases DTE.empty
128   in
129   let new_text =
130     if DisambiguateTypes.Environment.is_empty new_aliases then
131       parsed_text
132     else
133       prepend_text (DisambiguatePp.pp_environment new_aliases)
134         parsed_text
135   in
136   let new_text =
137     if !goal_changed then
138       prepend_text
139         (TAPp.pp_tactic (TA.Goal (loc, user_goal))(* ^ "\n"*))
140         new_text
141     else
142       new_text
143   in
144     [ new_status, new_text ], parsed_text_length
145
146 let eval_with_engine guistuff status user_goal parsed_text st =
147   try
148     eval_with_engine guistuff status user_goal parsed_text st
149   with
150     MatitaEngine.UnableToInclude what as exc ->
151       let compile_needed_and_go_on d =
152         let target = what in
153         let refresh_cb () = 
154           while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
155         in
156         if not(MatitamakeLib.build_development_in_bg ~target refresh_cb d) then
157           raise exc
158         else
159           eval_with_engine guistuff status user_goal parsed_text st
160       in
161       let do_nothing () = [], 0 in
162       let handle_with_devel d =
163         let name = MatitamakeLib.name_for_development d in
164         let title = "Unable to include " ^ what in
165         let message = 
166           what ^ " is handled by development <b>" ^ name ^ "</b>.\n\n" ^
167           "<i>Should I compile it and Its dependencies?</i>"
168         in
169         (match guistuff.ask_confirmation ~title ~message with
170         | `YES -> compile_needed_and_go_on d
171         | `NO -> raise exc
172         | `CANCEL -> do_nothing ())
173       in
174       let handle_withoud_devel filename =
175         let title = "Unable to include " ^ what in
176         let message = 
177          what ^ " is <b>not</b> handled by a development.\n" ^
178          "All dependencies are authomatically solved for a development.\n\n" ^
179          "<i>Do you want to set up a development?</i>"
180         in
181         (match guistuff.ask_confirmation ~title ~message with
182         | `YES -> 
183             (match filename with
184             | Some f -> 
185                 guistuff.develcreator ~containing:(Some (Filename.dirname f))
186             | None -> guistuff.develcreator ~containing:None);
187             do_nothing ()
188         | `NO -> raise exc
189         | `CANCEL -> do_nothing())
190       in
191       match guistuff.filenamedata with
192       | None,None -> handle_withoud_devel None
193       | None,Some d -> handle_with_devel d
194       | Some f,_ ->
195           match MatitamakeLib.development_for_dir (Filename.dirname f) with
196           | None -> handle_withoud_devel (Some f)
197           | Some d -> handle_with_devel d
198 ;;
199
200 let disambiguate term status =
201   let module MD = MatitaDisambiguator in
202   let dbd = MatitaDb.instance () in
203   let metasenv = MatitaMisc.get_proof_metasenv status in
204   let context = MatitaMisc.get_proof_context status in
205   let aliases = MatitaMisc.get_proof_aliases status in
206   let interps = MD.disambiguate_term dbd context metasenv aliases term in
207   match interps with 
208   | [_,_,x,_] -> x
209   | _ -> assert false
210  
211 let eval_macro guistuff status parsed_text script mac
212 =
213   let module TA = GrafiteAst in
214   let module TAPp = GrafiteAstPp in
215   let module MQ = MetadataQuery in
216   let module MDB = MatitaDb in
217   let module CTC = CicTypeChecker in
218   let module CU = CicUniv in
219   (* no idea why ocaml wants this *)
220   let advance ?statement () = script#advance ?statement () in
221   let parsed_text_length = String.length parsed_text in
222   let dbd = MatitaDb.instance () in
223   match mac with
224   (* WHELP's stuff *)
225   | TA.WMatch (loc, term) -> 
226       let term = disambiguate term status in
227       let l =  MQ.match_term ~dbd term in
228       let entry = `Whelp (TAPp.pp_macro_cic (TA.WMatch (loc, term)), l) in
229       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
230       [], parsed_text_length
231   | TA.WInstance (loc, term) ->
232       let term = disambiguate term status in
233       let l = MQ.instance ~dbd term in
234       let entry = `Whelp (TAPp.pp_macro_cic (TA.WInstance (loc, term)), l) in
235       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
236       [], parsed_text_length
237   | TA.WLocate (loc, s) -> 
238       let l = MQ.locate ~dbd s in
239       let entry = `Whelp (TAPp.pp_macro_cic (TA.WLocate (loc, s)), l) in
240       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
241       [], parsed_text_length
242   | TA.WElim (loc, term) ->
243       let term = disambiguate term status in
244       let uri =
245         match term with
246         | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
247         | _ -> failwith "Not a MutInd"
248       in
249       let l = MQ.elim ~dbd uri in
250       let entry = `Whelp (TAPp.pp_macro_cic (TA.WElim (loc, term)), l) in
251       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
252       [], parsed_text_length
253   | TA.WHint (loc, term) ->
254       let term = disambiguate term status in
255       let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
256       let l = List.map fst (MQ.experimental_hint ~dbd s) in
257       let entry = `Whelp (TAPp.pp_macro_cic (TA.WHint (loc, term)), l) in
258       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
259       [], parsed_text_length
260   (* REAL macro *)
261   | TA.Hint loc -> 
262       let s = MatitaMisc.get_proof_status status in
263       let l = List.map fst (MQ.experimental_hint ~dbd s) in
264       let selected = guistuff.urichooser l in
265       (match selected with
266       | [] -> [], parsed_text_length
267       | [uri] -> 
268         let ast = 
269          TA.Executable (loc,
270           (TA.Tactical (loc, 
271             TA.Tactic (loc,
272              TA.Apply (loc, CicNotationPt.Uri (UriManager.string_of_uri uri,None))))))
273         in
274         let new_status = MatitaEngine.eval_ast status ast in
275         let extra_text = 
276           comment parsed_text ^ 
277           "\n" ^ TAPp.pp_statement ast
278         in
279         [ new_status , extra_text ], parsed_text_length
280       | _ -> 
281           MatitaLog.error 
282             "The result of the urichooser should be only 1 uri, not:\n";
283           List.iter (
284             fun u -> MatitaLog.error (UriManager.string_of_uri u ^ "\n")
285           ) selected;
286           assert false)
287   | TA.Check (_,term) ->
288       let metasenv = MatitaMisc.get_proof_metasenv status in
289       let context = MatitaMisc.get_proof_context status in
290       let aliases = MatitaMisc.get_proof_aliases status in
291       let interps = 
292         MatitaDisambiguator.disambiguate_term 
293           dbd context metasenv aliases term 
294       in
295       let _, metasenv , term, ugraph =
296         match interps with 
297         | [x] -> x
298         | _ -> assert false
299       in
300       let ty,_ = CTC.type_of_aux' metasenv context term ugraph in
301       let t_and_ty = Cic.Cast (term,ty) in
302       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
303       [], parsed_text_length
304 (*   | TA.Abort _ -> 
305       let rec go_back () =
306         let status = script#status.proof_status in
307         match status with
308         | No_proof -> ()
309         | _ -> script#retract ();go_back()
310       in
311       [], parsed_text_length, Some go_back
312   | TA.Redo (_, Some i) ->  [], parsed_text_length, 
313       Some (fun () -> for j = 1 to i do advance () done)
314   | TA.Redo (_, None) ->   [], parsed_text_length, 
315       Some (fun () -> advance ())
316   | TA.Undo (_, Some i) ->  [], parsed_text_length, 
317       Some (fun () -> for j = 1 to i do script#retract () done)
318   | TA.Undo (_, None) -> [], parsed_text_length, 
319       Some (fun () -> script#retract ()) *)
320   (* TODO *)
321   | TA.Quit _ -> failwith "not implemented"
322   | TA.Print (_,kind) -> failwith "not implemented"
323   | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
324   | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
325
326                                 
327 let eval_executable guistuff status user_goal parsed_text script ex =
328   let module TA = GrafiteAst in
329   let module TAPp = GrafiteAstPp in
330   let module MD = MatitaDisambiguator in
331   let module ML = MatitacleanLib in
332   let parsed_text_length = String.length parsed_text in
333   match ex with
334   | TA.Command (loc, _) | TA.Tactical (loc, _) ->
335       (try 
336         (match MatitaMisc.baseuri_of_baseuri_decl (TA.Executable (loc,ex)) with
337         | None -> ()
338         | Some u -> 
339             if not (MatitaMisc.is_empty u) then
340               match 
341                 guistuff.ask_confirmation 
342                   ~title:"Baseuri redefinition" 
343                   ~message:(
344                     "Baseuri " ^ u ^ " already exists.\n" ^
345                     "Do you want to redefine the corresponding "^
346                     "part of the library?")
347               with
348               | `YES -> MatitacleanLib.clean_baseuris [u]
349               | `NO -> ()
350               | `CANCEL -> raise MatitaTypes.Cancel);
351         eval_with_engine 
352           guistuff status user_goal parsed_text (TA.Executable (loc, ex))
353       with MatitaTypes.Cancel -> [], 0)
354   | TA.Macro (_,mac) ->
355       eval_macro guistuff status parsed_text script mac
356
357 let rec eval_statement baseoffset parsedlen error_tag (buffer : GText.buffer)
358  guistuff status user_goal script s
359 =
360   if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
361   let st =
362    try
363     GrafiteParser.parse_statement (Stream.of_string s)
364    with
365     CicNotationParser.Parse_error (floc,err) as exc ->
366      let (x, y) = CicNotationPt.loc_of_floc floc in
367      let x = parsedlen + x in
368      let y = parsedlen + y in
369      let x' = baseoffset + x in
370      let y' = baseoffset + y in
371      let x_iter = buffer#get_iter (`OFFSET x') in
372      let y_iter = buffer#get_iter (`OFFSET y') in
373       buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
374      let id = ref None in
375       id :=
376        Some
377         (buffer#connect#changed
378           ~callback:(
379             fun () ->
380              buffer#remove_tag error_tag ~start:buffer#start_iter
381               ~stop:buffer#end_iter;
382              match !id with
383                 None -> assert false (* a race condition occurred *)
384               | Some id ->
385                  (new GObj.gobject_ops buffer#as_buffer)#disconnect id));
386       let flocb,floce = floc in
387       let floc =
388        {flocb with Lexing.pos_cnum = x}, {floce with Lexing.pos_cnum = y } in
389       raise (CicNotationParser.Parse_error (floc,err))
390   in
391   let text_of_loc loc =
392     let parsed_text_length = snd (CicNotationPt.loc_of_floc loc) in
393     let parsed_text = safe_substring s 0 parsed_text_length in
394     parsed_text, parsed_text_length
395   in
396   match st with
397   | GrafiteAst.Comment (loc,_)-> 
398       let parsed_text, parsed_text_length = text_of_loc loc in
399       let remain_len = String.length s - parsed_text_length in
400       let s = String.sub s parsed_text_length remain_len in
401       let s,len = 
402         eval_statement baseoffset (parsedlen + parsed_text_length) error_tag
403          buffer guistuff status user_goal script s 
404       in
405       (match s with
406       | (status, text) :: tl ->
407         ((status, parsed_text ^ text)::tl), (parsed_text_length + len)
408       | [] -> [], 0)
409   | GrafiteAst.Executable (loc, ex) ->
410       let parsed_text, parsed_text_length = text_of_loc loc in
411       eval_executable guistuff  status user_goal parsed_text script ex 
412   
413 let fresh_script_id =
414   let i = ref 0 in
415   fun () -> incr i; !i
416
417 class script  ~(view: GText.view)
418               ~(init: MatitaTypes.status) 
419               ~(mathviewer: MatitaTypes.mathViewer) 
420               ~set_star
421               ~ask_confirmation
422               ~urichooser 
423               ~develcreator 
424               () =
425 let buffer = view#buffer in
426 object (self)
427   val scriptId = fresh_script_id ()
428   
429   val guistuff = {
430     mathviewer = mathviewer;
431     urichooser = urichooser;
432     ask_confirmation = ask_confirmation;
433     develcreator = develcreator;
434     filenamedata = (None, None)} 
435   
436   method private getFilename =
437     match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
438     
439   method private ppFilename =
440     match guistuff.filenamedata with 
441     | Some f,_ -> f 
442     | None,_ -> sprintf ".unnamed%d.ma" scriptId
443   
444   initializer 
445     ignore(GMain.Timeout.add ~ms:300000 
446        ~callback:(fun _ -> self#_saveToBackuptFile ();true));
447     ignore(buffer#connect#modified_changed 
448        (fun _ -> if buffer#modified then 
449           set_star self#ppFilename true 
450         else 
451           set_star self#ppFilename false))
452
453   val mutable statements = [];    (** executed statements *)
454   val mutable history = [ init ];
455     (** list of states before having executed statements. Head element of this
456       * list is the current state, last element is the state at the beginning of
457       * the script.
458       * Invariant: this list length is 1 + length of statements *)
459
460   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
461   val mutable userGoal = ~-1
462
463   (** text mark and tag representing locked part of a script *)
464   val locked_mark =
465     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
466   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
467   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
468
469   method locked_mark = locked_mark
470   method locked_tag = locked_tag
471
472     (* history can't be empty, the invariant above grant that it contains at
473      * least the init status *)
474   method status = match history with hd :: _ -> hd | _ -> assert false
475
476   method private _advance ?statement () =
477     let s = match statement with Some s -> s | None -> self#getFuture in
478     MatitaLog.debug ("evaluating: " ^ first_line s ^ " ...");
479     let (entries, parsed_len) = 
480      eval_statement (buffer#get_iter_at_mark (`MARK locked_mark))#offset 0
481       error_tag buffer guistuff self#status userGoal self s
482     in
483     let (new_statuses, new_statements) = List.split entries in
484     history <- List.rev new_statuses @ history;
485     statements <- List.rev new_statements @ statements;
486     let start = buffer#get_iter_at_mark (`MARK locked_mark) in
487     let new_text = String.concat "" new_statements in
488     if statement <> None then
489      buffer#insert ~iter:start new_text
490     else
491      if new_text <> String.sub s 0 parsed_len then
492       begin
493        let stop = start#copy#forward_chars parsed_len in
494         buffer#delete ~start ~stop;
495         buffer#insert ~iter:start new_text;
496       end;
497     self#moveMark (String.length new_text)
498
499   method private _retract offset status new_statements new_history =
500    let cur_status = match history with s::_ -> s | [] -> assert false in
501     MatitaSync.time_travel ~present:cur_status ~past:status;
502     statements <- new_statements;
503     history <- new_history;
504     self#moveMark (- offset)
505
506   method advance ?statement () =
507     try
508       self#_advance ?statement ();
509       self#notify
510     with 
511     | Margin -> self#notify
512     | exc -> self#notify; raise exc
513
514   method retract () =
515     try
516       let cmp,new_statements,new_history,status =
517        match statements,history with
518           stat::statements, _::(status::_ as history) ->
519            String.length stat, statements, history, status
520        | [],[_] -> raise Margin
521        | _,_ -> assert false
522       in
523        self#_retract cmp status new_statements new_history;
524        self#notify
525     with 
526     | Margin -> self#notify
527     | exc -> self#notify; raise exc
528
529   method private getFuture =
530     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
531       ~stop:buffer#end_iter ()
532
533       
534   (** @param rel_offset relative offset from current position of locked_mark *)
535   method private moveMark rel_offset =
536     let mark = `MARK locked_mark in
537     let old_insert = buffer#get_iter_at_mark `INSERT in
538     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
539     let current_mark_pos = buffer#get_iter_at_mark mark in
540     let new_mark_pos =
541       match rel_offset with
542       | 0 -> current_mark_pos
543       | n when n > 0 -> current_mark_pos#forward_chars n
544       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
545     in
546     buffer#move_mark mark ~where:new_mark_pos;
547     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
548     buffer#move_mark `INSERT old_insert;
549     begin
550      match self#status.proof_status with
551         Incomplete_proof (_,goal) -> self#setGoal goal
552       | _ -> ()
553     end ;
554     let mark_position = buffer#get_iter_at_mark mark in
555     if view#move_mark_onscreen mark then
556      begin
557       buffer#move_mark mark mark_position;
558       view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
559      end;
560     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
561
562   method clean_dirty_lock =
563     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
564     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
565     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
566
567   val mutable observers = []
568
569   method addObserver (o: MatitaTypes.status -> unit) =
570     observers <- o :: observers
571
572   method private notify =
573     let status = self#status in
574     List.iter (fun o -> o status) observers
575
576   method loadFromFile f =
577     buffer#set_text (MatitaMisc.input_file f);
578     self#goto_top;
579     buffer#set_modified false
580     
581   method assignFileName file =
582     let abspath = MatitaMisc.absolute_path file in
583     let devel = MatitamakeLib.development_for_dir (Filename.dirname abspath) in
584     guistuff.filenamedata <- Some abspath, devel
585     
586   method saveToFile () =
587     let oc = open_out self#getFilename in
588     output_string oc (buffer#get_text ~start:buffer#start_iter
589                         ~stop:buffer#end_iter ());
590     close_out oc;
591     buffer#set_modified false
592   
593   method private _saveToBackuptFile () =
594     if buffer#modified then
595       begin
596         let f = self#ppFilename ^ "~" in
597         let oc = open_out f in
598         output_string oc (buffer#get_text ~start:buffer#start_iter
599                             ~stop:buffer#end_iter ());
600         close_out oc;
601         MatitaLog.debug ("backup " ^ f ^ " saved")                    
602       end
603   
604   method private goto_top =
605     MatitaSync.time_travel ~present:self#status ~past:init;
606     statements <- [];
607     history <- [ init ];
608     userGoal <- ~-1;
609     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
610     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
611
612   method reset () =
613     self#goto_top;
614     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
615     self#notify;
616     buffer#set_modified false
617
618   method template () =
619     let template = MatitaMisc.input_file BuildTimeConf.script_template in 
620     buffer#insert ~iter:(buffer#get_iter `START) template;
621     guistuff.filenamedata <- 
622       (None,MatitamakeLib.development_for_dir (Unix.getcwd ()));
623     buffer#set_modified false;
624     set_star self#ppFilename false
625
626   method goto (pos: [`Top | `Bottom | `Cursor]) () =
627     let old_locked_mark =
628      `MARK
629        (buffer#create_mark ~name:"old_locked_mark"
630          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
631     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
632     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
633     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
634     match pos with
635     | `Top -> dispose_old_locked_mark (); self#goto_top; self#notify
636     | `Bottom ->
637         (try 
638           let rec dowhile () =
639             self#_advance ();
640             let newpos = getpos () in
641             if (getoldpos ())#compare newpos < 0 then
642               begin
643                 buffer#move_mark old_locked_mark newpos;
644                 dowhile ()
645               end
646           in
647           dowhile ();
648           dispose_old_locked_mark ();
649           self#notify 
650         with 
651         | Margin -> dispose_old_locked_mark (); self#notify
652         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
653     | `Cursor ->
654         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
655         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
656         let remember =
657          `MARK
658            (buffer#create_mark ~name:"initial_insert"
659              ~left_gravity:true (cursor_iter ())) in
660         let dispose_remember () = buffer#delete_mark remember in
661         let remember_iter () =
662          buffer#get_iter_at_mark (`NAME "initial_insert") in
663         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
664         let icmp = cmp () in
665         let forward_until_cursor () = (* go forward until locked > cursor *)
666           let rec aux () =
667             self#_advance ();
668             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
669             then
670              begin
671               buffer#move_mark old_locked_mark (getpos ());
672               aux ()
673              end
674           in
675           aux ()
676         in
677         let rec back_until_cursor len = (* go backward until locked < cursor *)
678          function
679             statements, (status::_ as history) when len <= 0 ->
680              self#_retract (icmp - len) status statements history
681           | statement::tl1, _::tl2 ->
682              back_until_cursor (len - String.length statement) (tl1,tl2)
683           | _,_ -> assert false
684         in
685         (try
686           begin
687            if icmp < 0 then       (* locked < cursor *)
688              (forward_until_cursor (); self#notify)
689            else if icmp > 0 then  (* locked > cursor *)
690              (back_until_cursor icmp (statements,history); self#notify)
691            else                  (* cursor = locked *)
692                ()
693           end ;
694           dispose_remember ();
695           dispose_old_locked_mark ();
696         with 
697         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
698         | exc -> dispose_remember (); dispose_old_locked_mark ();
699                  self#notify; raise exc)
700               
701   method onGoingProof () =
702     match self#status.proof_status with
703     | No_proof | Proof _ -> false
704     | Incomplete_proof _ -> true
705     | Intermediate _ -> assert false
706
707   method proofStatus = MatitaMisc.get_proof_status self#status
708   method proofMetasenv = MatitaMisc.get_proof_metasenv self#status
709   method proofContext = MatitaMisc.get_proof_context self#status
710   method proofConclusion = MatitaMisc.get_proof_conclusion self#status
711   method setGoal n = userGoal <- n
712
713   method eos = 
714     let s = self#getFuture in
715     let rec is_there_and_executable s = 
716       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
717       let st = GrafiteParser.parse_statement (Stream.of_string s) in
718       match st with
719       | GrafiteAst.Comment (loc,_)-> 
720           let parsed_text_length = snd (CicNotationPt.loc_of_floc loc) in
721           let remain_len = String.length s - parsed_text_length in
722           let next = String.sub s parsed_text_length remain_len in
723           is_there_and_executable next
724       | GrafiteAst.Executable (loc, ex) -> false
725     in
726     try
727       is_there_and_executable s
728     with 
729     | CicNotationParser.Parse_error _ -> false
730     | Margin -> true
731       
732     
733     
734   (* debug *)
735   method dump () =
736     MatitaLog.debug "script status:";
737     MatitaLog.debug ("history size: " ^ string_of_int (List.length history));
738     MatitaLog.debug (sprintf "%d statements:" (List.length statements));
739     List.iter MatitaLog.debug statements;
740     MatitaLog.debug ("Current file name: " ^
741       (match guistuff.filenamedata with 
742       |None,_ -> "[ no name ]" 
743       | Some f,_ -> f));
744
745 end
746
747 let _script = ref None
748
749 let script ~view ~init ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
750 =
751   let s = new script 
752     ~view ~init ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
753   in
754   _script := Some s;
755   s
756
757 let instance () = match !_script with None -> assert false | Some s -> s
758
759