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