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