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