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