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