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