]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaScript.ml
fixed a specific case in development handling
[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 "%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 = TacticAst in
65   let loc = CicAst.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 = TacticAst in
78   let module TAPp = TacticAstPp 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 "automathic 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 (CicTextualParser2.EnvironmentP3.to_string 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 root = MatitamakeLib.root_for_development d in
153         let target = root ^ "/" ^ what in
154         if not(MatitamakeLib.build_development ~target d) then
155           raise exc
156         else
157           eval_with_engine guistuff status user_goal parsed_text st
158       in
159       let do_nothing () = [], 0 in
160       let handle_with_devel d =
161         let name = MatitamakeLib.name_for_development d in
162         let title = "Unable to include " ^ what in
163         let message = 
164           what ^ " is handled by development <b>" ^ name ^ "</b>.\n\n" ^
165           "<i>Should I compile it and Its dependencies?</i>"
166         in
167         (match guistuff.ask_confirmation ~title ~message with
168         | `YES -> compile_needed_and_go_on d
169         | `NO -> raise exc
170         | `CANCEL -> do_nothing ())
171       in
172       let handle_withoud_devel filename =
173         let title = "Unable to include " ^ what in
174         let message = 
175          what ^ " is <b>not</b> handled by a development.\n" ^
176          "All dependencies are authomatically solved for a development.\n\n" ^
177          "<i>Do you want to set up a development?</i>"
178         in
179         (match guistuff.ask_confirmation ~title ~message with
180         | `YES -> 
181             (match filename with
182             | Some f -> 
183                 guistuff.develcreator ~containing:(Some (Filename.dirname f))
184             | None -> guistuff.develcreator ~containing:None);
185             do_nothing ()
186         | `NO -> raise exc
187         | `CANCEL -> do_nothing())
188       in
189       match guistuff.filenamedata with
190       | None,None -> handle_withoud_devel None
191       | None,Some d -> handle_with_devel d
192       | Some f,_ ->
193           match MatitamakeLib.development_for_dir (Filename.dirname f) with
194           | None -> handle_withoud_devel (Some f)
195           | Some d -> handle_with_devel d
196 ;;
197
198 let disambiguate term status =
199   let module MD = MatitaDisambiguator in
200   let dbd = MatitaDb.instance () in
201   let metasenv = MatitaMisc.get_proof_metasenv status in
202   let context = MatitaMisc.get_proof_context status in
203   let aliases = MatitaMisc.get_proof_aliases status in
204   let interps = MD.disambiguate_term dbd context metasenv aliases term in
205   match interps with 
206   | [_,_,x,_] -> x
207   | _ -> assert false
208  
209 let eval_macro guistuff status parsed_text script mac
210 =
211   let module TA = TacticAst in
212   let module TAPp = TacticAstPp in
213   let module MQ = MetadataQuery in
214   let module MDB = MatitaDb in
215   let module CTC = CicTypeChecker in
216   let module CU = CicUniv in
217   (* no idea why ocaml wants this *)
218   let advance ?statement () = script#advance ?statement () in
219   let parsed_text_length = String.length parsed_text in
220   let dbd = MatitaDb.instance () in
221   match mac with
222   (* WHELP's stuff *)
223   | TA.WMatch (loc, term) -> 
224       let term = disambiguate term status in
225       let l =  MQ.match_term ~dbd term in
226       let entry = `Whelp (TAPp.pp_macro_cic (TA.WMatch (loc, term)), l) in
227       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
228       [], parsed_text_length
229   | TA.WInstance (loc, term) ->
230       let term = disambiguate term status in
231       let l = MQ.instance ~dbd term in
232       let entry = `Whelp (TAPp.pp_macro_cic (TA.WInstance (loc, term)), l) in
233       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
234       [], parsed_text_length
235   | TA.WLocate (loc, s) -> 
236       let l = MQ.locate ~dbd s in
237       let entry = `Whelp (TAPp.pp_macro_cic (TA.WLocate (loc, s)), l) in
238       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
239       [], parsed_text_length
240   | TA.WElim (loc, term) ->
241       let term = disambiguate term status in
242       let uri =
243         match term with
244         | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
245         | _ -> failwith "Not a MutInd"
246       in
247       let l = MQ.elim ~dbd uri in
248       let entry = `Whelp (TAPp.pp_macro_cic (TA.WElim (loc, term)), l) in
249       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
250       [], parsed_text_length
251   | TA.WHint (loc, term) ->
252       let term = disambiguate term status in
253       let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
254       let l = List.map fst (MQ.experimental_hint ~dbd s) in
255       let entry = `Whelp (TAPp.pp_macro_cic (TA.WHint (loc, term)), l) in
256       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
257       [], parsed_text_length
258   (* REAL macro *)
259   | TA.Hint loc -> 
260       let s = MatitaMisc.get_proof_status status in
261       let l = List.map fst (MQ.experimental_hint ~dbd s) in
262       let selected = guistuff.urichooser l in
263       (match selected with
264       | [] -> [], parsed_text_length
265       | [uri] -> 
266         let ast = 
267          TA.Executable (loc,
268           (TA.Tactical (loc, 
269             TA.Tactic (loc,
270              TA.Apply (loc, CicAst.Uri (UriManager.string_of_uri uri,None))))))
271         in
272         let new_status = MatitaEngine.eval_ast status ast in
273         let extra_text = 
274           comment parsed_text ^ 
275           "\n" ^ TAPp.pp_statement ast
276         in
277         [ new_status , extra_text ], parsed_text_length
278       | _ -> 
279           MatitaLog.error 
280             "The result of the urichooser should be only 1 uri, not:\n";
281           List.iter (
282             fun u -> MatitaLog.error (UriManager.string_of_uri u ^ "\n")
283           ) selected;
284           assert false)
285   | TA.Check (_,term) ->
286       let metasenv = MatitaMisc.get_proof_metasenv status in
287       let context = MatitaMisc.get_proof_context status in
288       let aliases = MatitaMisc.get_proof_aliases status in
289       let interps = 
290         MatitaDisambiguator.disambiguate_term 
291           dbd context metasenv aliases term 
292       in
293       let _, metasenv , term, ugraph =
294         match interps with 
295         | [x] -> x
296         | _ -> assert false
297       in
298       let ty,_ = CTC.type_of_aux' metasenv context term ugraph in
299       let t_and_ty = Cic.Cast (term,ty) in
300       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
301       [], parsed_text_length
302 (*   | TA.Abort _ -> 
303       let rec go_back () =
304         let status = script#status.proof_status in
305         match status with
306         | No_proof -> ()
307         | _ -> script#retract ();go_back()
308       in
309       [], parsed_text_length, Some go_back
310   | TA.Redo (_, Some i) ->  [], parsed_text_length, 
311       Some (fun () -> for j = 1 to i do advance () done)
312   | TA.Redo (_, None) ->   [], parsed_text_length, 
313       Some (fun () -> advance ())
314   | TA.Undo (_, Some i) ->  [], parsed_text_length, 
315       Some (fun () -> for j = 1 to i do script#retract () done)
316   | TA.Undo (_, None) -> [], parsed_text_length, 
317       Some (fun () -> script#retract ()) *)
318   (* TODO *)
319   | TA.Quit _ -> failwith "not implemented"
320   | TA.Print (_,kind) -> failwith "not implemented"
321   | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
322   | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
323
324                                 
325 let eval_executable guistuff status user_goal parsed_text script ex =
326   let module TA = TacticAst in
327   let module TAPp = TacticAstPp in
328   let module MD = MatitaDisambiguator in
329   let module ML = MatitacleanLib in
330   let parsed_text_length = String.length parsed_text in
331   match ex with
332   | TA.Command (loc, _) | TA.Tactical (loc, _) ->
333       (try 
334         (match ML.baseuri_of_baseuri_decl (TA.Executable (loc,ex)) with
335         | None -> ()
336         | Some u -> 
337             if not (MatitacleanLib.is_empty u) then
338               match 
339                 guistuff.ask_confirmation 
340                   ~title:"Baseuri redefinition" 
341                   ~message:(
342                     "Baseuri " ^ u ^ " already exists.\n" ^
343                     "Do you want to redefine the corresponding "^
344                     "part of the library?")
345               with
346               | `YES -> MatitacleanLib.clean_baseuris [u]
347               | `NO -> ()
348               | `CANCEL -> raise MatitaTypes.Cancel);
349         eval_with_engine 
350           guistuff status user_goal parsed_text (TA.Executable (loc, ex))
351       with MatitaTypes.Cancel -> [], 0)
352   | TA.Macro (_,mac) ->
353       eval_macro guistuff status parsed_text script mac
354
355 let rec eval_statement guistuff status user_goal script s =
356   if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
357   let st = CicTextualParser2.parse_statement (Stream.of_string s) in
358   let text_of_loc loc =
359     let parsed_text_length = snd (CicAst.loc_of_floc loc) in
360     let parsed_text = safe_substring s 0 parsed_text_length in
361     parsed_text, parsed_text_length
362   in
363   match st with
364   | TacticAst.Comment (loc,_)-> 
365       let parsed_text, parsed_text_length = text_of_loc loc in
366       let remain_len = String.length s - parsed_text_length in
367       let s = String.sub s parsed_text_length remain_len in
368       let s,len = 
369         eval_statement guistuff status user_goal script s 
370       in
371       (match s with
372       | (status, text) :: tl ->
373         ((status, parsed_text ^ text)::tl), (parsed_text_length + len)
374       | [] -> [], 0)
375   | TacticAst.Executable (loc, ex) ->
376       let parsed_text, parsed_text_length = text_of_loc loc in
377       eval_executable guistuff  status user_goal parsed_text script ex 
378   
379 let fresh_script_id =
380   let i = ref 0 in
381   fun () -> incr i; !i
382
383 class script ~(buffer: GText.buffer) ~(init: MatitaTypes.status) 
384               ~(mathviewer: MatitaTypes.mathViewer) 
385               ~set_star
386               ~ask_confirmation
387               ~urichooser 
388               ~develcreator 
389               () =
390 object (self)
391   val scriptId = fresh_script_id ()
392   
393   val guistuff = {
394     mathviewer = mathviewer;
395     urichooser = urichooser;
396     ask_confirmation = ask_confirmation;
397     develcreator = develcreator;
398     filenamedata = (None, None)} 
399   
400   method private getFilename =
401     match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
402     
403   method private ppFilename =
404     match guistuff.filenamedata with 
405     | Some f,_ -> f 
406     | None,_ -> sprintf ".unnamed%d.ma" scriptId
407   
408   initializer 
409     ignore(GMain.Timeout.add ~ms:300000 
410        ~callback:(fun _ -> self#_saveToBackuptFile ();true));
411     ignore(buffer#connect#modified_changed 
412        (fun _ -> if buffer#modified then 
413           set_star self#ppFilename true 
414         else 
415           set_star self#ppFilename false));
416     self#reset ();
417     self#template ()
418
419   val mutable statements = [];    (** executed statements *)
420   val mutable history = [ init ];
421     (** list of states before having executed statements. Head element of this
422       * list is the current state, last element is the state at the beginning of
423       * the script.
424       * Invariant: this list length is 1 + length of statements *)
425
426   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
427   val mutable userGoal = ~-1
428
429   (** text mark and tag representing locked part of a script *)
430   val locked_mark =
431     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
432   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
433
434     (* history can't be empty, the invariant above grant that it contains at
435      * least the init status *)
436   method status = match history with hd :: _ -> hd | _ -> assert false
437
438   method private _advance ?statement () =
439     let s = match statement with Some s -> s | None -> self#getFuture in
440     MatitaLog.debug ("evaluating: " ^ first_line s ^ " ...");
441     let (entries, parsed_len) = 
442       eval_statement guistuff self#status userGoal self s
443     in
444     let (new_statuses, new_statements) = List.split entries in
445 (*
446 prerr_endline "evalStatement returned";
447 List.iter (fun s -> prerr_endline ("'" ^ s ^ "'")) new_statements;
448 *)
449     history <- List.rev new_statuses @ history;
450     statements <- List.rev new_statements @ statements;
451     let start = buffer#get_iter_at_mark (`MARK locked_mark) in
452     let new_text = String.concat "" new_statements in
453     if new_text <> String.sub s 0 parsed_len then
454       begin
455 (*       prerr_endline ("new:" ^ new_text); *)
456 (*       prerr_endline ("s:" ^ String.sub s 0 parsed_len); *)
457       let stop = start#copy#forward_chars parsed_len in
458       buffer#delete ~start ~stop;
459       buffer#insert ~iter:start new_text;
460 (*       prerr_endline "AUTOMATICALLY MODIFIED!!!!!" *)
461       end;
462     self#moveMark (String.length new_text)
463
464   method private _retract () =
465     match statements, history with
466     | last_statement :: _, cur_status :: prev_status :: _ ->
467         MatitaSync.time_travel ~present:cur_status ~past:prev_status;
468         statements <- List.tl statements;
469         history <- List.tl history;
470         self#moveMark (- (String.length last_statement));
471     | _ -> raise Margin
472
473   method advance ?statement () =
474     try
475       self#_advance ?statement ();
476       self#notify
477     with 
478     | Margin -> self#notify
479     | exc -> self#notify; raise exc
480
481   method retract () =
482     try
483       self#_retract ();
484       self#notify
485     with 
486     | Margin -> self#notify
487     | exc -> self#notify; raise exc
488
489   method private getFuture =
490     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
491       ~stop:buffer#end_iter ()
492
493       
494   (** @param rel_offset relative offset from current position of locked_mark *)
495   method private moveMark rel_offset =
496     let mark = `MARK locked_mark in
497     let old_insert = buffer#get_iter_at_mark `INSERT in
498     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
499     let current_mark_pos = buffer#get_iter_at_mark mark in
500     let new_mark_pos =
501       match rel_offset with
502       | 0 -> current_mark_pos
503       | n when n > 0 -> current_mark_pos#forward_chars n
504       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
505     in
506     buffer#move_mark mark ~where:new_mark_pos;
507     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
508     buffer#move_mark `INSERT old_insert;
509     begin
510      match self#status.proof_status with
511         Incomplete_proof (_,goal) -> self#setGoal goal
512       | _ -> ()
513     end ;
514     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
515
516   method clean_dirty_lock =
517     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
518     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
519     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
520
521   val mutable observers = []
522
523   method addObserver (o: MatitaTypes.status -> unit) =
524     observers <- o :: observers
525
526   method private notify =
527     let status = self#status in
528     List.iter (fun o -> o status) observers
529
530   method loadFromFile () =
531     buffer#set_text (MatitaMisc.input_file self#getFilename);
532     self#goto_top;
533     buffer#set_modified false
534     
535   method assignFileName file =
536     let abspath = MatitaMisc.absolute_path file in
537     let devel = MatitamakeLib.development_for_dir (Filename.dirname abspath) in
538     guistuff.filenamedata <- Some abspath, devel
539     
540   method saveToFile () =
541     let oc = open_out self#getFilename in
542     output_string oc (buffer#get_text ~start:buffer#start_iter
543                         ~stop:buffer#end_iter ());
544     close_out oc;
545     buffer#set_modified false
546   
547   method private _saveToBackuptFile () =
548     if buffer#modified then
549       begin
550         let f = self#ppFilename ^ "~" in
551         let oc = open_out f in
552         output_string oc (buffer#get_text ~start:buffer#start_iter
553                             ~stop:buffer#end_iter ());
554         close_out oc;
555         MatitaLog.debug ("backup " ^ f ^ " saved")                    
556       end
557   
558   method private goto_top =
559     MatitaSync.time_travel ~present:self#status ~past:init;
560     statements <- [];
561     history <- [ init ];
562     userGoal <- ~-1;
563     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
564     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
565
566   method reset () =
567     self#goto_top;
568     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
569     self#notify;
570     buffer#set_modified false
571
572   method template () =
573     let template = MatitaMisc.input_file BuildTimeConf.script_template in 
574     buffer#insert ~iter:(buffer#get_iter `START) template;
575     guistuff.filenamedata <- 
576       (None,MatitamakeLib.development_for_dir (Unix.getcwd ()));
577     buffer#set_modified false;
578     set_star self#ppFilename false
579
580   method goto (pos: [`Top | `Bottom | `Cursor]) () =
581     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
582     match pos with
583     | `Top -> self#goto_top; self#notify
584     | `Bottom ->
585         (try 
586           let rec dowhile pos =
587             self#_advance ();
588             if pos#compare (getpos ()) < 0 then
589               dowhile (getpos ())
590           in
591           dowhile (getpos ());
592           self#notify 
593         with 
594         | Margin -> self#notify
595         | exc -> self#notify; raise exc)
596     | `Cursor ->
597         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
598         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
599         let forward_until_cursor () = (* go forward until locked > cursor *)
600           let rec aux oldpos =
601             self#_advance ();
602             if (locked_iter ())#compare (cursor_iter ()) < 0 &&
603                oldpos#compare (getpos ()) < 0 
604             then
605               aux (getpos ())
606           in
607           aux (getpos ())
608         in
609         let rec back_until_cursor () = (* go backward until locked < cursor *)
610           self#_retract ();
611           if (locked_iter ())#compare (cursor_iter ()) > 0 then
612             back_until_cursor ()
613         in
614         let cmp = (locked_iter ())#compare (cursor_iter ()) in
615         (try
616           if cmp < 0 then       (* locked < cursor *)
617             (forward_until_cursor (); self#notify)
618           else if cmp > 0 then  (* locked > cursor *)
619             (back_until_cursor (); self#notify)
620           else                  (* cursor = locked *)
621               ()
622         with 
623         | Margin -> self#notify
624         | exc -> self#notify; raise exc)
625               
626   method onGoingProof () =
627     match self#status.proof_status with
628     | No_proof | Proof _ -> false
629     | Incomplete_proof _ -> true
630     | Intermediate _ -> assert false
631
632   method proofStatus = MatitaMisc.get_proof_status self#status
633   method proofMetasenv = MatitaMisc.get_proof_metasenv self#status
634   method proofContext = MatitaMisc.get_proof_context self#status
635   method setGoal n = userGoal <- n
636
637   method eos = 
638     let s = self#getFuture in
639     let rec is_there_and_executable s = 
640       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
641       let st = CicTextualParser2.parse_statement (Stream.of_string s) in
642       match st with
643       | TacticAst.Comment (loc,_)-> 
644           let parsed_text_length = snd (CicAst.loc_of_floc loc) in
645           let remain_len = String.length s - parsed_text_length in
646           let next = String.sub s parsed_text_length remain_len in
647           is_there_and_executable next
648       | TacticAst.Executable (loc, ex) -> false
649     in
650     try
651       is_there_and_executable s
652     with 
653     | CicTextualParser2.Parse_error _ -> false
654     | Margin -> true
655       
656     
657     
658   (* debug *)
659   method dump () =
660     MatitaLog.debug "script status:";
661     MatitaLog.debug ("history size: " ^ string_of_int (List.length history));
662     MatitaLog.debug (sprintf "%d statements:" (List.length statements));
663     List.iter MatitaLog.debug statements;
664     MatitaLog.debug ("Current file name: " ^
665       (match guistuff.filenamedata with 
666       |None,_ -> "[ no name ]" 
667       | Some f,_ -> f));
668
669 end
670
671 let _script = ref None
672
673 let script ~buffer ~init ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
674 =
675   let s = new script 
676     ~buffer ~init ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
677   in
678   _script := Some s;
679   s
680
681 let instance () = match !_script with None -> assert false | Some s -> s
682
683