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