]> matita.cs.unibo.it Git - helm.git/blob - matita/matitaScript.ml
snapshot for camlp5 v5
[helm.git] / matita / matitaScript.ml
1 (* Copyright (C) 2004-2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 open Printf
29 open GrafiteTypes
30
31 module TA = GrafiteAst
32
33 let debug = false
34 let debug_print = if debug then prerr_endline else ignore
35
36   (** raised when one of the script margins (top or bottom) is reached *)
37 exception Margin
38 exception NoUnfinishedProof
39 exception ActionCancelled of string
40
41 let safe_substring s i j =
42   try String.sub s i j with Invalid_argument _ -> assert false
43
44 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*"
45 let heading_nl_RE' = Pcre.regexp "^(\\s*\n\\s*)"
46 let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$"
47 let multiline_RE = Pcre.regexp "^\n[^\n]+$"
48 let newline_RE = Pcre.regexp "\n"
49 let comment_RE = Pcre.regexp "\\(\\*(.|\n)*\\*\\)\n?" ~flags:[`UNGREEDY]
50  
51 let comment str =
52   if Pcre.pmatch ~rex:multiline_RE str then
53     "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " *)"
54   else
55     "\n(**\n" ^ str ^ "\n*)"
56
57 let strip_comments str =
58   Pcre.qreplace ~templ:"\n" ~pat:"\n\n" (Pcre.qreplace ~rex:comment_RE str)
59 ;;
60                      
61 let first_line s =
62   let s = Pcre.replace ~rex:heading_nl_RE s in
63   try
64     let nl_pos = String.index s '\n' in
65     String.sub s 0 nl_pos
66   with Not_found -> s
67
68 type guistuff = {
69   mathviewer:MatitaTypes.mathViewer;
70   urichooser: UriManager.uri list -> UriManager.uri list;
71   ask_confirmation: title:string -> message:string -> [`YES | `NO | `CANCEL];
72   develcreator: containing:string option -> unit;
73   mutable filenamedata: string option * MatitamakeLib.development option
74 }
75
76 let eval_with_engine guistuff lexicon_status grafite_status user_goal
77  skipped_txt nonskipped_txt st
78 =
79   let module TAPp = GrafiteAstPp in
80   let module DTE = DisambiguateTypes.Environment in
81   let module DP = DisambiguatePp in
82   let parsed_text_length =
83     String.length skipped_txt + String.length nonskipped_txt 
84   in
85   let text = skipped_txt ^ nonskipped_txt in
86   let prefix_len = MatitaGtkMisc.utf8_string_length skipped_txt in
87   let enriched_history_fragment =
88    MatitaEngine.eval_ast ~do_heavy_checks:(Helm_registry.get_bool
89      "matita.do_heavy_checks")
90     lexicon_status grafite_status (text,prefix_len,st)
91   in
92   let enriched_history_fragment = List.rev enriched_history_fragment in
93   (* really fragile *)
94   let res,_ = 
95     List.fold_left 
96       (fun (acc, to_prepend) (status,alias) ->
97        match alias with
98        | None -> (status,to_prepend ^ nonskipped_txt)::acc,""
99        | Some (k,((v,_) as value)) ->
100             let newtxt = DP.pp_environment (DTE.add k value DTE.empty) in
101             (status,to_prepend ^ newtxt ^ "\n")::acc, "")
102       ([],skipped_txt) enriched_history_fragment
103   in
104   res,"",parsed_text_length
105
106 let wrap_with_developments guistuff f arg = 
107   let compile_needed_and_go_on lexiconfile d exc =
108     let target = Pcre.replace ~pat:"lexicon$" ~templ:"moo" lexiconfile in
109     let target = Pcre.replace ~pat:"metadata$" ~templ:"moo" target in
110     let refresh_cb () = 
111       while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
112     in
113     if not(MatitamakeLib.build_development_in_bg ~target refresh_cb d) then
114       raise exc
115     else
116       f arg
117   in
118   let do_nothing () = raise (ActionCancelled "Inclusion not performed") in
119   let check_if_file_is_exists f =
120     assert(Pcre.pmatch ~pat:"ma$" f);
121     let pwd = Sys.getcwd () in
122     let f_pwd = pwd ^ "/" ^ f in
123     if not (HExtlib.is_regular f_pwd) then
124       raise (ActionCancelled ("File "^f_pwd^" does not exists!"))
125     else
126       raise 
127         (ActionCancelled 
128           ("Internal error: "^f_pwd^" exists but I'm unable to include it!"))
129   in
130   let handle_with_devel d lexiconfile mafile exc =
131     let name = MatitamakeLib.name_for_development d in
132     let title = "Unable to include " ^ lexiconfile in
133     let message = 
134       mafile ^ " is handled by development <b>" ^ name ^ "</b>.\n\n" ^
135       "<i>Should I compile it and Its dependencies?</i>"
136     in
137     (match guistuff.ask_confirmation ~title ~message with
138     | `YES -> compile_needed_and_go_on lexiconfile d exc
139     | `NO -> raise exc
140     | `CANCEL -> do_nothing ())
141   in
142   let handle_without_devel mafilename exc =
143     let title = "Unable to include " ^ mafilename in
144     let message = 
145      mafilename ^ " is <b>not</b> handled by a development.\n" ^
146      "All dependencies are automatically solved for a development.\n\n" ^
147      "<i>Do you want to set up a development?</i>"
148     in
149     (match guistuff.ask_confirmation ~title ~message with
150     | `YES -> 
151         guistuff.develcreator ~containing:(Some (Filename.dirname mafilename));
152         do_nothing ()
153     | `NO -> raise exc
154     | `CANCEL -> do_nothing())
155   in
156   try 
157     f arg
158   with
159   | DependenciesParser.UnableToInclude mafilename -> 
160       assert (Pcre.pmatch ~pat:"ma$" mafilename);
161       check_if_file_is_exists mafilename
162   | LexiconEngine.IncludedFileNotCompiled (xfilename,mafilename) 
163   | GrafiteEngine.IncludedFileNotCompiled (xfilename,mafilename) as exn ->
164       assert (Pcre.pmatch ~pat:"ma$" mafilename);
165       assert (Pcre.pmatch ~pat:"lexicon$" xfilename || 
166               Pcre.pmatch ~pat:"mo$" xfilename );
167       (* we know that someone was able to include the .ma, get the baseuri
168        * but was unable to get the compilation output 'xfilename' *)
169       match MatitamakeLib.development_for_dir (Filename.dirname mafilename) with
170       | None -> handle_without_devel mafilename exn
171       | Some d -> handle_with_devel d xfilename mafilename exn
172 ;;
173     
174 let eval_with_engine
175      guistuff lexicon_status grafite_status user_goal 
176        skipped_txt nonskipped_txt st
177 =
178   wrap_with_developments guistuff
179     (eval_with_engine 
180       guistuff lexicon_status grafite_status user_goal 
181         skipped_txt nonskipped_txt) st
182 ;;
183
184 let pp_eager_statement_ast =
185   GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
186     ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
187
188 (* naive implementation of procedural proof script generation, 
189  * starting from an applicatiove *auto generated) proof.
190  * this is out of place, but I like it :-P *)
191 let cic2grafite context menv t =
192   (* indents a proof script in a stupid way, better than nothing *)
193   let stupid_indenter s =
194     let next s = 
195       let idx_square_o = try String.index s '[' with Not_found -> -1 in
196       let idx_square_c = try String.index s ']' with Not_found -> -1 in
197       let idx_pipe = try String.index s '|' with Not_found -> -1 in
198       let tok = 
199         List.sort (fun (i,_) (j,_) -> compare i j)
200           [idx_square_o,'[';idx_square_c,']';idx_pipe,'|']
201       in
202       let tok = List.filter (fun (i,_) -> i <> -1) tok in
203       match tok with
204       | (i,c)::_ -> Some (i,c)
205       | _ -> None
206     in
207     let break_apply n s =
208       let tab = String.make (n+1) ' ' in
209       Pcre.replace ~templ:(".\n" ^ tab ^ "apply") ~pat:"\\.apply" s
210     in
211     let rec ind n s =
212       match next s with
213       | None -> 
214           s
215       | Some (position, char) ->
216           try 
217             let s1, s2 = 
218               String.sub s 0 position, 
219               String.sub s (position+1) (String.length s - (position+1))
220             in
221             match char with
222             | '[' -> break_apply n s1 ^ "\n" ^ String.make (n+2) ' ' ^
223                        "[" ^ ind (n+2) s2
224             | '|' -> break_apply n s1 ^ "\n" ^ String.make n ' ' ^ 
225                        "|" ^ ind n s2
226             | ']' -> break_apply n s1 ^ "\n" ^ String.make n ' ' ^ 
227                        "]" ^ ind (n-2) s2
228             | _ -> assert false
229           with
230           Invalid_argument err -> 
231             prerr_endline err;
232             s
233     in
234      ind 0 s
235   in
236   let module PT = CicNotationPt in
237   let module GA = GrafiteAst in
238   let pp_t context t =
239     let names = 
240       List.map (function Some (n,_) -> Some n | None -> None) context 
241     in
242     CicPp.pp t names
243   in
244   let sort_of context t = 
245     try
246       let ty,_ = 
247         CicTypeChecker.type_of_aux' menv context t
248           CicUniv.oblivion_ugraph 
249       in
250       let sort,_ = CicTypeChecker.type_of_aux' menv context ty
251           CicUniv.oblivion_ugraph
252       in
253       match sort with
254       | Cic.Sort Cic.Prop -> true
255       | _ -> false
256     with
257       CicTypeChecker.TypeCheckerFailure _ ->
258         HLog.error "auto proof to sript transformation error"; false
259   in
260   let floc = HExtlib.dummy_floc in
261   (* minimalisti cic.term -> pt.term *)
262   let print_term c t =
263     let rec aux c = function
264       | Cic.Rel _
265       | Cic.MutConstruct _ 
266       | Cic.MutInd _ 
267       | Cic.Const _ as t -> 
268           PT.Ident (pp_t c t, None)
269       | Cic.Appl l -> PT.Appl (List.map (aux c) l)
270       | Cic.Implicit _ -> PT.Implicit
271       | Cic.Lambda (Cic.Name n, s, t) ->
272           PT.Binder (`Lambda, (PT.Ident (n,None), Some (aux c s)),
273             aux (Some (Cic.Name n, Cic.Decl s)::c) t)
274       | Cic.Prod (Cic.Name n, s, t) ->
275           PT.Binder (`Forall, (PT.Ident (n,None), Some (aux c s)),
276             aux (Some (Cic.Name n, Cic.Decl s)::c) t)
277       | Cic.LetIn (Cic.Name n, s, t) ->
278           PT.Binder (`Lambda, (PT.Ident (n,None), Some (aux c s)),
279             aux (Some (Cic.Name n, Cic.Def (s,None))::c) t)
280       | Cic.Meta _ -> PT.Implicit
281       | Cic.Sort (Cic.Type u) -> PT.Sort (`Type u)
282       | Cic.Sort Cic.Set -> PT.Sort `Set
283       | Cic.Sort Cic.CProp -> PT.Sort `CProp
284       | Cic.Sort Cic.Prop -> PT.Sort `Prop
285       | _ as t -> PT.Ident ("ERROR: "^CicPp.ppterm t, None)
286     in
287     aux c t
288   in
289   (* prints an applicative proof, that is an auto proof.
290    * don't use in the general case! *)
291   let rec print_proof context = function
292     | Cic.Rel _
293     | Cic.Const _ as t -> 
294         [GA.Executable (floc, 
295           GA.Tactic (floc,
296           Some (GA.Apply (floc, print_term context t)), GA.Dot floc))]
297     | Cic.Appl (he::tl) ->
298         let tl = List.map (fun t -> t, sort_of context t) tl in
299         let subgoals = 
300           HExtlib.filter_map (function (t,true) -> Some t | _ -> None) tl
301         in
302         let args = 
303           List.map (function | (t,true) -> Cic.Implicit None | (t,_) -> t) tl
304         in
305         if List.length subgoals > 1 then
306           (* branch *)
307           [GA.Executable (floc, 
308             GA.Tactic (floc,
309               Some (GA.Apply (floc, print_term context (Cic.Appl (he::args)))),
310               GA.Semicolon floc))] @
311           [GA.Executable (floc, GA.Tactic (floc, None, GA.Branch floc))] @
312           (HExtlib.list_concat 
313           ~sep:[GA.Executable (floc, GA.Tactic (floc, None,GA.Shift floc))]
314             (List.map (print_proof context) subgoals)) @
315           [GA.Executable (floc, GA.Tactic (floc, None,GA.Merge floc))]
316         else
317           (* simple apply *)
318           [GA.Executable (floc, 
319             GA.Tactic (floc,
320             Some (GA.Apply 
321               (floc, print_term context (Cic.Appl (he::args)) )), GA.Dot floc))]
322           @
323           (match subgoals with
324           | [] -> []
325           | [x] -> print_proof context x
326           | _ -> assert false)
327     | Cic.Lambda (Cic.Name n, ty, bo) ->
328         [GA.Executable (floc, 
329           GA.Tactic (floc,
330             Some (GA.Cut (floc, Some n, (print_term context ty))),
331             GA.Branch floc))] @
332         (print_proof (Some (Cic.Name n, Cic.Decl ty)::context) bo) @
333         [GA.Executable (floc, GA.Tactic (floc, None,GA.Shift floc))] @
334         [GA.Executable (floc, GA.Tactic (floc, 
335           Some (GA.Assumption floc),GA.Merge floc))]
336     | _ -> []
337     (*
338         debug_print (lazy (CicPp.ppterm t));
339         assert false
340         *)
341   in
342   (* performs a lambda closure of the proof term abstracting metas.
343    * this is really an approximation of a closure, local subst of metas 
344    * is not kept into account *)
345   let close_pt menv context t =
346     let metas = CicUtil.metas_of_term t in
347     let metas = 
348       HExtlib.list_uniq ~eq:(fun (i,_) (j,_) -> i = j)
349         (List.sort (fun (i,_) (j,_) -> compare i j) metas)
350     in
351     let mk_rels_and_collapse_metas metas = 
352       let rec aux i map acc acc1 = function 
353         | [] -> acc, acc1, map
354         | (j,_ as m)::tl -> 
355             let _,_,ty = CicUtil.lookup_meta j menv in
356             try 
357               let n = List.assoc ty map in
358               aux i map (Cic.Rel n :: acc) (m::acc1) tl 
359             with Not_found -> 
360               let map = (ty, i)::map in
361               aux (i+1) map (Cic.Rel i :: acc) (m::acc1) tl
362       in
363       aux 1 [] [] [] metas
364     in
365     let rels, metas, map = mk_rels_and_collapse_metas metas in
366     let n_lambdas = List.length map in
367     let t = 
368       if metas = [] then 
369         t 
370       else
371         let t =
372           ProofEngineReduction.replace_lifting
373            ~what:(List.map (fun (x,_) -> Cic.Meta (x,[])) metas)
374            ~with_what:rels
375            ~context:context
376            ~equality:(fun _ x y ->
377              match x,y with
378              | Cic.Meta(i,_), Cic.Meta(j,_) when i=j -> true
379              | _ -> false)
380            ~where:(CicSubstitution.lift n_lambdas t)
381         in
382         let rec mk_lam = function 
383           | [] -> t 
384           | (ty,n)::tl -> 
385               let name = "fresh_"^ string_of_int n in
386               Cic.Lambda (Cic.Name name, ty, mk_lam tl)
387         in
388          mk_lam 
389           (fst (List.fold_left 
390             (fun (l,liftno) (ty,_)  -> 
391               (l @ [CicSubstitution.lift liftno ty,liftno] , liftno+1))
392             ([],0) map))
393     in
394       t
395   in
396   let ast = print_proof context (close_pt menv context t) in
397   let pp t = 
398     (* ZACK: setting width to 80 will trigger a bug of BoxPp.render_to_string
399      * which will show up using the following command line:
400      * ./tptp2grafite -tptppath ~tassi/TPTP-v3.1.1 GRP170-1 *)
401     let width = max_int in
402     let term_pp content_term =
403       let pres_term = TermContentPres.pp_ast content_term in
404       let dummy_tbl = Hashtbl.create 1 in
405       let markup = CicNotationPres.render dummy_tbl pres_term in
406       let s = "(" ^ BoxPp.render_to_string
407        ~map_unicode_to_tex:(Helm_registry.get_bool
408          "matita.paste_unicode_as_tex")
409        List.hd width markup ^ ")" in
410       Pcre.substitute 
411         ~pat:"\\\\forall [Ha-z][a-z0-9_]*" ~subst:(fun x -> "\n" ^ x) s
412     in
413     CicNotationPp.set_pp_term term_pp;
414     let lazy_term_pp = fun x -> assert false in
415     let obj_pp = CicNotationPp.pp_obj CicNotationPp.pp_term in
416     GrafiteAstPp.pp_statement
417      ~map_unicode_to_tex:(Helm_registry.get_bool
418        "matita.paste_unicode_as_tex")
419      ~term_pp ~lazy_term_pp ~obj_pp t
420   in
421   let script = String.concat "" (List.map pp ast) in
422   prerr_endline script;
423   stupid_indenter script
424 ;;
425
426 let rec eval_macro include_paths (buffer : GText.buffer) guistuff lexicon_status grafite_status user_goal unparsed_text parsed_text script mac =
427   let module TAPp = GrafiteAstPp in
428   let module MQ = MetadataQuery in
429   let module MDB = LibraryDb in
430   let module CTC = CicTypeChecker in
431   let module CU = CicUniv in
432   (* no idea why ocaml wants this *)
433   let parsed_text_length = String.length parsed_text in
434   let dbd = LibraryDb.instance () in
435   let pp_macro = 
436     let f t = ProofEngineReduction.replace 
437       ~equality:(fun _ t -> match t with Cic.Meta _ -> true | _ -> false)
438       ~what:[()] ~with_what:[Cic.Implicit None] ~where:t
439     in
440     let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
441     TAPp.pp_macro 
442       ~term_pp:(fun x -> 
443         ApplyTransformation.txt_of_cic_term max_int metasenv [] (f x)
444          ~map_unicode_to_tex:(Helm_registry.get_bool
445            "matita.paste_unicode_as_tex"))
446   in
447   match mac with
448   (* WHELP's stuff *)
449   | TA.WMatch (loc, term) -> 
450      let l =  Whelp.match_term ~dbd term in
451      let entry = `Whelp (pp_macro mac, l) in
452      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
453      [], "", parsed_text_length
454   | TA.WInstance (loc, term) ->
455      let l = Whelp.instance ~dbd term in
456      let entry = `Whelp (pp_macro mac, l) in
457      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
458      [], "", parsed_text_length
459   | TA.WLocate (loc, s) -> 
460      let l = Whelp.locate ~dbd s in
461      let entry = `Whelp (pp_macro mac, l) in
462      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
463      [], "", parsed_text_length
464   | TA.WElim (loc, term) ->
465      let uri =
466        match term with
467        | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
468        | _ -> failwith "Not a MutInd"
469      in
470      let l = Whelp.elim ~dbd uri in
471      let entry = `Whelp (pp_macro mac, l) in
472      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
473      [], "", parsed_text_length
474   | TA.WHint (loc, term) ->
475      let _subst = [] in
476      let s = ((None,[0,[],term], _subst, Cic.Meta (0,[]) ,term, []),0) in
477      let l = List.map fst (MQ.experimental_hint ~dbd s) in
478      let entry = `Whelp (pp_macro mac, l) in
479      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
480      [], "", parsed_text_length
481   (* REAL macro *)
482   | TA.Hint (loc, rewrite) -> 
483       let user_goal' =
484        match user_goal with
485           Some n -> n
486         | None -> raise NoUnfinishedProof
487       in
488       let proof = GrafiteTypes.get_current_proof grafite_status in
489       let proof_status = proof,user_goal' in
490       if rewrite then
491         let l = MQ.equations_for_goal ~dbd proof_status in
492         let l = List.filter (fun u -> not (LibraryObjects.in_eq_URIs u)) l in
493         let entry = `Whelp (pp_macro (TA.WHint(loc, Cic.Implicit None)), l) in
494         guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
495         [], "", parsed_text_length
496       else
497         let l = List.map fst (MQ.experimental_hint ~dbd proof_status) in
498         let selected = guistuff.urichooser l in
499         (match selected with
500         | [] -> [], "", parsed_text_length
501         | [uri] -> 
502             let suri = UriManager.string_of_uri uri in
503             let ast loc =
504               TA.Executable (loc, (TA.Tactic (loc,
505                Some (TA.Apply (loc, CicNotationPt.Uri (suri, None))),
506                TA.Dot loc))) in
507             let text =
508              comment parsed_text ^ "\n" ^
509               pp_eager_statement_ast (ast HExtlib.dummy_floc)
510               ~map_unicode_to_tex:(Helm_registry.get_bool
511                 "matita.paste_unicode_as_tex")
512             in
513             let text_len = MatitaGtkMisc.utf8_string_length text in
514             let loc = HExtlib.floc_of_loc (0,text_len) in
515             let statement = `Ast (GrafiteParser.LSome (ast loc),text) in
516             let res,_,_parsed_text_len =
517              eval_statement include_paths buffer guistuff lexicon_status
518               grafite_status user_goal script statement
519             in
520              (* we need to replace all the parsed_text *)
521              res,"",String.length parsed_text
522         | _ -> 
523             HLog.error 
524               "The result of the urichooser should be only 1 uri, not:\n";
525             List.iter (
526               fun u -> HLog.error (UriManager.string_of_uri u ^ "\n")
527             ) selected;
528             assert false)
529   | TA.Check (_,term) ->
530       let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
531       let context =
532        match user_goal with
533           None -> []
534         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
535       let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
536       let t_and_ty = Cic.Cast (term,ty) in
537       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
538       [], "", parsed_text_length
539   | TA.AutoInteractive (_, params) ->
540       let user_goal' =
541        match user_goal with
542           Some n -> n
543         | None -> raise NoUnfinishedProof
544       in
545       let proof = GrafiteTypes.get_current_proof grafite_status in
546       let proof_status = proof,user_goal' in
547       (try
548         let _,menv,_,_,_,_ = proof in
549         let i,cc,ty = CicUtil.lookup_meta user_goal' menv in
550         let timestamp = Unix.gettimeofday () in
551         let (_,menv,subst,_,_,_), _ = 
552           ProofEngineTypes.apply_tactic
553             (Auto.auto_tac ~dbd ~params
554               ~universe:grafite_status.GrafiteTypes.universe) proof_status
555         in
556         let proof_term = 
557           let irl = 
558             CicMkImplicit.identity_relocation_list_for_metavariable cc
559           in
560           CicMetaSubst.apply_subst subst (Cic.Meta (i,irl))
561         in
562         let time = Unix.gettimeofday () -. timestamp in
563         let size, depth = Auto.size_and_depth cc menv proof_term in
564         let trailer = 
565           Printf.sprintf 
566             "\n(* end auto(%s) proof: TIME=%4.2f SIZE=%d DEPTH=%d *)"
567             Auto.revision time size depth
568         in
569         let proof_script = 
570           if List.exists (fun (s,_) -> s = "paramodulation") params then
571               let proof_term, how_many_lambdas = 
572                 Auto.lambda_close ~prefix_name:"orrible_hack_" 
573                   proof_term menv cc 
574               in
575               let ty,_ = 
576                 CicTypeChecker.type_of_aux'
577                   menv [] proof_term CicUniv.empty_ugraph
578               in
579               prerr_endline (CicPp.ppterm proof_term);
580               (* use declarative output *)
581               let obj =
582                 (* il proof_term vive in cc, devo metterci i lambda no? *)
583                 (Cic.CurrentProof ("xxx",menv,proof_term,ty,[],[]))
584               in
585                ApplyTransformation.txt_of_cic_object
586                 ~map_unicode_to_tex:(Helm_registry.get_bool
587                   "matita.paste_unicode_as_tex")
588                 ~skip_thm_and_qed:true
589                 ~skip_initial_lambdas:how_many_lambdas
590                 80 GrafiteAst.Declarative "" obj
591           else
592             if true then
593               (* use cic2grafite *)
594               cic2grafite cc menv proof_term 
595             else
596               (* alternative using FG stuff *)
597               let proof_term, how_many_lambdas = 
598                 Auto.lambda_close ~prefix_name:"orrible_hack_" 
599                   proof_term menv cc 
600               in
601               let ty,_ = 
602                 CicTypeChecker.type_of_aux'
603                   menv [] proof_term CicUniv.empty_ugraph
604               in
605               let obj = 
606                 Cic.Constant ("",Some proof_term, ty, [], [`Flavour `Lemma])
607               in
608                 Pcre.qreplace ~templ:"?" ~pat:"orrible_hack_[0-9]+"
609                  (strip_comments
610                   (ApplyTransformation.txt_of_cic_object
611                     ~map_unicode_to_tex:(Helm_registry.get_bool
612                       "matita.paste_unicode_as_tex")
613                     ~skip_thm_and_qed:true
614                     ~skip_initial_lambdas:how_many_lambdas
615                     80 (GrafiteAst.Procedural None) "" obj)) 
616         in
617         let text = comment parsed_text ^ "\n" ^ proof_script ^ trailer in
618         [],text,parsed_text_length
619       with
620         ProofEngineTypes.Fail _ as exn -> 
621           raise exn
622           (* [], comment parsed_text ^ "\nfail.\n", parsed_text_length *))
623   | TA.Inline (_,style,suri,prefix) ->
624        let str = 
625          ApplyTransformation.txt_of_inline_macro
626           ~map_unicode_to_tex:(Helm_registry.get_bool
627             "matita.paste_unicode_as_tex")
628           style suri prefix 
629        in
630        [], str, String.length parsed_text
631                                 
632 and eval_executable include_paths (buffer : GText.buffer) guistuff
633 lexicon_status grafite_status user_goal unparsed_text skipped_txt nonskipped_txt
634 script ex loc
635 =
636  let module TAPp = GrafiteAstPp in
637  let module MD = GrafiteDisambiguator in
638  let module ML = MatitaMisc in
639   try
640    begin
641     match ex with
642      | TA.Command (_,TA.Set (_,"baseuri",u)) ->
643         if  Http_getter_storage.is_read_only u then
644           raise (ActionCancelled ("baseuri " ^ u ^ " is readonly"));
645         if not (Http_getter_storage.is_empty ~local:true u) then
646          (match 
647             guistuff.ask_confirmation 
648               ~title:"Baseuri redefinition" 
649               ~message:(
650                 "Baseuri " ^ u ^ " already exists.\n" ^
651                 "Do you want to redefine the corresponding "^
652                 "part of the library?")
653           with
654            | `YES -> LibraryClean.clean_baseuris [u]
655            | `NO -> ()
656            | `CANCEL -> raise MatitaTypes.Cancel)
657      | _ -> ()
658    end;
659    ignore (buffer#move_mark (`NAME "beginning_of_statement")
660     ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
661        (Glib.Utf8.length skipped_txt))) ;
662    eval_with_engine
663     guistuff lexicon_status grafite_status user_goal skipped_txt nonskipped_txt
664      (TA.Executable (loc, ex))
665   with
666      MatitaTypes.Cancel -> [], "", 0
667    | GrafiteEngine.Macro (_loc,lazy_macro) ->
668       let context =
669        match user_goal with
670           None -> []
671         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
672       let grafite_status,macro = lazy_macro context in
673        eval_macro include_paths buffer guistuff lexicon_status grafite_status
674         user_goal unparsed_text (skipped_txt ^ nonskipped_txt) script macro
675
676 and eval_statement include_paths (buffer : GText.buffer) guistuff lexicon_status
677  grafite_status user_goal script statement
678 =
679   let (lexicon_status,st), unparsed_text =
680     match statement with
681     | `Raw text ->
682         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
683         let ast = 
684           wrap_with_developments guistuff
685             (GrafiteParser.parse_statement 
686               (Ulexing.from_utf8_string text) ~include_paths) lexicon_status 
687         in
688           ast, text
689     | `Ast (st, text) -> (lexicon_status, st), text
690   in
691   let text_of_loc floc = 
692     let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
693     let start, stop = HExtlib.loc_of_floc floc in 
694     let floc = HExtlib.floc_of_loc (0, start) in
695     let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
696     let floc = HExtlib.floc_of_loc (0, stop) in
697     let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
698     txt,nonskipped_txt,skipped_txt,len
699   in 
700   match st with
701   | GrafiteParser.LNone loc ->
702       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
703        [(grafite_status,lexicon_status),parsed_text],"",
704         parsed_text_length
705   | GrafiteParser.LSome (GrafiteAst.Comment (loc, _)) -> 
706       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
707       let remain_len = String.length unparsed_text - parsed_text_length in
708       let s = String.sub unparsed_text parsed_text_length remain_len in
709       let s,text,len = 
710        try
711         eval_statement include_paths buffer guistuff lexicon_status
712          grafite_status user_goal script (`Raw s)
713        with
714           HExtlib.Localized (floc, exn) ->
715            HExtlib.raise_localized_exception 
716              ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
717         | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
718            raise
719             (GrafiteDisambiguator.DisambiguationError
720               (offset+parsed_text_length, errorll))
721       in
722       assert (text=""); (* no macros inside comments, please! *)
723       (match s with
724       | (statuses,text)::tl ->
725          (statuses,parsed_text ^ text)::tl,"",parsed_text_length + len
726       | [] -> [], "", 0)
727   | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) ->
728      let _, nonskipped, skipped, parsed_text_length = 
729        text_of_loc loc 
730      in
731       eval_executable include_paths buffer guistuff lexicon_status
732        grafite_status user_goal unparsed_text skipped nonskipped script ex loc
733   
734 let fresh_script_id =
735   let i = ref 0 in
736   fun () -> incr i; !i
737
738 class script  ~(source_view: GSourceView.source_view)
739               ~(mathviewer: MatitaTypes.mathViewer) 
740               ~set_star
741               ~ask_confirmation
742               ~urichooser 
743               ~develcreator 
744               () =
745 let buffer = source_view#buffer in
746 let source_buffer = source_view#source_buffer in
747 let initial_statuses () =
748  (* these include_paths are used only to load the initial notation *)
749  let include_paths =
750   Helm_registry.get_list Helm_registry.string "matita.includes" in
751  let lexicon_status =
752   CicNotation2.load_notation ~include_paths
753    BuildTimeConf.core_notation_script in
754  let grafite_status = GrafiteSync.init () in
755   grafite_status,lexicon_status
756 in
757 object (self)
758   val mutable include_paths =
759    Helm_registry.get_list Helm_registry.string "matita.includes"
760
761   val scriptId = fresh_script_id ()
762   
763   val guistuff = {
764     mathviewer = mathviewer;
765     urichooser = urichooser;
766     ask_confirmation = ask_confirmation;
767     develcreator = develcreator;
768     filenamedata = (None, None)} 
769   
770   method private getFilename =
771     match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
772
773   method filename = self#getFilename
774     
775   method private ppFilename =
776     match guistuff.filenamedata with 
777     | Some f,_ -> f 
778     | None,_ -> sprintf ".unnamed%d.ma" scriptId
779   
780   initializer 
781     ignore (GMain.Timeout.add ~ms:300000 
782        ~callback:(fun _ -> self#_saveToBackupFile ();true));
783     ignore (buffer#connect#modified_changed 
784       (fun _ -> set_star (Filename.basename self#ppFilename) buffer#modified))
785
786   val mutable statements = []    (** executed statements *)
787
788   val mutable history = [ initial_statuses () ]
789     (** list of states before having executed statements. Head element of this
790       * list is the current state, last element is the state at the beginning of
791       * the script.
792       * Invariant: this list length is 1 + length of statements *)
793
794   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
795   val mutable userGoal = None
796
797   (** text mark and tag representing locked part of a script *)
798   val locked_mark =
799     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
800   val beginning_of_statement_mark =
801     buffer#create_mark ~name:"beginning_of_statement"
802      ~left_gravity:true buffer#start_iter
803   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
804   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
805
806   method locked_mark = locked_mark
807   method locked_tag = locked_tag
808   method error_tag = error_tag
809
810     (* history can't be empty, the invariant above grant that it contains at
811      * least the init grafite_status *)
812   method grafite_status = match history with (s,_)::_ -> s | _ -> assert false
813   method lexicon_status = match history with (_,ss)::_ -> ss | _ -> assert false
814
815   method private _advance ?statement () =
816    let s = match statement with Some s -> s | None -> self#getFuture in
817    HLog.debug ("evaluating: " ^ first_line s ^ " ...");
818    let entries, newtext, parsed_len = 
819     try
820      eval_statement include_paths buffer guistuff self#lexicon_status
821       self#grafite_status userGoal self (`Raw s)
822     with End_of_file -> raise Margin
823    in
824    let new_statuses, new_statements =
825      let statuses, texts = List.split entries in
826      statuses, texts
827    in
828    history <- new_statuses @ history;
829    statements <- new_statements @ statements;
830    let start = buffer#get_iter_at_mark (`MARK locked_mark) in
831    let new_text = String.concat "" (List.rev new_statements) in
832    if statement <> None then
833      buffer#insert ~iter:start new_text
834    else begin
835      let parsed_text = String.sub s 0 parsed_len in
836      if new_text <> parsed_text then begin
837        let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
838        buffer#delete ~start ~stop;
839        buffer#insert ~iter:start new_text;
840      end;
841    end;
842    self#moveMark (Glib.Utf8.length new_text);
843    buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext;
844    (* here we need to set the Goal in case we are going to cursor (or to
845       bottom) and we will face a macro *)
846    match self#grafite_status.proof_status with
847       Incomplete_proof p ->
848        userGoal <-
849          (try Some (Continuationals.Stack.find_goal p.stack)
850          with Failure _ -> None)
851     | _ -> userGoal <- None
852
853   method private _retract offset lexicon_status grafite_status new_statements
854    new_history
855   =
856    let cur_grafite_status,cur_lexicon_status =
857     match history with s::_ -> s | [] -> assert false
858    in
859     LexiconSync.time_travel ~present:cur_lexicon_status ~past:lexicon_status;
860     GrafiteSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
861     statements <- new_statements;
862     history <- new_history;
863     self#moveMark (- offset)
864
865   method advance ?statement () =
866     try
867       self#_advance ?statement ();
868       self#notify
869     with 
870     | Margin -> self#notify
871     | Not_found -> assert false
872     | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
873     | exc -> self#notify; raise exc
874
875   method retract () =
876     try
877       let cmp,new_statements,new_history,(grafite_status,lexicon_status) =
878        match statements,history with
879           stat::statements, _::(status::_ as history) ->
880            assert (Glib.Utf8.validate stat);
881            Glib.Utf8.length stat, statements, history, status
882        | [],[_] -> raise Margin
883        | _,_ -> assert false
884       in
885        self#_retract cmp lexicon_status grafite_status new_statements
886         new_history;
887        self#notify
888     with 
889     | Margin -> self#notify
890     | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
891     | exc -> self#notify; raise exc
892
893   method private getFuture =
894     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
895       ~stop:buffer#end_iter ()
896
897       
898   (** @param rel_offset relative offset from current position of locked_mark *)
899   method private moveMark rel_offset =
900     let mark = `MARK locked_mark in
901     let old_insert = buffer#get_iter_at_mark `INSERT in
902     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
903     let current_mark_pos = buffer#get_iter_at_mark mark in
904     let new_mark_pos =
905       match rel_offset with
906       | 0 -> current_mark_pos
907       | n when n > 0 -> current_mark_pos#forward_chars n
908       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
909     in
910     buffer#move_mark mark ~where:new_mark_pos;
911     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
912     buffer#move_mark `INSERT old_insert;
913     let mark_position = buffer#get_iter_at_mark mark in
914     if source_view#move_mark_onscreen mark then
915      begin
916       buffer#move_mark mark mark_position;
917       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
918      end;
919     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
920
921   method clean_dirty_lock =
922     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
923     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
924     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
925
926   val mutable observers = []
927
928   method addObserver (o: LexiconEngine.status -> GrafiteTypes.status -> unit) =
929     observers <- o :: observers
930
931   method private notify =
932     let lexicon_status = self#lexicon_status in
933     let grafite_status = self#grafite_status in
934     List.iter (fun o -> o lexicon_status grafite_status) observers
935
936   method loadFromString s =
937     buffer#set_text s;
938     self#reset_buffer;
939     buffer#set_modified true
940
941   method loadFromFile f =
942     buffer#set_text (HExtlib.input_file f);
943     self#reset_buffer;
944     buffer#set_modified false
945     
946   method assignFileName file =
947     let abspath = MatitaMisc.absolute_path file in
948     let dirname = Filename.dirname abspath in
949     let devel = MatitamakeLib.development_for_dir dirname in
950     guistuff.filenamedata <- Some abspath, devel;
951     let include_ = 
952      match MatitamakeLib.development_for_dir dirname with
953         None -> []
954       | Some devel -> [MatitamakeLib.root_for_development devel] in
955     let include_ =
956      include_ @ (Helm_registry.get_list Helm_registry.string "matita.includes")
957     in
958      include_paths <- include_
959     
960   method saveToFile () =
961     let oc = open_out self#getFilename in
962     output_string oc (buffer#get_text ~start:buffer#start_iter
963                         ~stop:buffer#end_iter ());
964     close_out oc;
965     buffer#set_modified false
966   
967   method private _saveToBackupFile () =
968     if buffer#modified then
969       begin
970         let f = self#ppFilename ^ "~" in
971         let oc = open_out f in
972         output_string oc (buffer#get_text ~start:buffer#start_iter
973                             ~stop:buffer#end_iter ());
974         close_out oc;
975         HLog.debug ("backup " ^ f ^ " saved")                    
976       end
977   
978   method private goto_top =
979     let grafite_status,lexicon_status = 
980       let rec last x = function 
981       | [] -> x
982       | hd::tl -> last hd tl
983       in
984       last (self#grafite_status,self#lexicon_status) history
985     in
986     (* FIXME: this is not correct since there is no undo for 
987      * library_objects.set_default... *)
988     GrafiteSync.time_travel ~present:self#grafite_status ~past:grafite_status;
989     LexiconSync.time_travel ~present:self#lexicon_status ~past:lexicon_status
990
991   method private reset_buffer = 
992     statements <- [];
993     history <- [ initial_statuses () ];
994     userGoal <- None;
995     self#notify;
996     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
997     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
998
999   method reset () =
1000     self#reset_buffer;
1001     source_buffer#begin_not_undoable_action ();
1002     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
1003     source_buffer#end_not_undoable_action ();
1004     buffer#set_modified false;
1005   
1006   method template () =
1007     let template = HExtlib.input_file BuildTimeConf.script_template in 
1008     buffer#insert ~iter:(buffer#get_iter `START) template;
1009     let development = MatitamakeLib.development_for_dir (Unix.getcwd ()) in
1010     guistuff.filenamedata <- (None,development);
1011     let include_ = 
1012      match development with
1013         None -> []
1014       | Some devel -> [MatitamakeLib.root_for_development devel ]
1015     in
1016     let include_ =
1017      include_ @ (Helm_registry.get_list Helm_registry.string "matita.includes")
1018     in
1019      include_paths <- include_ ;
1020      buffer#set_modified false;
1021      set_star (Filename.basename self#ppFilename) false
1022
1023   method goto (pos: [`Top | `Bottom | `Cursor]) () =
1024   try  
1025     let old_locked_mark =
1026      `MARK
1027        (buffer#create_mark ~name:"old_locked_mark"
1028          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
1029     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
1030     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
1031     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
1032     match pos with
1033     | `Top -> 
1034         dispose_old_locked_mark (); 
1035         self#goto_top; 
1036         self#reset_buffer;
1037         self#notify
1038     | `Bottom ->
1039         (try 
1040           let rec dowhile () =
1041             self#_advance ();
1042             let newpos = getpos () in
1043             if (getoldpos ())#compare newpos < 0 then
1044               begin
1045                 buffer#move_mark old_locked_mark newpos;
1046                 dowhile ()
1047               end
1048           in
1049           dowhile ();
1050           dispose_old_locked_mark ();
1051           self#notify 
1052         with 
1053         | Margin -> dispose_old_locked_mark (); self#notify
1054         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
1055     | `Cursor ->
1056         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
1057         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
1058         let remember =
1059          `MARK
1060            (buffer#create_mark ~name:"initial_insert"
1061              ~left_gravity:true (cursor_iter ())) in
1062         let dispose_remember () = buffer#delete_mark remember in
1063         let remember_iter () =
1064          buffer#get_iter_at_mark (`NAME "initial_insert") in
1065         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
1066         let icmp = cmp () in
1067         let forward_until_cursor () = (* go forward until locked > cursor *)
1068           let rec aux () =
1069             self#_advance ();
1070             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
1071             then
1072              begin
1073               buffer#move_mark old_locked_mark (getpos ());
1074               aux ()
1075              end
1076           in
1077           aux ()
1078         in
1079         let rec back_until_cursor len = (* go backward until locked < cursor *)
1080          function
1081             statements, ((grafite_status,lexicon_status)::_ as history)
1082             when len <= 0 ->
1083              self#_retract (icmp - len) lexicon_status grafite_status statements
1084               history
1085           | statement::tl1, _::tl2 ->
1086              back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
1087           | _,_ -> assert false
1088         in
1089         (try
1090           begin
1091            if icmp < 0 then       (* locked < cursor *)
1092              (forward_until_cursor (); self#notify)
1093            else if icmp > 0 then  (* locked > cursor *)
1094              (back_until_cursor icmp (statements,history); self#notify)
1095            else                  (* cursor = locked *)
1096                ()
1097           end ;
1098           dispose_remember ();
1099           dispose_old_locked_mark ();
1100         with 
1101         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
1102         | exc -> dispose_remember (); dispose_old_locked_mark ();
1103                  self#notify; raise exc)
1104   with Invalid_argument "Array.make" ->
1105      HLog.error "The script is too big!\n"
1106   
1107   method onGoingProof () =
1108     match self#grafite_status.proof_status with
1109     | No_proof | Proof _ -> false
1110     | Incomplete_proof _ -> true
1111     | Intermediate _ -> assert false
1112
1113 (*   method proofStatus = MatitaTypes.get_proof_status self#status *)
1114   method proofMetasenv = GrafiteTypes.get_proof_metasenv self#grafite_status
1115
1116   method proofContext =
1117    match userGoal with
1118       None -> []
1119     | Some n -> GrafiteTypes.get_proof_context self#grafite_status n
1120
1121   method proofConclusion =
1122    match userGoal with
1123       None -> assert false
1124     | Some n ->
1125        GrafiteTypes.get_proof_conclusion self#grafite_status n
1126
1127   method stack = GrafiteTypes.get_stack self#grafite_status
1128   method setGoal n = userGoal <- n
1129   method goal = userGoal
1130
1131   method eos = 
1132     let rec is_there_only_comments lexicon_status s = 
1133       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
1134       let lexicon_status,st =
1135        GrafiteParser.parse_statement (Ulexing.from_utf8_string s)
1136         ~include_paths lexicon_status
1137       in
1138       match st with
1139       | GrafiteParser.LSome (GrafiteAst.Comment (loc,_)) -> 
1140           let _,parsed_text_length = MatitaGtkMisc.utf8_parsed_text s loc in
1141           (* CSC: why +1 in the following lines ???? *)
1142           let parsed_text_length = parsed_text_length + 1 in
1143 prerr_endline ("## " ^ string_of_int parsed_text_length);
1144           let remain_len = String.length s - parsed_text_length in
1145           let next = String.sub s parsed_text_length remain_len in
1146           is_there_only_comments lexicon_status next
1147       | GrafiteParser.LNone _
1148       | GrafiteParser.LSome (GrafiteAst.Executable _) -> false
1149     in
1150     try
1151       is_there_only_comments self#lexicon_status self#getFuture
1152     with 
1153     | LexiconEngine.IncludedFileNotCompiled _
1154     | HExtlib.Localized _
1155     | CicNotationParser.Parse_error _ -> false
1156     | Margin | End_of_file -> true
1157     | Invalid_argument "Array.make" -> false
1158
1159   (* debug *)
1160   method dump () =
1161     HLog.debug "script status:";
1162     HLog.debug ("history size: " ^ string_of_int (List.length history));
1163     HLog.debug (sprintf "%d statements:" (List.length statements));
1164     List.iter HLog.debug statements;
1165     HLog.debug ("Current file name: " ^
1166       (match guistuff.filenamedata with 
1167       |None,_ -> "[ no name ]" 
1168       | Some f,_ -> f));
1169
1170 end
1171
1172 let _script = ref None
1173
1174 let script ~source_view ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
1175 =
1176   let s = new script 
1177     ~source_view ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
1178   in
1179   _script := Some s;
1180   s
1181
1182 let current () = match !_script with None -> assert false | Some s -> s
1183