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