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