]> matita.cs.unibo.it Git - helm.git/blob - matita/matitaScript.ml
Much ado about nothing:
[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 s = ((None,[0,[],term], Cic.Meta (0,[]) ,term, []),0) in
230      let l = List.map fst (MQ.experimental_hint ~dbd s) in
231      let entry = `Whelp (pp_macro mac, l) in
232      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
233      [], "", parsed_text_length
234   (* REAL macro *)
235   | TA.Hint loc -> 
236       let user_goal' =
237        match user_goal with
238           Some n -> n
239         | None -> raise NoUnfinishedProof
240       in
241       let proof = GrafiteTypes.get_current_proof grafite_status in
242       let proof_status = proof,user_goal' in
243       let l = List.map fst (MQ.experimental_hint ~dbd proof_status) in
244       let selected = guistuff.urichooser l in
245       (match selected with
246       | [] -> [], "", parsed_text_length
247       | [uri] -> 
248           let suri = UriManager.string_of_uri uri in
249           let ast loc =
250             TA.Executable (loc, (TA.Tactic (loc,
251              Some (TA.Apply (loc, CicNotationPt.Uri (suri, None))),
252              TA.Dot loc))) in
253           let text =
254            comment parsed_text ^ "\n" ^
255             pp_eager_statement_ast (ast HExtlib.dummy_floc) in
256           let text_len = MatitaGtkMisc.utf8_string_length text in
257           let loc = HExtlib.floc_of_loc (0,text_len) in
258           let statement = `Ast (GrafiteParser.LSome (ast loc),text) in
259           let res,_,_parsed_text_len =
260            eval_statement include_paths buffer guistuff lexicon_status
261             grafite_status user_goal script statement
262           in
263            (* we need to replace all the parsed_text *)
264            res,"",String.length parsed_text
265       | _ -> 
266           HLog.error 
267             "The result of the urichooser should be only 1 uri, not:\n";
268           List.iter (
269             fun u -> HLog.error (UriManager.string_of_uri u ^ "\n")
270           ) selected;
271           assert false)
272   | TA.Check (_,term) ->
273       let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
274       let context =
275        match user_goal with
276           None -> []
277         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
278       let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
279       let t_and_ty = Cic.Cast (term,ty) in
280       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
281       [], "", parsed_text_length
282   | TA.Inline (_,style,suri,prefix) ->
283        let str = ApplyTransformation.txt_of_inline_macro style suri prefix in
284        [], str, String.length parsed_text
285                                 
286 and eval_executable include_paths (buffer : GText.buffer) guistuff
287 lexicon_status grafite_status user_goal unparsed_text skipped_txt nonskipped_txt
288 script ex loc
289 =
290  let module TAPp = GrafiteAstPp in
291  let module MD = GrafiteDisambiguator in
292  let module ML = MatitaMisc in
293   try
294    begin
295     match ex with
296      | TA.Command (_,TA.Set (_,"baseuri",u)) ->
297         if  Http_getter_storage.is_read_only u then
298           raise (ActionCancelled ("baseuri " ^ u ^ " is readonly"));
299         if not (Http_getter_storage.is_empty u) then
300          (match 
301             guistuff.ask_confirmation 
302               ~title:"Baseuri redefinition" 
303               ~message:(
304                 "Baseuri " ^ u ^ " already exists.\n" ^
305                 "Do you want to redefine the corresponding "^
306                 "part of the library?")
307           with
308            | `YES -> LibraryClean.clean_baseuris [u]
309            | `NO -> ()
310            | `CANCEL -> raise MatitaTypes.Cancel)
311      | _ -> ()
312    end;
313    ignore (buffer#move_mark (`NAME "beginning_of_statement")
314     ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
315        (Glib.Utf8.length skipped_txt))) ;
316    eval_with_engine
317     guistuff lexicon_status grafite_status user_goal skipped_txt nonskipped_txt
318      (TA.Executable (loc, ex))
319   with
320      MatitaTypes.Cancel -> [], "", 0
321    | GrafiteEngine.Macro (_loc,lazy_macro) ->
322       let context =
323        match user_goal with
324           None -> []
325         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
326       let grafite_status,macro = lazy_macro context in
327        eval_macro include_paths buffer guistuff lexicon_status grafite_status
328         user_goal unparsed_text (skipped_txt ^ nonskipped_txt) script macro
329
330 and eval_statement include_paths (buffer : GText.buffer) guistuff lexicon_status
331  grafite_status user_goal script statement
332 =
333   let (lexicon_status,st), unparsed_text =
334     match statement with
335     | `Raw text ->
336         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
337         let ast = 
338           wrap_with_developments guistuff
339             (GrafiteParser.parse_statement 
340               (Ulexing.from_utf8_string text) ~include_paths) lexicon_status 
341         in
342           ast, text
343     | `Ast (st, text) -> (lexicon_status, st), text
344   in
345   let text_of_loc floc = 
346     let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
347     let start, stop = HExtlib.loc_of_floc floc in 
348     let floc = HExtlib.floc_of_loc (0, start) in
349     let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
350     let floc = HExtlib.floc_of_loc (0, stop) in
351     let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
352     txt,nonskipped_txt,skipped_txt,len
353   in 
354   match st with
355   | GrafiteParser.LNone loc ->
356       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
357        [(grafite_status,lexicon_status),parsed_text],"",
358         parsed_text_length
359   | GrafiteParser.LSome (GrafiteAst.Comment (loc, _)) -> 
360       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
361       let remain_len = String.length unparsed_text - parsed_text_length in
362       let s = String.sub unparsed_text parsed_text_length remain_len in
363       let s,text,len = 
364        try
365         eval_statement include_paths buffer guistuff lexicon_status
366          grafite_status user_goal script (`Raw s)
367        with
368           HExtlib.Localized (floc, exn) ->
369            HExtlib.raise_localized_exception 
370              ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
371         | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
372            raise
373             (GrafiteDisambiguator.DisambiguationError
374               (offset+parsed_text_length, errorll))
375       in
376       assert (text=""); (* no macros inside comments, please! *)
377       (match s with
378       | (statuses,text)::tl ->
379          (statuses,parsed_text ^ text)::tl,"",parsed_text_length + len
380       | [] -> [], "", 0)
381   | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) ->
382      let _, nonskipped, skipped, parsed_text_length = 
383        text_of_loc loc 
384      in
385       eval_executable include_paths buffer guistuff lexicon_status
386        grafite_status user_goal unparsed_text skipped nonskipped script ex loc
387   
388 let fresh_script_id =
389   let i = ref 0 in
390   fun () -> incr i; !i
391
392 class script  ~(source_view: GSourceView.source_view)
393               ~(mathviewer: MatitaTypes.mathViewer) 
394               ~set_star
395               ~ask_confirmation
396               ~urichooser 
397               ~develcreator 
398               () =
399 let buffer = source_view#buffer in
400 let source_buffer = source_view#source_buffer in
401 let initial_statuses () =
402  (* these include_paths are used only to load the initial notation *)
403  let include_paths =
404   Helm_registry.get_list Helm_registry.string "matita.includes" in
405  let lexicon_status =
406   CicNotation2.load_notation ~include_paths
407    BuildTimeConf.core_notation_script in
408  let grafite_status = GrafiteSync.init () in
409   grafite_status,lexicon_status
410 in
411 object (self)
412   val mutable include_paths =
413    Helm_registry.get_list Helm_registry.string "matita.includes"
414
415   val scriptId = fresh_script_id ()
416   
417   val guistuff = {
418     mathviewer = mathviewer;
419     urichooser = urichooser;
420     ask_confirmation = ask_confirmation;
421     develcreator = develcreator;
422     filenamedata = (None, None)} 
423   
424   method private getFilename =
425     match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
426
427   method filename = self#getFilename
428     
429   method private ppFilename =
430     match guistuff.filenamedata with 
431     | Some f,_ -> f 
432     | None,_ -> sprintf ".unnamed%d.ma" scriptId
433   
434   initializer 
435     ignore (GMain.Timeout.add ~ms:300000 
436        ~callback:(fun _ -> self#_saveToBackupFile ();true));
437     ignore (buffer#connect#modified_changed 
438       (fun _ -> set_star (Filename.basename self#ppFilename) buffer#modified))
439
440   val mutable statements = []    (** executed statements *)
441
442   val mutable history = [ initial_statuses () ]
443     (** list of states before having executed statements. Head element of this
444       * list is the current state, last element is the state at the beginning of
445       * the script.
446       * Invariant: this list length is 1 + length of statements *)
447
448   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
449   val mutable userGoal = None
450
451   (** text mark and tag representing locked part of a script *)
452   val locked_mark =
453     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
454   val beginning_of_statement_mark =
455     buffer#create_mark ~name:"beginning_of_statement"
456      ~left_gravity:true buffer#start_iter
457   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
458   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
459
460   method locked_mark = locked_mark
461   method locked_tag = locked_tag
462   method error_tag = error_tag
463
464     (* history can't be empty, the invariant above grant that it contains at
465      * least the init grafite_status *)
466   method grafite_status = match history with (s,_)::_ -> s | _ -> assert false
467   method lexicon_status = match history with (_,ss)::_ -> ss | _ -> assert false
468
469   method private _advance ?statement () =
470    let s = match statement with Some s -> s | None -> self#getFuture in
471    HLog.debug ("evaluating: " ^ first_line s ^ " ...");
472    let entries, newtext, parsed_len = 
473     try
474      eval_statement include_paths buffer guistuff self#lexicon_status
475       self#grafite_status userGoal self (`Raw s)
476     with End_of_file -> raise Margin
477    in
478    let new_statuses, new_statements =
479      let statuses, texts = List.split entries in
480      statuses, texts
481    in
482    history <- new_statuses @ history;
483    statements <- new_statements @ statements;
484    let start = buffer#get_iter_at_mark (`MARK locked_mark) in
485    let new_text = String.concat "" (List.rev new_statements) in
486    if statement <> None then
487      buffer#insert ~iter:start new_text
488    else begin
489      let parsed_text = String.sub s 0 parsed_len in
490      if new_text <> parsed_text then begin
491        let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
492        buffer#delete ~start ~stop;
493        buffer#insert ~iter:start new_text;
494      end;
495    end;
496    self#moveMark (Glib.Utf8.length new_text);
497    buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext;
498    (* here we need to set the Goal in case we are going to cursor (or to
499       bottom) and we will face a macro *)
500    match self#grafite_status.proof_status with
501       Incomplete_proof p ->
502        userGoal <-
503          (try Some (Continuationals.Stack.find_goal p.stack)
504          with Failure _ -> None)
505     | _ -> userGoal <- None
506
507   method private _retract offset lexicon_status grafite_status new_statements
508    new_history
509   =
510    let cur_grafite_status,cur_lexicon_status =
511     match history with s::_ -> s | [] -> assert false
512    in
513     LexiconSync.time_travel ~present:cur_lexicon_status ~past:lexicon_status;
514     GrafiteSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
515     statements <- new_statements;
516     history <- new_history;
517     self#moveMark (- offset)
518
519   method advance ?statement () =
520     try
521       self#_advance ?statement ();
522       self#notify
523     with 
524     | Margin -> self#notify
525     | Not_found -> assert false
526     | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
527     | exc -> self#notify; raise exc
528
529   method retract () =
530     try
531       let cmp,new_statements,new_history,(grafite_status,lexicon_status) =
532        match statements,history with
533           stat::statements, _::(status::_ as history) ->
534            assert (Glib.Utf8.validate stat);
535            Glib.Utf8.length stat, statements, history, status
536        | [],[_] -> raise Margin
537        | _,_ -> assert false
538       in
539        self#_retract cmp lexicon_status grafite_status new_statements
540         new_history;
541        self#notify
542     with 
543     | Margin -> self#notify
544     | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
545     | exc -> self#notify; raise exc
546
547   method private getFuture =
548     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
549       ~stop:buffer#end_iter ()
550
551       
552   (** @param rel_offset relative offset from current position of locked_mark *)
553   method private moveMark rel_offset =
554     let mark = `MARK locked_mark in
555     let old_insert = buffer#get_iter_at_mark `INSERT in
556     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
557     let current_mark_pos = buffer#get_iter_at_mark mark in
558     let new_mark_pos =
559       match rel_offset with
560       | 0 -> current_mark_pos
561       | n when n > 0 -> current_mark_pos#forward_chars n
562       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
563     in
564     buffer#move_mark mark ~where:new_mark_pos;
565     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
566     buffer#move_mark `INSERT old_insert;
567     let mark_position = buffer#get_iter_at_mark mark in
568     if source_view#move_mark_onscreen mark then
569      begin
570       buffer#move_mark mark mark_position;
571       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
572      end;
573     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
574
575   method clean_dirty_lock =
576     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
577     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
578     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
579
580   val mutable observers = []
581
582   method addObserver (o: LexiconEngine.status -> GrafiteTypes.status -> unit) =
583     observers <- o :: observers
584
585   method private notify =
586     let lexicon_status = self#lexicon_status in
587     let grafite_status = self#grafite_status in
588     List.iter (fun o -> o lexicon_status grafite_status) observers
589
590   method loadFromString s =
591     buffer#set_text s;
592     self#reset_buffer;
593     buffer#set_modified true
594
595   method loadFromFile f =
596     buffer#set_text (HExtlib.input_file f);
597     self#reset_buffer;
598     buffer#set_modified false
599     
600   method assignFileName file =
601     let abspath = MatitaMisc.absolute_path file in
602     let dirname = Filename.dirname abspath in
603     let devel = MatitamakeLib.development_for_dir dirname in
604     guistuff.filenamedata <- Some abspath, devel;
605     let include_ = 
606      match MatitamakeLib.development_for_dir dirname with
607         None -> []
608       | Some devel -> [MatitamakeLib.root_for_development devel] in
609     let include_ =
610      include_ @ (Helm_registry.get_list Helm_registry.string "matita.includes")
611     in
612      include_paths <- include_
613     
614   method saveToFile () =
615     let oc = open_out self#getFilename in
616     output_string oc (buffer#get_text ~start:buffer#start_iter
617                         ~stop:buffer#end_iter ());
618     close_out oc;
619     buffer#set_modified false
620   
621   method private _saveToBackupFile () =
622     if buffer#modified then
623       begin
624         let f = self#ppFilename ^ "~" in
625         let oc = open_out f in
626         output_string oc (buffer#get_text ~start:buffer#start_iter
627                             ~stop:buffer#end_iter ());
628         close_out oc;
629         HLog.debug ("backup " ^ f ^ " saved")                    
630       end
631   
632   method private goto_top =
633     let grafite_status,lexicon_status = 
634       let rec last x = function 
635       | [] -> x
636       | hd::tl -> last hd tl
637       in
638       last (self#grafite_status,self#lexicon_status) history
639     in
640     (* FIXME: this is not correct since there is no undo for 
641      * library_objects.set_default... *)
642     GrafiteSync.time_travel ~present:self#grafite_status ~past:grafite_status;
643     LexiconSync.time_travel ~present:self#lexicon_status ~past:lexicon_status
644
645   method private reset_buffer = 
646     statements <- [];
647     history <- [ initial_statuses () ];
648     userGoal <- None;
649     self#notify;
650     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
651     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
652
653   method reset () =
654     self#reset_buffer;
655     source_buffer#begin_not_undoable_action ();
656     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
657     source_buffer#end_not_undoable_action ();
658     buffer#set_modified false;
659   
660   method template () =
661     let template = HExtlib.input_file BuildTimeConf.script_template in 
662     buffer#insert ~iter:(buffer#get_iter `START) template;
663     let development = MatitamakeLib.development_for_dir (Unix.getcwd ()) in
664     guistuff.filenamedata <- (None,development);
665     let include_ = 
666      match development with
667         None -> []
668       | Some devel -> [MatitamakeLib.root_for_development devel ]
669     in
670     let include_ =
671      include_ @ (Helm_registry.get_list Helm_registry.string "matita.includes")
672     in
673      include_paths <- include_ ;
674      buffer#set_modified false;
675      set_star (Filename.basename self#ppFilename) false
676
677   method goto (pos: [`Top | `Bottom | `Cursor]) () =
678   try  
679     let old_locked_mark =
680      `MARK
681        (buffer#create_mark ~name:"old_locked_mark"
682          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
683     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
684     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
685     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
686     match pos with
687     | `Top -> 
688         dispose_old_locked_mark (); 
689         self#goto_top; 
690         self#reset_buffer;
691         self#notify
692     | `Bottom ->
693         (try 
694           let rec dowhile () =
695             self#_advance ();
696             let newpos = getpos () in
697             if (getoldpos ())#compare newpos < 0 then
698               begin
699                 buffer#move_mark old_locked_mark newpos;
700                 dowhile ()
701               end
702           in
703           dowhile ();
704           dispose_old_locked_mark ();
705           self#notify 
706         with 
707         | Margin -> dispose_old_locked_mark (); self#notify
708         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
709     | `Cursor ->
710         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
711         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
712         let remember =
713          `MARK
714            (buffer#create_mark ~name:"initial_insert"
715              ~left_gravity:true (cursor_iter ())) in
716         let dispose_remember () = buffer#delete_mark remember in
717         let remember_iter () =
718          buffer#get_iter_at_mark (`NAME "initial_insert") in
719         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
720         let icmp = cmp () in
721         let forward_until_cursor () = (* go forward until locked > cursor *)
722           let rec aux () =
723             self#_advance ();
724             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
725             then
726              begin
727               buffer#move_mark old_locked_mark (getpos ());
728               aux ()
729              end
730           in
731           aux ()
732         in
733         let rec back_until_cursor len = (* go backward until locked < cursor *)
734          function
735             statements, ((grafite_status,lexicon_status)::_ as history)
736             when len <= 0 ->
737              self#_retract (icmp - len) lexicon_status grafite_status statements
738               history
739           | statement::tl1, _::tl2 ->
740              back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
741           | _,_ -> assert false
742         in
743         (try
744           begin
745            if icmp < 0 then       (* locked < cursor *)
746              (forward_until_cursor (); self#notify)
747            else if icmp > 0 then  (* locked > cursor *)
748              (back_until_cursor icmp (statements,history); self#notify)
749            else                  (* cursor = locked *)
750                ()
751           end ;
752           dispose_remember ();
753           dispose_old_locked_mark ();
754         with 
755         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
756         | exc -> dispose_remember (); dispose_old_locked_mark ();
757                  self#notify; raise exc)
758   with Invalid_argument "Array.make" ->
759      HLog.error "The script is too big!\n"
760   
761   method onGoingProof () =
762     match self#grafite_status.proof_status with
763     | No_proof | Proof _ -> false
764     | Incomplete_proof _ -> true
765     | Intermediate _ -> assert false
766
767 (*   method proofStatus = MatitaTypes.get_proof_status self#status *)
768   method proofMetasenv = GrafiteTypes.get_proof_metasenv self#grafite_status
769
770   method proofContext =
771    match userGoal with
772       None -> []
773     | Some n -> GrafiteTypes.get_proof_context self#grafite_status n
774
775   method proofConclusion =
776    match userGoal with
777       None -> assert false
778     | Some n ->
779        GrafiteTypes.get_proof_conclusion self#grafite_status n
780
781   method stack = GrafiteTypes.get_stack self#grafite_status
782   method setGoal n = userGoal <- n
783   method goal = userGoal
784
785   method eos = 
786     let rec is_there_only_comments lexicon_status s = 
787       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
788       let lexicon_status,st =
789        GrafiteParser.parse_statement (Ulexing.from_utf8_string s)
790         ~include_paths lexicon_status
791       in
792       match st with
793       | GrafiteParser.LSome (GrafiteAst.Comment (loc,_)) -> 
794           let _,parsed_text_length = MatitaGtkMisc.utf8_parsed_text s loc in
795           (* CSC: why +1 in the following lines ???? *)
796           let parsed_text_length = parsed_text_length + 1 in
797 prerr_endline ("## " ^ string_of_int parsed_text_length);
798           let remain_len = String.length s - parsed_text_length in
799           let next = String.sub s parsed_text_length remain_len in
800           is_there_only_comments lexicon_status next
801       | GrafiteParser.LNone _
802       | GrafiteParser.LSome (GrafiteAst.Executable _) -> false
803     in
804     try
805       is_there_only_comments self#lexicon_status self#getFuture
806     with 
807     | LexiconEngine.IncludedFileNotCompiled _
808     | HExtlib.Localized _
809     | CicNotationParser.Parse_error _ -> false
810     | Margin | End_of_file -> true
811     | Invalid_argument "Array.make" -> false
812
813   (* debug *)
814   method dump () =
815     HLog.debug "script status:";
816     HLog.debug ("history size: " ^ string_of_int (List.length history));
817     HLog.debug (sprintf "%d statements:" (List.length statements));
818     List.iter HLog.debug statements;
819     HLog.debug ("Current file name: " ^
820       (match guistuff.filenamedata with 
821       |None,_ -> "[ no name ]" 
822       | Some f,_ -> f));
823
824 end
825
826 let _script = ref None
827
828 let script ~source_view ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
829 =
830   let s = new script 
831     ~source_view ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
832   in
833   _script := Some s;
834   s
835
836 let current () = match !_script with None -> assert false | Some s -> s
837