]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaScript.ml
188726d9510879720ff984782cd5d8e26fe558d6
[helm.git] / helm / 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
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*)((.|\n)*)"
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  parsed_text st
81 =
82   let module TAPp = GrafiteAstPp in
83   let parsed_text_length = String.length parsed_text in
84   let initial_space,parsed_text =
85    try
86     let pieces = Pcre.extract ~rex:heading_nl_RE' parsed_text in
87      pieces.(1), pieces.(2)
88    with
89     Not_found -> "", parsed_text in
90   let inital_space,new_grafite_status,new_lexicon_status,new_status_and_text_list' =
91    (* the code commented out adds the "select" command if needed *)
92    initial_space,grafite_status,lexicon_status,[] in
93 (* let loc, ex = 
94     match st with TA.Executable (loc,ex) -> loc, ex | _ -> assert false in
95     match grafite_status.proof_status with
96      | Incomplete_proof { stack = stack }
97       when not (List.mem user_goal (Continuationals.head_goals stack)) ->
98         let grafite_status =
99           MatitaEngine.eval_ast
100             ~do_heavy_checks:true grafite_status (goal_ast user_goal)
101         in
102         let initial_space = if initial_space = "" then "\n" else initial_space
103         in
104         "\n", grafite_status,
105         [ grafite_status,
106           initial_space ^ TAPp.pp_tactical (TA.Select (loc, [user_goal])) ]
107       | _ -> initial_space,grafite_status,[] in *)
108   let enriched_history_fragment =
109    MatitaEngine.eval_ast ~do_heavy_checks:true
110     new_lexicon_status new_grafite_status st
111   in
112   let _,new_text_list_rev = 
113     let module DTE = DisambiguateTypes.Environment in
114     let module UM = UriManager in
115     List.fold_right (
116       fun (_,alias) (initial_space,acc) ->
117        match alias with
118           None -> initial_space,initial_space::acc
119         | Some (k,((v,_) as value)) ->
120            let new_text =
121             let initial_space =
122              if initial_space = "" then "\n" else initial_space
123             in
124              initial_space ^
125               DisambiguatePp.pp_environment
126                (DisambiguateTypes.Environment.add k value
127                  DisambiguateTypes.Environment.empty)
128            in
129             "\n",new_text::acc
130     ) enriched_history_fragment (initial_space,[]) in
131   let new_text_list_rev =
132    match enriched_history_fragment,new_text_list_rev with
133       (_,None)::_, initial_space::tl -> (initial_space ^ parsed_text)::tl
134     | _,_ -> assert false
135   in
136    let res =
137     try
138      List.combine (fst (List.split enriched_history_fragment)) new_text_list_rev
139     with
140      Invalid_argument _ -> assert false
141    in
142     res,parsed_text_length
143
144 let wrap_with_developments guistuff f arg = 
145   try 
146     f arg
147   with
148   | DependenciesParser.UnableToInclude what 
149   | LexiconEngine.IncludedFileNotCompiled what 
150   | GrafiteEngine.IncludedFileNotCompiled what as exc ->
151       let compile_needed_and_go_on d =
152         let target = Pcre.replace ~pat:"lexicon$" ~templ:"moo" what in
153         let refresh_cb () = 
154           while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
155         in
156         if not(MatitamakeLib.build_development_in_bg ~target refresh_cb d) then
157           raise exc
158         else
159           f arg
160       in
161       let do_nothing () = raise ActionCancelled in
162       let handle_with_devel d =
163         let name = MatitamakeLib.name_for_development d in
164         let title = "Unable to include " ^ what in
165         let message = 
166           what ^ " is handled by development <b>" ^ name ^ "</b>.\n\n" ^
167           "<i>Should I compile it and Its dependencies?</i>"
168         in
169         (match guistuff.ask_confirmation ~title ~message with
170         | `YES -> compile_needed_and_go_on d
171         | `NO -> raise exc
172         | `CANCEL -> do_nothing ())
173       in
174       let handle_without_devel filename =
175         let title = "Unable to include " ^ what in
176         let message = 
177          what ^ " is <b>not</b> handled by a development.\n" ^
178          "All dependencies are automatically solved for a development.\n\n" ^
179          "<i>Do you want to set up a development?</i>"
180         in
181         (match guistuff.ask_confirmation ~title ~message with
182         | `YES -> 
183             (match filename with
184             | Some f -> 
185                 guistuff.develcreator ~containing:(Some (Filename.dirname f))
186             | None -> guistuff.develcreator ~containing:None);
187             do_nothing ()
188         | `NO -> raise exc
189         | `CANCEL -> do_nothing())
190       in
191       match guistuff.filenamedata with
192       | None,None -> handle_without_devel None
193       | None,Some d -> handle_with_devel d
194       | Some f,_ ->
195           match MatitamakeLib.development_for_dir (Filename.dirname f) with
196           | None -> handle_without_devel (Some f)
197           | Some d -> handle_with_devel d
198 ;;
199     
200 let eval_with_engine
201      guistuff lexicon_status grafite_status user_goal parsed_text st
202 =
203   wrap_with_developments guistuff
204     (eval_with_engine 
205       guistuff lexicon_status grafite_status user_goal parsed_text) st
206 ;;
207
208 let pp_eager_statement_ast =
209   GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
210     ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
211  
212 let rec eval_macro include_paths (buffer : GText.buffer) guistuff lexicon_status grafite_status user_goal unparsed_text parsed_text script mac =
213   let module TAPp = GrafiteAstPp in
214   let module MQ = MetadataQuery in
215   let module MDB = LibraryDb in
216   let module CTC = CicTypeChecker in
217   let module CU = CicUniv in
218   (* no idea why ocaml wants this *)
219   let parsed_text_length = String.length parsed_text in
220   let dbd = LibraryDb.instance () in
221   (* XXX use a real CIC -> string pretty printer *)
222   let pp_macro = TAPp.pp_macro ~term_pp:CicPp.ppterm in
223   match mac with
224   (* WHELP's stuff *)
225   | TA.WMatch (loc, term) -> 
226      let l =  Whelp.match_term ~dbd term in
227      let query_url =
228        MatitaMisc.strip_suffix ~suffix:"."
229          (HExtlib.trim_blanks unparsed_text)
230      in
231      let entry = `Whelp (query_url, l) in
232      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
233      [], parsed_text_length
234   | TA.WInstance (loc, term) ->
235      let l = Whelp.instance ~dbd term in
236      let entry = `Whelp (pp_macro (TA.WInstance (loc, term)), l) in
237      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
238      [], parsed_text_length
239   | TA.WLocate (loc, s) -> 
240      let l = Whelp.locate ~dbd s in
241      let entry = `Whelp (pp_macro (TA.WLocate (loc, s)), l) in
242      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
243      [], parsed_text_length
244   | TA.WElim (loc, term) ->
245      let uri =
246        match term with
247        | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
248        | _ -> failwith "Not a MutInd"
249      in
250      let l = Whelp.elim ~dbd uri in
251      let entry = `Whelp (pp_macro (TA.WElim (loc, term)), l) in
252      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
253      [], parsed_text_length
254   | TA.WHint (loc, term) ->
255      let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
256      let l = List.map fst (MQ.experimental_hint ~dbd s) in
257      let entry = `Whelp (pp_macro (TA.WHint (loc, term)), l) in
258      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
259      [], parsed_text_length
260   (* REAL macro *)
261   | TA.Hint loc -> 
262       let user_goal' =
263        match user_goal with
264           Some n -> n
265         | None -> raise NoUnfinishedProof
266       in
267       let proof = GrafiteTypes.get_current_proof grafite_status in
268       let proof_status = proof,user_goal' in
269       let l = List.map fst (MQ.experimental_hint ~dbd proof_status) in
270       let selected = guistuff.urichooser l in
271       (match selected with
272       | [] -> [], parsed_text_length
273       | [uri] -> 
274           let suri = UriManager.string_of_uri uri in
275           let ast loc =
276             TA.Executable (loc, (TA.Tactical (loc,
277               TA.Tactic (loc,
278                 TA.Apply (loc, CicNotationPt.Uri (suri, None))),
279                 Some (TA.Dot loc)))) in
280           let text =
281            comment parsed_text ^ "\n" ^
282             pp_eager_statement_ast (ast HExtlib.dummy_floc) in
283           let text_len = String.length text in
284           let loc = HExtlib.floc_of_loc (0,text_len) in
285           let statement = `Ast (GrafiteParser.LSome (ast loc),text) in
286           let res,_parsed_text_len =
287            eval_statement include_paths buffer guistuff lexicon_status
288             grafite_status user_goal script statement
289           in
290            (* we need to replace all the parsed_text *)
291            res,String.length parsed_text
292       | _ -> 
293           HLog.error 
294             "The result of the urichooser should be only 1 uri, not:\n";
295           List.iter (
296             fun u -> HLog.error (UriManager.string_of_uri u ^ "\n")
297           ) selected;
298           assert false)
299   | TA.Check (_,term) ->
300       let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
301       let context =
302        match user_goal with
303           None -> []
304         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
305       let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
306       let t_and_ty = Cic.Cast (term,ty) in
307       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
308       [], parsed_text_length
309   (* TODO *)
310   | TA.Quit _ -> failwith "not implemented"
311   | TA.Print (_,kind) -> failwith "not implemented"
312   | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
313   | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
314                                 
315 and eval_executable include_paths (buffer : GText.buffer) guistuff lexicon_status grafite_status user_goal unparsed_text parsed_text script loc ex
316 =
317  let module TAPp = GrafiteAstPp in
318  let module MD = GrafiteDisambiguator in
319  let module ML = MatitaMisc in
320   try
321    begin
322     match ex with
323      | TA.Command (_,TA.Set (_,"baseuri",u)) ->
324         if not (GrafiteMisc.is_empty u) then
325          (match 
326             guistuff.ask_confirmation 
327               ~title:"Baseuri redefinition" 
328               ~message:(
329                 "Baseuri " ^ u ^ " already exists.\n" ^
330                 "Do you want to redefine the corresponding "^
331                 "part of the library?")
332           with
333            | `YES ->
334                let basedir = Helm_registry.get "matita.basedir" in
335                 LibraryClean.clean_baseuris ~basedir [u]
336            | `NO -> ()
337            | `CANCEL -> raise MatitaTypes.Cancel)
338      | _ -> ()
339    end;
340    eval_with_engine
341     guistuff lexicon_status grafite_status user_goal parsed_text
342      (TA.Executable (loc, ex))
343   with
344      MatitaTypes.Cancel -> [], 0
345    | GrafiteEngine.Macro (_loc,lazy_macro) ->
346       let context =
347        match user_goal with
348           None -> []
349         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
350       let grafite_status,macro = lazy_macro context in
351        eval_macro include_paths buffer guistuff lexicon_status grafite_status
352         user_goal unparsed_text parsed_text script macro
353
354 and eval_statement include_paths (buffer : GText.buffer) guistuff lexicon_status
355  grafite_status user_goal script statement
356 =
357   let (lexicon_status,st), unparsed_text =
358     match statement with
359     | `Raw text ->
360         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
361         let ast = 
362           wrap_with_developments guistuff
363             (GrafiteParser.parse_statement 
364               (Ulexing.from_utf8_string text) ~include_paths) lexicon_status 
365         in
366           ast, text
367     | `Ast (st, text) -> (lexicon_status, st), text
368   in
369   let text_of_loc loc =
370     let parsed_text_length = snd (HExtlib.loc_of_floc loc) in
371     let parsed_text = safe_substring unparsed_text 0 parsed_text_length in
372     parsed_text, parsed_text_length
373   in
374   match st with
375   | GrafiteParser.LNone loc ->
376       let parsed_text, parsed_text_length = text_of_loc loc in
377        [(grafite_status,lexicon_status),parsed_text],
378         parsed_text_length
379   | GrafiteParser.LSome (GrafiteAst.Comment (loc, _)) -> 
380       let parsed_text, parsed_text_length = text_of_loc loc in
381       let remain_len = String.length unparsed_text - parsed_text_length in
382       let s = String.sub unparsed_text parsed_text_length remain_len in
383       let s,len = 
384        try
385         eval_statement include_paths buffer guistuff lexicon_status
386          grafite_status user_goal script (`Raw s)
387        with
388           HExtlib.Localized (floc, exn) ->
389            HExtlib.raise_localized_exception ~offset:parsed_text_length floc exn
390         | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
391            raise
392             (GrafiteDisambiguator.DisambiguationError
393               (offset+parsed_text_length, errorll))
394       in
395       (match s with
396       | (statuses,text)::tl ->
397          (statuses,parsed_text ^ text)::tl,parsed_text_length + len
398       | [] -> [], 0)
399   | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) ->
400      let parsed_text, parsed_text_length = text_of_loc loc in
401       eval_executable include_paths buffer guistuff lexicon_status
402        grafite_status user_goal unparsed_text parsed_text script loc ex
403   
404 let fresh_script_id =
405   let i = ref 0 in
406   fun () -> incr i; !i
407
408 class script  ~(source_view: GSourceView.source_view)
409               ~(mathviewer: MatitaTypes.mathViewer) 
410               ~set_star
411               ~ask_confirmation
412               ~urichooser 
413               ~develcreator 
414               () =
415 let buffer = source_view#buffer in
416 let source_buffer = source_view#source_buffer in
417 let initial_statuses =
418  (* these include_paths are used only to load the initial notation *)
419  let include_paths =
420   Helm_registry.get_list Helm_registry.string "matita.includes" in
421  let lexicon_status =
422   CicNotation2.load_notation ~include_paths
423    BuildTimeConf.core_notation_script in
424  let grafite_status = GrafiteSync.init () in
425   grafite_status,lexicon_status
426 in
427 object (self)
428   val mutable include_paths =
429    Helm_registry.get_list Helm_registry.string "matita.includes"
430
431   val scriptId = fresh_script_id ()
432   
433   val guistuff = {
434     mathviewer = mathviewer;
435     urichooser = urichooser;
436     ask_confirmation = ask_confirmation;
437     develcreator = develcreator;
438     filenamedata = (None, None)} 
439   
440   method private getFilename =
441     match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
442
443   method filename = self#getFilename
444     
445   method private ppFilename =
446     match guistuff.filenamedata with 
447     | Some f,_ -> f 
448     | None,_ -> sprintf ".unnamed%d.ma" scriptId
449   
450   initializer 
451     ignore (GMain.Timeout.add ~ms:300000 
452        ~callback:(fun _ -> self#_saveToBackupFile ();true));
453     ignore (buffer#connect#modified_changed 
454       (fun _ -> set_star (Filename.basename self#ppFilename) buffer#modified))
455
456   val mutable statements = []    (** executed statements *)
457
458   val mutable history = [ initial_statuses ]
459     (** list of states before having executed statements. Head element of this
460       * list is the current state, last element is the state at the beginning of
461       * the script.
462       * Invariant: this list length is 1 + length of statements *)
463
464   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
465   val mutable userGoal = None
466
467   (** text mark and tag representing locked part of a script *)
468   val locked_mark =
469     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
470   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
471   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
472
473   method locked_mark = locked_mark
474   method locked_tag = locked_tag
475   method error_tag = error_tag
476
477     (* history can't be empty, the invariant above grant that it contains at
478      * least the init grafite_status *)
479   method grafite_status = match history with (s,_)::_ -> s | _ -> assert false
480   method lexicon_status = match history with (_,ss)::_ -> ss | _ -> assert false
481
482   method private _advance ?statement () =
483    let s = match statement with Some s -> s | None -> self#getFuture in
484    HLog.debug ("evaluating: " ^ first_line s ^ " ...");
485    let (entries, parsed_len) = 
486     try
487      eval_statement include_paths buffer guistuff self#lexicon_status
488       self#grafite_status userGoal self (`Raw s)
489     with End_of_file -> raise Margin
490    in
491    let new_statuses, new_statements =
492      let statuses, texts = List.split entries in
493      statuses, texts
494    in
495    history <- new_statuses @ history;
496    statements <- new_statements @ statements;
497    let start = buffer#get_iter_at_mark (`MARK locked_mark) in
498    let new_text = String.concat "" (List.rev new_statements) in
499    if statement <> None then
500      buffer#insert ~iter:start new_text
501    else begin
502      if new_text <> String.sub s 0 parsed_len then begin
503        buffer#delete ~start ~stop:(start#copy#forward_chars parsed_len);
504        buffer#insert ~iter:start new_text;
505      end;
506    end;
507    self#moveMark (String.length new_text);
508    (* here we need to set the Goal in case we are going to cursor (or to
509       bottom) and we will face a macro *)
510    match self#grafite_status.proof_status with
511       Incomplete_proof p ->
512        userGoal <-
513          (try Some (Continuationals.Stack.find_goal p.stack)
514          with Failure _ -> None)
515     | _ -> userGoal <- None
516
517   method private _retract offset lexicon_status grafite_status new_statements
518    new_history
519   =
520    let cur_grafite_status,cur_lexicon_status =
521     match history with s::_ -> s | [] -> assert false
522    in
523     LexiconSync.time_travel ~present:cur_lexicon_status ~past:lexicon_status;
524     GrafiteSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
525     statements <- new_statements;
526     history <- new_history;
527     self#moveMark (- offset)
528
529   method advance ?statement () =
530     try
531       self#_advance ?statement ();
532       self#notify
533     with 
534     | Margin -> self#notify
535     | exc -> self#notify; raise exc
536
537   method retract () =
538     try
539       let cmp,new_statements,new_history,(grafite_status,lexicon_status) =
540        match statements,history with
541           stat::statements, _::(status::_ as history) ->
542            String.length stat, statements, history, status
543        | [],[_] -> raise Margin
544        | _,_ -> assert false
545       in
546        self#_retract cmp lexicon_status grafite_status new_statements
547         new_history;
548        self#notify
549     with 
550     | Margin -> self#notify
551     | exc -> self#notify; raise exc
552
553   method private getFuture =
554     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
555       ~stop:buffer#end_iter ()
556
557       
558   (** @param rel_offset relative offset from current position of locked_mark *)
559   method private moveMark rel_offset =
560     let mark = `MARK locked_mark in
561     let old_insert = buffer#get_iter_at_mark `INSERT in
562     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
563     let current_mark_pos = buffer#get_iter_at_mark mark in
564     let new_mark_pos =
565       match rel_offset with
566       | 0 -> current_mark_pos
567       | n when n > 0 -> current_mark_pos#forward_chars n
568       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
569     in
570     buffer#move_mark mark ~where:new_mark_pos;
571     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
572     buffer#move_mark `INSERT old_insert;
573     let mark_position = buffer#get_iter_at_mark mark in
574     if source_view#move_mark_onscreen mark then
575      begin
576       buffer#move_mark mark mark_position;
577       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
578      end;
579     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
580
581   method clean_dirty_lock =
582     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
583     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
584     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
585
586   val mutable observers = []
587
588   method addObserver (o: LexiconEngine.status -> GrafiteTypes.status -> unit) =
589     observers <- o :: observers
590
591   method private notify =
592     let lexicon_status = self#lexicon_status in
593     let grafite_status = self#grafite_status in
594     List.iter (fun o -> o lexicon_status grafite_status) observers
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     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 - 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               
759   method onGoingProof () =
760     match self#grafite_status.proof_status with
761     | No_proof | Proof _ -> false
762     | Incomplete_proof _ -> true
763     | Intermediate _ -> assert false
764
765 (*   method proofStatus = MatitaTypes.get_proof_status self#status *)
766   method proofMetasenv = GrafiteTypes.get_proof_metasenv self#grafite_status
767
768   method proofContext =
769    match userGoal with
770       None -> []
771     | Some n -> GrafiteTypes.get_proof_context self#grafite_status n
772
773   method proofConclusion =
774    match userGoal with
775       None -> assert false
776     | Some n ->
777        GrafiteTypes.get_proof_conclusion self#grafite_status n
778
779   method stack = GrafiteTypes.get_stack self#grafite_status
780   method setGoal n = userGoal <- n
781   method goal = userGoal
782
783   method eos = 
784     let s = self#getFuture in
785     let rec is_there_only_comments lexicon_status s = 
786       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
787       let lexicon_status,st =
788        GrafiteParser.parse_statement (Ulexing.from_utf8_string s)
789         ~include_paths lexicon_status
790       in
791       match st with
792       | GrafiteParser.LSome (GrafiteAst.Comment (loc,_)) -> 
793           let parsed_text_length = snd (HExtlib.loc_of_floc loc) in
794           let remain_len = String.length s - parsed_text_length in
795           let next = String.sub s parsed_text_length remain_len in
796           is_there_only_comments lexicon_status next
797       | GrafiteParser.LNone _
798       | GrafiteParser.LSome (GrafiteAst.Executable _) -> false
799     in
800     try
801       is_there_only_comments self#lexicon_status s
802     with 
803     | CicNotationParser.Parse_error _ -> false
804     | Margin | End_of_file -> true
805
806   (* debug *)
807   method dump () =
808     HLog.debug "script status:";
809     HLog.debug ("history size: " ^ string_of_int (List.length history));
810     HLog.debug (sprintf "%d statements:" (List.length statements));
811     List.iter HLog.debug statements;
812     HLog.debug ("Current file name: " ^
813       (match guistuff.filenamedata with 
814       |None,_ -> "[ no name ]" 
815       | Some f,_ -> f));
816
817 end
818
819 let _script = ref None
820
821 let script ~source_view ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
822 =
823   let s = new script 
824     ~source_view ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
825   in
826   _script := Some s;
827   s
828
829 let current () = match !_script with None -> assert false | Some s -> s
830