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