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