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