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