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