]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaScript.ml
DisambiguationError exceptions (that have locations inside) are now relocated
[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 open Printf
27 open MatitaTypes
28
29 module TA = GrafiteAst
30
31 let debug = false
32 let debug_print = if debug then prerr_endline else ignore
33
34   (** raised when one of the script margins (top or bottom) is reached *)
35 exception Margin
36
37 let safe_substring s i j =
38   try String.sub s i j with Invalid_argument _ -> assert false
39
40 let heading_nl_RE = Pcre.regexp "^\\s*\n\\s*"
41 let heading_nl_RE' = Pcre.regexp "^(\\s*\n\\s*)((.|\n)*)"
42 let only_dust_RE = Pcre.regexp "^(\\s|\n|%%[^\n]*\n)*$"
43 let multiline_RE = Pcre.regexp "^\n[^\n]+$"
44 let newline_RE = Pcre.regexp "\n"
45  
46 let comment str =
47   if Pcre.pmatch ~rex:multiline_RE str then
48     "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " *)"
49   else
50     "\n(**\n" ^ str ^ "\n*)"
51                      
52 let first_line s =
53   let s = Pcre.replace ~rex:heading_nl_RE s in
54   try
55     let nl_pos = String.index s '\n' in
56     String.sub s 0 nl_pos
57   with Not_found -> s
58
59   (** creates a statement AST for the Goal tactic, e.g. "goal 7" *)
60 let goal_ast n =
61   let module A = GrafiteAst in
62   let loc = DisambiguateTypes.dummy_floc in
63   A.Executable (loc, A.Tactical (loc,
64     A.Tactic (loc, A.Goal (loc, n)),
65     Some (A.Dot loc)))
66
67 type guistuff = {
68   mathviewer:MatitaTypes.mathViewer;
69   urichooser: UriManager.uri list -> UriManager.uri list;
70   ask_confirmation: title:string -> message:string -> [`YES | `NO | `CANCEL];
71   develcreator: containing:string option -> unit;
72   mutable filenamedata: string option * MatitamakeLib.development option
73 }
74
75 let eval_with_engine guistuff status user_goal parsed_text st =
76   let module TAPp = GrafiteAstPp in
77   let include_ = 
78     match guistuff.filenamedata with
79     | None,None -> []
80     | None,Some devel -> [MatitamakeLib.root_for_development devel ]
81     | Some f,_ -> 
82         match MatitamakeLib.development_for_dir (Filename.dirname f) with
83         | None -> []
84         | Some devel -> [MatitamakeLib.root_for_development devel ]
85   in
86   let parsed_text_length = String.length parsed_text in
87   let loc, ex = 
88     match st with TA.Executable (loc,ex) -> loc, ex | _ -> assert false in
89   let initial_space,parsed_text =
90    try
91     let pieces = Pcre.extract ~rex:heading_nl_RE' parsed_text in
92      pieces.(1), pieces.(2)
93    with
94     Not_found -> "", parsed_text in
95   (* we add the goal command if needed *)
96   let inital_space,new_status,new_status_and_text_list' =
97     match status.proof_status with
98 (*     | Incomplete_proof { stack = stack }
99       when not (List.mem user_goal (Continuationals.head_goals stack)) ->
100         let status =
101           MatitaEngine.eval_ast ~include_paths:include_
102             ~do_heavy_checks:true status (goal_ast user_goal)
103         in
104         let initial_space = if initial_space = "" then "\n" else initial_space
105         in
106         "\n", status,
107         [ status,
108           initial_space ^ TAPp.pp_tactical (TA.Select (loc, [user_goal])) ] *)
109       | _ -> initial_space,status,[] in
110   let new_status = 
111     MatitaEngine.eval_ast 
112       ~include_paths:include_ ~do_heavy_checks:true new_status st 
113   in
114   let new_aliases =
115     match ex with
116       | TA.Command (_, TA.Alias _)
117       | TA.Command (_, TA.Include _)
118       | TA.Command (_, TA.Interpretation _) -> []
119       | _ -> MatitaSync.alias_diff ~from:status new_status
120   in
121   (* we remove the defined object since we consider them "automatic aliases" *)
122   let dummy_st =
123     TA.Comment (DisambiguateTypes.dummy_floc,
124       TA.Note (DisambiguateTypes.dummy_floc, ""))
125   in
126   let initial_space,status,new_status_and_text_list_rev = 
127     let module DTE = DisambiguateTypes.Environment in
128     let module UM = UriManager in
129     List.fold_left (
130       fun (initial_space,status,acc) (k,((v,_) as value)) -> 
131         let b = 
132           try
133             let v = UM.strip_xpointer (UM.uri_of_string v) in
134             List.exists (fun (s,_) -> s = v) new_status.objects 
135           with UM.IllFormedUri _ -> false
136         in
137         if b then 
138           initial_space,status,acc
139         else
140          let new_text =
141           let initial_space =
142            if initial_space = "" then "\n" else initial_space in
143             initial_space ^
144              DisambiguatePp.pp_environment
145               (DisambiguateTypes.Environment.add k value
146                 DisambiguateTypes.Environment.empty) in
147          let new_status =
148           MatitaSync.set_proof_aliases status [k,value]
149          in
150           "\n",new_status,((new_status, (new_text, dummy_st))::acc)
151     ) (initial_space,status,[]) new_aliases in
152   let parsed_text = initial_space ^ parsed_text in
153   let res =
154    List.rev new_status_and_text_list_rev @ new_status_and_text_list' @
155     [new_status, (parsed_text, st)]
156   in
157    res,parsed_text_length
158
159 let eval_with_engine guistuff status user_goal parsed_text st =
160   try
161     eval_with_engine guistuff status user_goal parsed_text st
162   with
163   | MatitaEngine.UnableToInclude what 
164   | MatitaEngine.IncludedFileNotCompiled what as exc ->
165       let compile_needed_and_go_on d =
166         let target = what in
167         let refresh_cb () = 
168           while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
169         in
170         if not(MatitamakeLib.build_development_in_bg ~target refresh_cb d) then
171           raise exc
172         else
173           eval_with_engine guistuff status user_goal 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 disambiguate_macro_term term status user_goal =
215   let module MD = MatitaDisambiguator in
216   let dbd = MatitaDb.instance () in
217   let metasenv = MatitaTypes.get_proof_metasenv status in
218   let context = MatitaTypes.get_proof_context status user_goal in
219   let interps =
220    MD.disambiguate_term ~dbd ~context ~metasenv ~aliases:status.aliases
221     ~universe:(Some status.multi_aliases) term in
222   match interps with 
223   | [_,_,x,_], _ -> x
224   | _ -> assert false
225  
226 let eval_macro guistuff status user_goal unparsed_text parsed_text script mac =
227   let module TAPp = GrafiteAstPp in
228   let module MQ = MetadataQuery in
229   let module MDB = MatitaDb in
230   let module CTC = CicTypeChecker in
231   let module CU = CicUniv in
232   (* no idea why ocaml wants this *)
233   let parsed_text_length = String.length parsed_text in
234   let dbd = MatitaDb.instance () in
235   match mac with
236   (* WHELP's stuff *)
237   | TA.WMatch (loc, term) -> 
238       let term = disambiguate_macro_term term status user_goal in
239       let l =  Whelp.match_term ~dbd term in
240       let query_url =
241         MatitaMisc.strip_suffix ~suffix:"."
242           (HExtlib.trim_blanks unparsed_text)
243       in
244       let entry = `Whelp (query_url, l) in
245       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
246       [], parsed_text_length
247   | TA.WInstance (loc, term) ->
248       let term = disambiguate_macro_term term status user_goal in
249       let l = Whelp.instance ~dbd term in
250       let entry = `Whelp (TAPp.pp_macro_cic (TA.WInstance (loc, term)), l) in
251       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
252       [], parsed_text_length
253   | TA.WLocate (loc, s) -> 
254       let l = Whelp.locate ~dbd s in
255       let entry = `Whelp (TAPp.pp_macro_cic (TA.WLocate (loc, s)), l) in
256       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
257       [], parsed_text_length
258   | TA.WElim (loc, term) ->
259       let term = disambiguate_macro_term term status user_goal in
260       let uri =
261         match term with
262         | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
263         | _ -> failwith "Not a MutInd"
264       in
265       let l = Whelp.elim ~dbd uri in
266       let entry = `Whelp (TAPp.pp_macro_cic (TA.WElim (loc, term)), l) in
267       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
268       [], parsed_text_length
269   | TA.WHint (loc, term) ->
270       let term = disambiguate_macro_term term status user_goal in
271       let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
272       let l = List.map fst (MQ.experimental_hint ~dbd s) in
273       let entry = `Whelp (TAPp.pp_macro_cic (TA.WHint (loc, term)), l) in
274       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
275       [], parsed_text_length
276   (* REAL macro *)
277   | TA.Hint loc -> 
278       let proof = MatitaTypes.get_current_proof status in
279       let proof_status = proof, user_goal in
280       let l = List.map fst (MQ.experimental_hint ~dbd proof_status) in
281       let selected = guistuff.urichooser l in
282       (match selected with
283       | [] -> [], parsed_text_length
284       | [uri] -> 
285           let suri = UriManager.string_of_uri uri in
286           let ast = 
287             TA.Executable (loc, (TA.Tactical (loc,
288               TA.Tactic (loc,
289                 TA.Apply (loc, CicNotationPt.Uri (suri, None))),
290                 Some (TA.Dot loc))))
291           in
292         let new_status = MatitaEngine.eval_ast status ast in
293         let extra_text = 
294           comment parsed_text ^ 
295           "\n" ^ TAPp.pp_statement ast
296         in
297         [ new_status , (extra_text, ast) ], parsed_text_length
298       | _ -> 
299           MatitaLog.error 
300             "The result of the urichooser should be only 1 uri, not:\n";
301           List.iter (
302             fun u -> MatitaLog.error (UriManager.string_of_uri u ^ "\n")
303           ) selected;
304           assert false)
305   | TA.Check (_,term) ->
306       let metasenv = MatitaTypes.get_proof_metasenv status in
307       let context = MatitaTypes.get_proof_context status user_goal in
308       let interps = 
309         MatitaDisambiguator.disambiguate_term ~dbd ~context ~metasenv
310          ~aliases:status.aliases ~universe:(Some status.multi_aliases) term
311       in
312       let _, metasenv , term, ugraph =
313         match interps with 
314         | [x], _ -> x
315         | _ -> assert false
316       in
317       let ty,_ = CTC.type_of_aux' metasenv context term ugraph in
318       let t_and_ty = Cic.Cast (term,ty) in
319       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
320       [], parsed_text_length
321 (*   | TA.Abort _ -> 
322       let rec go_back () =
323         let status = script#status.proof_status in
324         match status with
325         | No_proof -> ()
326         | _ -> script#retract ();go_back()
327       in
328       [], parsed_text_length, Some go_back
329   | TA.Redo (_, Some i) ->  [], parsed_text_length, 
330       Some (fun () -> for j = 1 to i do advance () done)
331   | TA.Redo (_, None) ->   [], parsed_text_length, 
332       Some (fun () -> advance ())
333   | TA.Undo (_, Some i) ->  [], parsed_text_length, 
334       Some (fun () -> for j = 1 to i do script#retract () done)
335   | TA.Undo (_, None) -> [], parsed_text_length, 
336       Some (fun () -> script#retract ()) *)
337   (* TODO *)
338   | TA.Quit _ -> failwith "not implemented"
339   | TA.Print (_,kind) -> failwith "not implemented"
340   | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
341   | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
342                                 
343 let eval_executable guistuff status user_goal unparsed_text parsed_text script
344   ex
345 =
346   let module TAPp = GrafiteAstPp in
347   let module MD = MatitaDisambiguator in
348   let module ML = MatitacleanLib in
349   match ex with
350   | TA.Command (loc, _) | TA.Tactical (loc, _, _) ->
351       (try 
352         (match MatitaMisc.baseuri_of_baseuri_decl (TA.Executable (loc,ex)) with
353         | None -> ()
354         | Some u -> 
355             if not (MatitaMisc.is_empty u) then
356               match 
357                 guistuff.ask_confirmation 
358                   ~title:"Baseuri redefinition" 
359                   ~message:(
360                     "Baseuri " ^ u ^ " already exists.\n" ^
361                     "Do you want to redefine the corresponding "^
362                     "part of the library?")
363               with
364               | `YES -> MatitacleanLib.clean_baseuris [u]
365               | `NO -> ()
366               | `CANCEL -> raise MatitaTypes.Cancel);
367         eval_with_engine 
368           guistuff status user_goal parsed_text (TA.Executable (loc, ex))
369       with MatitaTypes.Cancel -> [], 0)
370   | TA.Macro (_,mac) ->
371       eval_macro guistuff status user_goal unparsed_text parsed_text script mac
372
373 let rec eval_statement (buffer : GText.buffer) guistuff status user_goal
374  script statement
375 =
376   let st, unparsed_text =
377     match statement with
378     | `Raw text ->
379         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
380         GrafiteParser.parse_statement (Ulexing.from_utf8_string text), text
381     | `Ast (st, text) -> st, text
382   in
383   let text_of_loc loc =
384     let parsed_text_length = snd (HExtlib.loc_of_floc loc) in
385     let parsed_text = safe_substring unparsed_text 0 parsed_text_length in
386     parsed_text, parsed_text_length
387   in
388   match st with
389   | GrafiteAst.Comment (loc, _) -> 
390       let parsed_text, parsed_text_length = text_of_loc loc in
391       let remain_len = String.length unparsed_text - parsed_text_length in
392       let s = String.sub unparsed_text parsed_text_length remain_len in
393       let s,len = 
394        try
395         eval_statement buffer guistuff status user_goal script
396          (`Raw s)
397        with
398           HExtlib.Localized (floc, exn) ->
399            HExtlib.raise_localized_exception ~offset:parsed_text_length floc exn
400         | MatitaDisambiguator.DisambiguationError (offset,errorll) ->
401            raise
402             (MatitaDisambiguator.DisambiguationError
403               (offset+parsed_text_length, errorll))
404       in
405       (match s with
406       | (status, (text, ast)) :: tl ->
407           ((status, (parsed_text ^ text, ast))::tl), (parsed_text_length + len)
408       | [] -> [], 0)
409   | GrafiteAst.Executable (loc, ex) ->
410       let parsed_text, parsed_text_length = text_of_loc loc in
411       eval_executable guistuff status user_goal unparsed_text parsed_text
412         script ex 
413   
414 let fresh_script_id =
415   let i = ref 0 in
416   fun () -> incr i; !i
417
418 class script  ~(source_view: GSourceView.source_view)
419               ~(init: MatitaTypes.status) 
420               ~(mathviewer: MatitaTypes.mathViewer) 
421               ~set_star
422               ~ask_confirmation
423               ~urichooser 
424               ~develcreator 
425               () =
426 let buffer = source_view#buffer in
427 let source_buffer = source_view#source_buffer in
428 object (self)
429   val scriptId = fresh_script_id ()
430   
431   val guistuff = {
432     mathviewer = mathviewer;
433     urichooser = urichooser;
434     ask_confirmation = ask_confirmation;
435     develcreator = develcreator;
436     filenamedata = (None, None)} 
437   
438   method private getFilename =
439     match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
440
441   method filename = self#getFilename
442     
443   method private ppFilename =
444     match guistuff.filenamedata with 
445     | Some f,_ -> f 
446     | None,_ -> sprintf ".unnamed%d.ma" scriptId
447   
448   initializer 
449     ignore (GMain.Timeout.add ~ms:300000 
450        ~callback:(fun _ -> self#_saveToBackupFile ();true));
451     ignore (buffer#connect#modified_changed 
452       (fun _ -> set_star (Filename.basename self#ppFilename) buffer#modified))
453
454   val mutable statements = [];    (** executed statements *)
455   val mutable history = [ init ];
456     (** list of states before having executed statements. Head element of this
457       * list is the current state, last element is the state at the beginning of
458       * the script.
459       * Invariant: this list length is 1 + length of statements *)
460
461   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
462   val mutable userGoal = ~-1
463
464   (** text mark and tag representing locked part of a script *)
465   val locked_mark =
466     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
467   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
468   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
469
470   method locked_mark = locked_mark
471   method locked_tag = locked_tag
472   method error_tag = error_tag
473
474     (* history can't be empty, the invariant above grant that it contains at
475      * least the init status *)
476   method status = match history with hd :: _ -> hd | _ -> assert false
477
478   method private _advance ?statement () =
479     let rec aux st =
480       let (entries, parsed_len) = 
481         eval_statement buffer guistuff self#status userGoal self st
482       in
483       let (new_statuses, new_statements, new_asts) =
484         let statuses, statements = List.split entries in
485         let texts, asts = List.split statements in
486         statuses, texts, asts
487       in
488       history <- List.rev new_statuses @ history;
489       statements <- List.rev new_statements @ statements;
490       let start = buffer#get_iter_at_mark (`MARK locked_mark) in
491       let new_text = String.concat "" new_statements in
492       if statement <> None then
493        buffer#insert ~iter:start new_text
494       else
495         let s = match st with `Raw s | `Ast (_, s) -> s in
496         if new_text <> String.sub s 0 parsed_len then
497         begin
498           let stop = start#copy#forward_chars parsed_len in
499           buffer#delete ~start ~stop;
500           buffer#insert ~iter:start new_text;
501         end;
502       self#moveMark (String.length new_text);
503       (*
504       (match List.rev new_asts with (* advance again on punctuation *)
505       | TA.Executable (_, TA.Tactical (_, tac, _)) :: _ ->
506           let baseoffset =
507             (buffer#get_iter_at_mark (`MARK locked_mark))#offset
508           in
509           let text = self#getFuture in
510           (try
511             (match parse_statement baseoffset 0 buffer text with
512             | TA.Executable (loc, TA.Tactical (_, tac, None)) as st
513               when GrafiteAst.is_punctuation tac ->
514                 let len = snd (CicNotationPt.loc_of_floc loc) in
515                 aux (`Ast (st, String.sub text 0 len))
516             | _ -> ())
517           with CicNotationParser.Parse_error _ | End_of_file -> ())
518       | _ -> ())
519       *)
520     in
521     let s = match statement with Some s -> s | None -> self#getFuture in
522     MatitaLog.debug ("evaluating: " ^ first_line s ^ " ...");
523     (try aux (`Raw s) with End_of_file -> raise Margin)
524
525   method private _retract offset status new_statements new_history =
526     let cur_status = match history with s::_ -> s | [] -> assert false in
527     MatitaSync.time_travel ~present:cur_status ~past:status;
528     statements <- new_statements;
529     history <- new_history;
530     self#moveMark (- offset)
531
532   method advance ?statement () =
533     try
534       self#_advance ?statement ();
535       self#notify
536     with 
537     | Margin -> self#notify
538     | exc -> self#notify; raise exc
539
540   method retract () =
541     try
542       let cmp,new_statements,new_history,status =
543        match statements,history with
544           stat::statements, _::(status::_ as history) ->
545            String.length stat, statements, history, status
546        | [],[_] -> raise Margin
547        | _,_ -> assert false
548       in
549        self#_retract cmp status new_statements new_history;
550        self#notify
551     with 
552     | Margin -> self#notify
553     | exc -> self#notify; raise exc
554
555   method private getFuture =
556     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
557       ~stop:buffer#end_iter ()
558
559       
560   (** @param rel_offset relative offset from current position of locked_mark *)
561   method private moveMark rel_offset =
562     let mark = `MARK locked_mark in
563     let old_insert = buffer#get_iter_at_mark `INSERT in
564     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
565     let current_mark_pos = buffer#get_iter_at_mark mark in
566     let new_mark_pos =
567       match rel_offset with
568       | 0 -> current_mark_pos
569       | n when n > 0 -> current_mark_pos#forward_chars n
570       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
571     in
572     buffer#move_mark mark ~where:new_mark_pos;
573     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
574     buffer#move_mark `INSERT old_insert;
575     let mark_position = buffer#get_iter_at_mark mark in
576     if source_view#move_mark_onscreen mark then
577      begin
578       buffer#move_mark mark mark_position;
579       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
580      end;
581     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
582
583   method clean_dirty_lock =
584     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
585     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
586     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
587
588   val mutable observers = []
589
590   method addObserver (o: MatitaTypes.status -> unit) =
591     observers <- o :: observers
592
593   method private notify =
594     let status = self#status in
595     List.iter (fun o -> o status) observers
596
597   method loadFromFile f =
598     buffer#set_text (HExtlib.input_file f);
599     self#reset_buffer;
600     buffer#set_modified false
601     
602   method assignFileName file =
603     let abspath = MatitaMisc.absolute_path file in
604     let devel = MatitamakeLib.development_for_dir (Filename.dirname abspath) in
605     guistuff.filenamedata <- Some abspath, devel
606     
607   method saveToFile () =
608     let oc = open_out self#getFilename in
609     output_string oc (buffer#get_text ~start:buffer#start_iter
610                         ~stop:buffer#end_iter ());
611     close_out oc;
612     buffer#set_modified false
613   
614   method private _saveToBackupFile () =
615     if buffer#modified then
616       begin
617         let f = self#ppFilename ^ "~" in
618         let oc = open_out f in
619         output_string oc (buffer#get_text ~start:buffer#start_iter
620                             ~stop:buffer#end_iter ());
621         close_out oc;
622         MatitaLog.debug ("backup " ^ f ^ " saved")                    
623       end
624   
625   method private goto_top =
626     MatitaSync.time_travel ~present:self#status ~past:init
627
628   method private reset_buffer = 
629     statements <- [];
630     history <- [ init ];
631     userGoal <- ~-1;
632     self#notify;
633     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
634     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
635
636   method reset () =
637     self#reset_buffer;
638     source_buffer#begin_not_undoable_action ();
639     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
640     source_buffer#end_not_undoable_action ();
641     buffer#set_modified false
642   
643   method template () =
644     let template = HExtlib.input_file BuildTimeConf.script_template in 
645     buffer#insert ~iter:(buffer#get_iter `START) template;
646     guistuff.filenamedata <- 
647       (None,MatitamakeLib.development_for_dir (Unix.getcwd ()));
648     buffer#set_modified false;
649     set_star (Filename.basename self#ppFilename) false
650
651   method goto (pos: [`Top | `Bottom | `Cursor]) () =
652     let old_locked_mark =
653      `MARK
654        (buffer#create_mark ~name:"old_locked_mark"
655          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
656     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
657     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
658     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
659     match pos with
660     | `Top -> 
661         dispose_old_locked_mark (); 
662         self#goto_top; 
663         self#reset_buffer;
664         self#notify
665     | `Bottom ->
666         (try 
667           let rec dowhile () =
668             self#_advance ();
669             let newpos = getpos () in
670             if (getoldpos ())#compare newpos < 0 then
671               begin
672                 buffer#move_mark old_locked_mark newpos;
673                 dowhile ()
674               end
675           in
676           dowhile ();
677           dispose_old_locked_mark ();
678           self#notify 
679         with 
680         | Margin -> dispose_old_locked_mark (); self#notify
681         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
682     | `Cursor ->
683         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
684         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
685         let remember =
686          `MARK
687            (buffer#create_mark ~name:"initial_insert"
688              ~left_gravity:true (cursor_iter ())) in
689         let dispose_remember () = buffer#delete_mark remember in
690         let remember_iter () =
691          buffer#get_iter_at_mark (`NAME "initial_insert") in
692         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
693         let icmp = cmp () in
694         let forward_until_cursor () = (* go forward until locked > cursor *)
695           let rec aux () =
696             self#_advance ();
697             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
698             then
699              begin
700               buffer#move_mark old_locked_mark (getpos ());
701               aux ()
702              end
703           in
704           aux ()
705         in
706         let rec back_until_cursor len = (* go backward until locked < cursor *)
707          function
708             statements, (status::_ as history) when len <= 0 ->
709              self#_retract (icmp - len) status statements history
710           | statement::tl1, _::tl2 ->
711              back_until_cursor (len - String.length statement) (tl1,tl2)
712           | _,_ -> assert false
713         in
714         (try
715           begin
716            if icmp < 0 then       (* locked < cursor *)
717              (forward_until_cursor (); self#notify)
718            else if icmp > 0 then  (* locked > cursor *)
719              (back_until_cursor icmp (statements,history); self#notify)
720            else                  (* cursor = locked *)
721                ()
722           end ;
723           dispose_remember ();
724           dispose_old_locked_mark ();
725         with 
726         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
727         | exc -> dispose_remember (); dispose_old_locked_mark ();
728                  self#notify; raise exc)
729               
730   method onGoingProof () =
731     match self#status.proof_status with
732     | No_proof | Proof _ -> false
733     | Incomplete_proof _ -> true
734     | Intermediate _ -> assert false
735
736 (*   method proofStatus = MatitaTypes.get_proof_status self#status *)
737   method proofMetasenv = MatitaTypes.get_proof_metasenv self#status
738   method proofContext = MatitaTypes.get_proof_context self#status userGoal
739   method proofConclusion = MatitaTypes.get_proof_conclusion self#status userGoal
740   method stack = MatitaTypes.get_stack self#status
741   method setGoal n = userGoal <- n
742   method goal = userGoal
743
744   method eos = 
745     let s = self#getFuture in
746     let rec is_there_and_executable s = 
747       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
748       let st = GrafiteParser.parse_statement (Ulexing.from_utf8_string s) in
749       match st with
750       | GrafiteAst.Comment (loc,_)-> 
751           let parsed_text_length = snd (HExtlib.loc_of_floc loc) in
752           let remain_len = String.length s - parsed_text_length in
753           let next = String.sub s parsed_text_length remain_len in
754           is_there_and_executable next
755       | GrafiteAst.Executable (loc, ex) -> false
756     in
757     try
758       is_there_and_executable s
759     with 
760     | CicNotationParser.Parse_error _ -> false
761     | Margin | End_of_file -> true
762
763   (* debug *)
764   method dump () =
765     MatitaLog.debug "script status:";
766     MatitaLog.debug ("history size: " ^ string_of_int (List.length history));
767     MatitaLog.debug (sprintf "%d statements:" (List.length statements));
768     List.iter MatitaLog.debug statements;
769     MatitaLog.debug ("Current file name: " ^
770       (match guistuff.filenamedata with 
771       |None,_ -> "[ no name ]" 
772       | Some f,_ -> f));
773
774 end
775
776 let _script = ref None
777
778 let script ~source_view ~init ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
779 =
780   let s = new script 
781     ~source_view ~init ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
782   in
783   _script := Some s;
784   s
785
786 let current () = match !_script with None -> assert false | Some s -> s
787