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