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