]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaScript.ml
Bug fixed: macros in the middle of a goto cursor or goto end-of-script were
[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
40 let safe_substring s i j =
41   try String.sub s i j with Invalid_argument _ -> assert false
42
43 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*"
44 let heading_nl_RE' = Pcre.regexp "^(\\s*\n\\s*)((.|\n)*)"
45 let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$"
46 let multiline_RE = Pcre.regexp "^\n[^\n]+$"
47 let newline_RE = Pcre.regexp "\n"
48  
49 let comment str =
50   if Pcre.pmatch ~rex:multiline_RE str then
51     "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " *)"
52   else
53     "\n(**\n" ^ str ^ "\n*)"
54                      
55 let first_line s =
56   let s = Pcre.replace ~rex:heading_nl_RE s in
57   try
58     let nl_pos = String.index s '\n' in
59     String.sub s 0 nl_pos
60   with Not_found -> s
61
62   (** creates a statement AST for the Goal tactic, e.g. "goal 7" *)
63 let goal_ast n =
64   let module A = GrafiteAst in
65   let loc = HExtlib.dummy_floc in
66   A.Executable (loc, A.Tactical (loc,
67     A.Tactic (loc, A.Goal (loc, n)),
68     Some (A.Dot loc)))
69
70 type guistuff = {
71   mathviewer:MatitaTypes.mathViewer;
72   urichooser: UriManager.uri list -> UriManager.uri list;
73   ask_confirmation: title:string -> message:string -> [`YES | `NO | `CANCEL];
74   develcreator: containing:string option -> unit;
75   mutable filenamedata: string option * MatitamakeLib.development option
76 }
77
78 let eval_with_engine guistuff lexicon_status grafite_status user_goal
79  parsed_text st
80 =
81   let module TAPp = GrafiteAstPp in
82   let include_ = 
83     match guistuff.filenamedata with
84     | None,None -> []
85     | None,Some devel -> [MatitamakeLib.root_for_development devel ]
86     | Some f,_ -> 
87         match MatitamakeLib.development_for_dir (Filename.dirname f) with
88         | None -> []
89         | Some devel -> [MatitamakeLib.root_for_development devel ]
90   in
91   let include_ =
92     include_ @ (Helm_registry.get_list Helm_registry.string "matita.includes")
93   in
94   let parsed_text_length = String.length parsed_text in
95   let loc, ex = 
96     match st with TA.Executable (loc,ex) -> loc, ex | _ -> assert false in
97   let initial_space,parsed_text =
98    try
99     let pieces = Pcre.extract ~rex:heading_nl_RE' parsed_text in
100      pieces.(1), pieces.(2)
101    with
102     Not_found -> "", parsed_text in
103   let inital_space,new_grafite_status,new_lexicon_status,new_status_and_text_list' =
104    (* the code commented out adds the "select" command if needed *)
105    initial_space,grafite_status,lexicon_status,[] in
106 (*    match grafite_status.proof_status with
107      | Incomplete_proof { stack = stack }
108       when not (List.mem user_goal (Continuationals.head_goals stack)) ->
109         let grafite_status =
110           MatitaEngine.eval_ast
111             ~do_heavy_checks:true grafite_status (goal_ast user_goal)
112         in
113         let initial_space = if initial_space = "" then "\n" else initial_space
114         in
115         "\n", grafite_status,
116         [ grafite_status,
117           initial_space ^ TAPp.pp_tactical (TA.Select (loc, [user_goal])) ]
118       | _ -> initial_space,grafite_status,[] in *)
119   let enriched_history_fragment =
120    MatitaEngine.eval_ast ~do_heavy_checks:true
121     new_lexicon_status new_grafite_status st
122   in
123   let _,new_text_list_rev = 
124     let module DTE = DisambiguateTypes.Environment in
125     let module UM = UriManager in
126     List.fold_right (
127       fun (_,alias) (initial_space,acc) ->
128        match alias with
129           None -> initial_space,initial_space::acc
130         | Some (k,((v,_) as value)) ->
131            let new_text =
132             let initial_space =
133              if initial_space = "" then "\n" else initial_space
134             in
135              initial_space ^
136               DisambiguatePp.pp_environment
137                (DisambiguateTypes.Environment.add k value
138                  DisambiguateTypes.Environment.empty)
139            in
140             "\n",new_text::acc
141     ) enriched_history_fragment (initial_space,[]) in
142   let new_text_list_rev =
143    match enriched_history_fragment,new_text_list_rev with
144       (_,None)::_, initial_space::tl -> (initial_space ^ parsed_text)::tl
145     | _,_ -> assert false
146   in
147    let res =
148     try
149      List.combine (fst (List.split enriched_history_fragment)) new_text_list_rev
150     with
151      Invalid_argument _ -> assert false
152    in
153     res,parsed_text_length
154
155 let eval_with_engine
156      guistuff lexicon_status grafite_status user_goal parsed_text st
157 =
158   try
159    eval_with_engine guistuff lexicon_status grafite_status user_goal parsed_text
160     st
161   with
162   | DependenciesParser.UnableToInclude what 
163   | GrafiteEngine.IncludedFileNotCompiled what as exc ->
164       let compile_needed_and_go_on d =
165         let target = what in
166         let refresh_cb () = 
167           while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
168         in
169         if not(MatitamakeLib.build_development_in_bg ~target refresh_cb d) then
170           raise exc
171         else
172          eval_with_engine guistuff lexicon_status grafite_status user_goal
173           parsed_text st
174       in
175       let do_nothing () = [], 0 in
176       let handle_with_devel d =
177         let name = MatitamakeLib.name_for_development d in
178         let title = "Unable to include " ^ what in
179         let message = 
180           what ^ " is handled by development <b>" ^ name ^ "</b>.\n\n" ^
181           "<i>Should I compile it and Its dependencies?</i>"
182         in
183         (match guistuff.ask_confirmation ~title ~message with
184         | `YES -> compile_needed_and_go_on d
185         | `NO -> raise exc
186         | `CANCEL -> do_nothing ())
187       in
188       let handle_without_devel filename =
189         let title = "Unable to include " ^ what in
190         let message = 
191          what ^ " is <b>not</b> handled by a development.\n" ^
192          "All dependencies are automatically solved for a development.\n\n" ^
193          "<i>Do you want to set up a development?</i>"
194         in
195         (match guistuff.ask_confirmation ~title ~message with
196         | `YES -> 
197             (match filename with
198             | Some f -> 
199                 guistuff.develcreator ~containing:(Some (Filename.dirname f))
200             | None -> guistuff.develcreator ~containing:None);
201             do_nothing ()
202         | `NO -> raise exc
203         | `CANCEL -> do_nothing())
204       in
205       match guistuff.filenamedata with
206       | None,None -> handle_without_devel None
207       | None,Some d -> handle_with_devel d
208       | Some f,_ ->
209           match MatitamakeLib.development_for_dir (Filename.dirname f) with
210           | None -> handle_without_devel (Some f)
211           | Some d -> handle_with_devel d
212 ;;
213
214 let pp_eager_statement_ast =
215   GrafiteAstPp.pp_statement ~term_pp:CicNotationPp.pp_term
216     ~lazy_term_pp:(fun _ -> assert false) ~obj_pp:(fun _ -> assert false)
217  
218 let rec eval_macro (buffer : GText.buffer) guistuff lexicon_status grafite_status user_goal unparsed_text parsed_text script mac =
219   let module TAPp = GrafiteAstPp in
220   let module MQ = MetadataQuery in
221   let module MDB = LibraryDb in
222   let module CTC = CicTypeChecker in
223   let module CU = CicUniv in
224   (* no idea why ocaml wants this *)
225   let parsed_text_length = String.length parsed_text in
226   let dbd = LibraryDb.instance () in
227   (* XXX use a real CIC -> string pretty printer *)
228   let pp_macro = TAPp.pp_macro ~term_pp:CicPp.ppterm in
229   match mac with
230   (* WHELP's stuff *)
231   | TA.WMatch (loc, term) -> 
232      let l =  Whelp.match_term ~dbd term in
233      let query_url =
234        MatitaMisc.strip_suffix ~suffix:"."
235          (HExtlib.trim_blanks unparsed_text)
236      in
237      let entry = `Whelp (query_url, l) in
238      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
239      [], parsed_text_length
240   | TA.WInstance (loc, term) ->
241      let l = Whelp.instance ~dbd term in
242      let entry = `Whelp (pp_macro (TA.WInstance (loc, term)), l) in
243      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
244      [], parsed_text_length
245   | TA.WLocate (loc, s) -> 
246      let l = Whelp.locate ~dbd s in
247      let entry = `Whelp (pp_macro (TA.WLocate (loc, s)), l) in
248      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
249      [], parsed_text_length
250   | TA.WElim (loc, term) ->
251      let uri =
252        match term with
253        | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
254        | _ -> failwith "Not a MutInd"
255      in
256      let l = Whelp.elim ~dbd uri in
257      let entry = `Whelp (pp_macro (TA.WElim (loc, term)), l) in
258      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
259      [], parsed_text_length
260   | TA.WHint (loc, term) ->
261      let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
262      let l = List.map fst (MQ.experimental_hint ~dbd s) in
263      let entry = `Whelp (pp_macro (TA.WHint (loc, term)), l) in
264      guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
265      [], parsed_text_length
266   (* REAL macro *)
267   | TA.Hint loc -> 
268       let user_goal' =
269        match user_goal with
270           Some n -> n
271         | None -> raise NoUnfinishedProof
272       in
273       let proof = GrafiteTypes.get_current_proof grafite_status in
274       let proof_status = proof,user_goal' in
275       let l = List.map fst (MQ.experimental_hint ~dbd proof_status) in
276       let selected = guistuff.urichooser l in
277       (match selected with
278       | [] -> [], parsed_text_length
279       | [uri] -> 
280           let suri = UriManager.string_of_uri uri in
281           let ast loc =
282             TA.Executable (loc, (TA.Tactical (loc,
283               TA.Tactic (loc,
284                 TA.Apply (loc, CicNotationPt.Uri (suri, None))),
285                 Some (TA.Dot loc)))) in
286           let text =
287            comment parsed_text ^ "\n" ^
288             pp_eager_statement_ast (ast HExtlib.dummy_floc) in
289           let text_len = String.length text in
290           let loc = HExtlib.floc_of_loc (0,text_len) in
291           let statement = `Ast (GrafiteParser.LSome (ast loc),text) in
292           let res,_parsed_text_len =
293            eval_statement buffer guistuff lexicon_status grafite_status
294             user_goal script statement
295           in
296            (* we need to replace all the parsed_text *)
297            res,String.length parsed_text
298       | _ -> 
299           HLog.error 
300             "The result of the urichooser should be only 1 uri, not:\n";
301           List.iter (
302             fun u -> HLog.error (UriManager.string_of_uri u ^ "\n")
303           ) selected;
304           assert false)
305   | TA.Check (_,term) ->
306       let metasenv = GrafiteTypes.get_proof_metasenv grafite_status in
307       let context =
308        match user_goal with
309           None -> []
310         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
311       let ty,_ = CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph in
312       let t_and_ty = Cic.Cast (term,ty) in
313       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
314       [], parsed_text_length
315   (* TODO *)
316   | TA.Quit _ -> failwith "not implemented"
317   | TA.Print (_,kind) -> failwith "not implemented"
318   | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
319   | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
320                                 
321 and eval_executable (buffer : GText.buffer) guistuff lexicon_status grafite_status user_goal unparsed_text parsed_text script loc ex
322 =
323  let module TAPp = GrafiteAstPp in
324  let module MD = GrafiteDisambiguator in
325  let module ML = MatitaMisc in
326   try
327    begin
328     match ex with
329      | TA.Command (_,TA.Set (_,"baseuri",u)) ->
330         if not (GrafiteMisc.is_empty u) then
331          (match 
332             guistuff.ask_confirmation 
333               ~title:"Baseuri redefinition" 
334               ~message:(
335                 "Baseuri " ^ u ^ " already exists.\n" ^
336                 "Do you want to redefine the corresponding "^
337                 "part of the library?")
338           with
339            | `YES ->
340                let basedir = Helm_registry.get "matita.basedir" in
341                 LibraryClean.clean_baseuris ~basedir [u]
342            | `NO -> ()
343            | `CANCEL -> raise MatitaTypes.Cancel)
344      | _ -> ()
345    end;
346    eval_with_engine
347     guistuff lexicon_status grafite_status user_goal parsed_text
348      (TA.Executable (loc, ex))
349   with
350      MatitaTypes.Cancel -> [], 0
351    | GrafiteEngine.Macro (_loc,lazy_macro) ->
352       let context =
353        match user_goal with
354           None -> []
355         | Some n -> GrafiteTypes.get_proof_context grafite_status n in
356       let grafite_status,macro = lazy_macro context in
357        eval_macro buffer guistuff lexicon_status grafite_status user_goal
358         unparsed_text parsed_text script macro
359
360 and eval_statement (buffer : GText.buffer) guistuff lexicon_status
361  grafite_status user_goal script statement
362 =
363   let (lexicon_status,st), unparsed_text =
364     match statement with
365     | `Raw text ->
366         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
367         GrafiteParser.parse_statement (Ulexing.from_utf8_string text)
368          ~include_paths:(Helm_registry.get_list
369            Helm_registry.string "matita.includes")
370          lexicon_status, text
371     | `Ast (st, text) -> (lexicon_status, st), text
372   in
373   let text_of_loc loc =
374     let parsed_text_length = snd (HExtlib.loc_of_floc loc) in
375     let parsed_text = safe_substring unparsed_text 0 parsed_text_length in
376     parsed_text, parsed_text_length
377   in
378   match st with
379   | GrafiteParser.LNone loc ->
380       let parsed_text, parsed_text_length = text_of_loc loc in
381        [(grafite_status,lexicon_status),parsed_text],
382         parsed_text_length
383   | GrafiteParser.LSome (GrafiteAst.Comment (loc, _)) -> 
384       let parsed_text, parsed_text_length = text_of_loc loc in
385       let remain_len = String.length unparsed_text - parsed_text_length in
386       let s = String.sub unparsed_text parsed_text_length remain_len in
387       let s,len = 
388        try
389         eval_statement buffer guistuff lexicon_status grafite_status user_goal
390          script (`Raw s)
391        with
392           HExtlib.Localized (floc, exn) ->
393            HExtlib.raise_localized_exception ~offset:parsed_text_length floc exn
394         | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
395            raise
396             (GrafiteDisambiguator.DisambiguationError
397               (offset+parsed_text_length, errorll))
398       in
399       (match s with
400       | (statuses,text)::tl ->
401          (statuses,parsed_text ^ text)::tl,parsed_text_length + len
402       | [] -> [], 0)
403   | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) ->
404      let parsed_text, parsed_text_length = text_of_loc loc in
405       eval_executable buffer guistuff lexicon_status grafite_status user_goal
406        unparsed_text parsed_text script loc ex
407   
408 let fresh_script_id =
409   let i = ref 0 in
410   fun () -> incr i; !i
411
412 class script  ~(source_view: GSourceView.source_view)
413               ~(mathviewer: MatitaTypes.mathViewer) 
414               ~set_star
415               ~ask_confirmation
416               ~urichooser 
417               ~develcreator 
418               () =
419 let buffer = source_view#buffer in
420 let source_buffer = source_view#source_buffer in
421 let initial_statuses =
422  let include_paths =
423   Helm_registry.get_list Helm_registry.string "matita.includes" in
424  let lexicon_status =
425   CicNotation2.load_notation ~include_paths
426    BuildTimeConf.core_notation_script in
427  let grafite_status = GrafiteSync.init () in
428   grafite_status,lexicon_status
429 in
430 object (self)
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 buffer guistuff self#lexicon_status self#grafite_status
488       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 <- Some (Continuationals.Stack.find_goal p.stack)
513     | _ -> userGoal <- None
514
515   method private _retract offset lexicon_status grafite_status new_statements
516    new_history
517   =
518    let cur_grafite_status,cur_lexicon_status =
519     match history with s::_ -> s | [] -> assert false
520    in
521     LexiconSync.time_travel ~present:cur_lexicon_status ~past:lexicon_status;
522     GrafiteSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
523     statements <- new_statements;
524     history <- new_history;
525     self#moveMark (- offset)
526
527   method advance ?statement () =
528     try
529       self#_advance ?statement ();
530       self#notify
531     with 
532     | Margin -> self#notify
533     | exc -> self#notify; raise exc
534
535   method retract () =
536     try
537       let cmp,new_statements,new_history,(grafite_status,lexicon_status) =
538        match statements,history with
539           stat::statements, _::(status::_ as history) ->
540            String.length stat, statements, history, status
541        | [],[_] -> raise Margin
542        | _,_ -> assert false
543       in
544        self#_retract cmp lexicon_status grafite_status new_statements
545         new_history;
546        self#notify
547     with 
548     | Margin -> self#notify
549     | exc -> self#notify; raise exc
550
551   method private getFuture =
552     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
553       ~stop:buffer#end_iter ()
554
555       
556   (** @param rel_offset relative offset from current position of locked_mark *)
557   method private moveMark rel_offset =
558     let mark = `MARK locked_mark in
559     let old_insert = buffer#get_iter_at_mark `INSERT in
560     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
561     let current_mark_pos = buffer#get_iter_at_mark mark in
562     let new_mark_pos =
563       match rel_offset with
564       | 0 -> current_mark_pos
565       | n when n > 0 -> current_mark_pos#forward_chars n
566       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
567     in
568     buffer#move_mark mark ~where:new_mark_pos;
569     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
570     buffer#move_mark `INSERT old_insert;
571     let mark_position = buffer#get_iter_at_mark mark in
572     if source_view#move_mark_onscreen mark then
573      begin
574       buffer#move_mark mark mark_position;
575       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
576      end;
577     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
578
579   method clean_dirty_lock =
580     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
581     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
582     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
583
584   val mutable observers = []
585
586   method addObserver (o: LexiconEngine.status -> GrafiteTypes.status -> unit) =
587     observers <- o :: observers
588
589   method private notify =
590     let lexicon_status = self#lexicon_status in
591     let grafite_status = self#grafite_status in
592     List.iter (fun o -> o lexicon_status grafite_status) observers
593
594   method loadFromFile f =
595     buffer#set_text (HExtlib.input_file f);
596     self#reset_buffer;
597     buffer#set_modified false
598     
599   method assignFileName file =
600     let abspath = MatitaMisc.absolute_path file in
601     let devel = MatitamakeLib.development_for_dir (Filename.dirname abspath) in
602     guistuff.filenamedata <- Some abspath, devel
603     
604   method saveToFile () =
605     let oc = open_out self#getFilename in
606     output_string oc (buffer#get_text ~start:buffer#start_iter
607                         ~stop:buffer#end_iter ());
608     close_out oc;
609     buffer#set_modified false
610   
611   method private _saveToBackupFile () =
612     if buffer#modified then
613       begin
614         let f = self#ppFilename ^ "~" in
615         let oc = open_out f in
616         output_string oc (buffer#get_text ~start:buffer#start_iter
617                             ~stop:buffer#end_iter ());
618         close_out oc;
619         HLog.debug ("backup " ^ f ^ " saved")                    
620       end
621   
622   method private goto_top =
623     let grafite_status,lexicon_status = 
624       let rec last x = function 
625       | [] -> x
626       | hd::tl -> last hd tl
627       in
628       last (self#grafite_status,self#lexicon_status) history
629     in
630     (* FIXME: this is not correct since there is no undo for 
631      * library_objects.set_default... *)
632     GrafiteSync.time_travel ~present:self#grafite_status ~past:grafite_status;
633     LexiconSync.time_travel ~present:self#lexicon_status ~past:lexicon_status
634
635   method private reset_buffer = 
636     statements <- [];
637     history <- [ initial_statuses ];
638     userGoal <- None;
639     self#notify;
640     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
641     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
642
643   method reset () =
644     self#reset_buffer;
645     source_buffer#begin_not_undoable_action ();
646     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
647     source_buffer#end_not_undoable_action ();
648     buffer#set_modified false;
649   
650   method template () =
651     let template = HExtlib.input_file BuildTimeConf.script_template in 
652     buffer#insert ~iter:(buffer#get_iter `START) template;
653     guistuff.filenamedata <- 
654       (None,MatitamakeLib.development_for_dir (Unix.getcwd ()));
655     buffer#set_modified false;
656     set_star (Filename.basename self#ppFilename) false
657
658   method goto (pos: [`Top | `Bottom | `Cursor]) () =
659     let old_locked_mark =
660      `MARK
661        (buffer#create_mark ~name:"old_locked_mark"
662          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
663     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
664     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
665     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
666     match pos with
667     | `Top -> 
668         dispose_old_locked_mark (); 
669         self#goto_top; 
670         self#reset_buffer;
671         self#notify
672     | `Bottom ->
673         (try 
674           let rec dowhile () =
675             self#_advance ();
676             let newpos = getpos () in
677             if (getoldpos ())#compare newpos < 0 then
678               begin
679                 buffer#move_mark old_locked_mark newpos;
680                 dowhile ()
681               end
682           in
683           dowhile ();
684           dispose_old_locked_mark ();
685           self#notify 
686         with 
687         | Margin -> dispose_old_locked_mark (); self#notify
688         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
689     | `Cursor ->
690         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
691         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
692         let remember =
693          `MARK
694            (buffer#create_mark ~name:"initial_insert"
695              ~left_gravity:true (cursor_iter ())) in
696         let dispose_remember () = buffer#delete_mark remember in
697         let remember_iter () =
698          buffer#get_iter_at_mark (`NAME "initial_insert") in
699         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
700         let icmp = cmp () in
701         let forward_until_cursor () = (* go forward until locked > cursor *)
702           let rec aux () =
703             self#_advance ();
704             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
705             then
706              begin
707               buffer#move_mark old_locked_mark (getpos ());
708               aux ()
709              end
710           in
711           aux ()
712         in
713         let rec back_until_cursor len = (* go backward until locked < cursor *)
714          function
715             statements, ((grafite_status,lexicon_status)::_ as history)
716             when len <= 0 ->
717              self#_retract (icmp - len) lexicon_status grafite_status statements
718               history
719           | statement::tl1, _::tl2 ->
720              back_until_cursor (len - String.length statement) (tl1,tl2)
721           | _,_ -> assert false
722         in
723         (try
724           begin
725            if icmp < 0 then       (* locked < cursor *)
726              (forward_until_cursor (); self#notify)
727            else if icmp > 0 then  (* locked > cursor *)
728              (back_until_cursor icmp (statements,history); self#notify)
729            else                  (* cursor = locked *)
730                ()
731           end ;
732           dispose_remember ();
733           dispose_old_locked_mark ();
734         with 
735         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
736         | exc -> dispose_remember (); dispose_old_locked_mark ();
737                  self#notify; raise exc)
738               
739   method onGoingProof () =
740     match self#grafite_status.proof_status with
741     | No_proof | Proof _ -> false
742     | Incomplete_proof _ -> true
743     | Intermediate _ -> assert false
744
745 (*   method proofStatus = MatitaTypes.get_proof_status self#status *)
746   method proofMetasenv = GrafiteTypes.get_proof_metasenv self#grafite_status
747
748   method proofContext =
749    match userGoal with
750       None -> assert false
751     | Some n ->
752        GrafiteTypes.get_proof_context self#grafite_status n
753
754   method proofConclusion =
755    match userGoal with
756       None -> assert false
757     | Some n ->
758        GrafiteTypes.get_proof_conclusion self#grafite_status n
759
760   method stack = GrafiteTypes.get_stack self#grafite_status
761   method setGoal n = userGoal <- Some n
762   method goal = userGoal
763
764   method eos = 
765     let s = self#getFuture in
766     let rec is_there_and_executable lexicon_status s = 
767       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
768       let lexicon_status,st =
769        GrafiteParser.parse_statement (Ulexing.from_utf8_string s)
770         ~include_paths:(Helm_registry.get_list
771           Helm_registry.string "matita.includes")
772         lexicon_status
773       in
774       match st with
775         GrafiteParser.LNone loc
776       | GrafiteParser.LSome (GrafiteAst.Comment (loc,_)) -> 
777           let parsed_text_length = snd (HExtlib.loc_of_floc loc) in
778           let remain_len = String.length s - parsed_text_length in
779           let next = String.sub s parsed_text_length remain_len in
780           is_there_and_executable lexicon_status next
781       | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) -> false
782     in
783     try
784       is_there_and_executable self#lexicon_status s
785     with 
786     | CicNotationParser.Parse_error _ -> false
787     | Margin | End_of_file -> true
788
789   (* debug *)
790   method dump () =
791     HLog.debug "script status:";
792     HLog.debug ("history size: " ^ string_of_int (List.length history));
793     HLog.debug (sprintf "%d statements:" (List.length statements));
794     List.iter HLog.debug statements;
795     HLog.debug ("Current file name: " ^
796       (match guistuff.filenamedata with 
797       |None,_ -> "[ no name ]" 
798       | Some f,_ -> f));
799
800 end
801
802 let _script = ref None
803
804 let script ~source_view ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
805 =
806   let s = new script 
807     ~source_view ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
808   in
809   _script := Some s;
810   s
811
812 let current () = match !_script with None -> assert false | Some s -> s
813