]> matita.cs.unibo.it Git - helm.git/blob - helm/matita/matitaScript.ml
ocaml 3.09 transition
[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 advance ?statement () = script#advance ?statement () in
234   let parsed_text_length = String.length parsed_text in
235   let dbd = MatitaDb.instance () in
236   match mac with
237   (* WHELP's stuff *)
238   | TA.WMatch (loc, term) -> 
239       let term = disambiguate_macro_term term status user_goal in
240       let l =  MQ.match_term ~dbd term in
241       let query_url =
242         MatitaMisc.strip_suffix ~suffix:"."
243           (HExtlib.trim_blanks unparsed_text)
244       in
245       let entry = `Whelp (query_url, l) in
246       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
247       [], parsed_text_length
248   | TA.WInstance (loc, term) ->
249       let term = disambiguate_macro_term term status user_goal in
250       let l = MQ.instance ~dbd term in
251       let entry = `Whelp (TAPp.pp_macro_cic (TA.WInstance (loc, term)), l) in
252       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
253       [], parsed_text_length
254   | TA.WLocate (loc, s) -> 
255       let l = MQ.locate ~dbd s in
256       let entry = `Whelp (TAPp.pp_macro_cic (TA.WLocate (loc, s)), l) in
257       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
258       [], parsed_text_length
259   | TA.WElim (loc, term) ->
260       let term = disambiguate_macro_term term status user_goal in
261       let uri =
262         match term with
263         | Cic.MutInd (uri,n,_) -> UriManager.uri_of_uriref uri n None 
264         | _ -> failwith "Not a MutInd"
265       in
266       let l = MQ.elim ~dbd uri in
267       let entry = `Whelp (TAPp.pp_macro_cic (TA.WElim (loc, term)), l) in
268       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
269       [], parsed_text_length
270   | TA.WHint (loc, term) ->
271       let term = disambiguate_macro_term term status user_goal in
272       let s = ((None,[0,[],term], Cic.Meta (0,[]) ,term),0) in
273       let l = List.map fst (MQ.experimental_hint ~dbd s) in
274       let entry = `Whelp (TAPp.pp_macro_cic (TA.WHint (loc, term)), l) in
275       guistuff.mathviewer#show_uri_list ~reuse:true ~entry l;
276       [], parsed_text_length
277   (* REAL macro *)
278   | TA.Hint loc -> 
279       let proof = MatitaTypes.get_current_proof status in
280       let proof_status = proof, user_goal in
281       let l = List.map fst (MQ.experimental_hint ~dbd proof_status) in
282       let selected = guistuff.urichooser l in
283       (match selected with
284       | [] -> [], parsed_text_length
285       | [uri] -> 
286           let suri = UriManager.string_of_uri uri in
287           let ast = 
288             TA.Executable (loc, (TA.Tactical (loc,
289               TA.Tactic (loc,
290                 TA.Apply (loc, CicNotationPt.Uri (suri, None))),
291                 Some (TA.Dot loc))))
292           in
293         let new_status = MatitaEngine.eval_ast status ast in
294         let extra_text = 
295           comment parsed_text ^ 
296           "\n" ^ TAPp.pp_statement ast
297         in
298         [ new_status , (extra_text, ast) ], parsed_text_length
299       | _ -> 
300           MatitaLog.error 
301             "The result of the urichooser should be only 1 uri, not:\n";
302           List.iter (
303             fun u -> MatitaLog.error (UriManager.string_of_uri u ^ "\n")
304           ) selected;
305           assert false)
306   | TA.Check (_,term) ->
307       let metasenv = MatitaTypes.get_proof_metasenv status in
308       let context = MatitaTypes.get_proof_context status user_goal in
309       let interps = 
310         MatitaDisambiguator.disambiguate_term ~dbd ~context ~metasenv
311          ~aliases:status.aliases ~universe:(Some status.multi_aliases) term
312       in
313       let _, metasenv , term, ugraph =
314         match interps with 
315         | [x], _ -> x
316         | _ -> assert false
317       in
318       let ty,_ = CTC.type_of_aux' metasenv context term ugraph in
319       let t_and_ty = Cic.Cast (term,ty) in
320       guistuff.mathviewer#show_entry (`Cic (t_and_ty,metasenv));
321       [], parsed_text_length
322 (*   | TA.Abort _ -> 
323       let rec go_back () =
324         let status = script#status.proof_status in
325         match status with
326         | No_proof -> ()
327         | _ -> script#retract ();go_back()
328       in
329       [], parsed_text_length, Some go_back
330   | TA.Redo (_, Some i) ->  [], parsed_text_length, 
331       Some (fun () -> for j = 1 to i do advance () done)
332   | TA.Redo (_, None) ->   [], parsed_text_length, 
333       Some (fun () -> advance ())
334   | TA.Undo (_, Some i) ->  [], parsed_text_length, 
335       Some (fun () -> for j = 1 to i do script#retract () done)
336   | TA.Undo (_, None) -> [], parsed_text_length, 
337       Some (fun () -> script#retract ()) *)
338   (* TODO *)
339   | TA.Quit _ -> failwith "not implemented"
340   | TA.Print (_,kind) -> failwith "not implemented"
341   | TA.Search_pat (_, search_kind, str) -> failwith "not implemented"
342   | TA.Search_term (_, search_kind, term) -> failwith "not implemented"
343                                 
344 let eval_executable guistuff status user_goal unparsed_text parsed_text script
345   ex
346 =
347   let module TAPp = GrafiteAstPp in
348   let module MD = MatitaDisambiguator in
349   let module ML = MatitacleanLib in
350   let parsed_text_length = String.length parsed_text in
351   match ex with
352   | TA.Command (loc, _) | TA.Tactical (loc, _, _) ->
353       (try 
354         (match MatitaMisc.baseuri_of_baseuri_decl (TA.Executable (loc,ex)) with
355         | None -> ()
356         | Some u -> 
357             if not (MatitaMisc.is_empty u) then
358               match 
359                 guistuff.ask_confirmation 
360                   ~title:"Baseuri redefinition" 
361                   ~message:(
362                     "Baseuri " ^ u ^ " already exists.\n" ^
363                     "Do you want to redefine the corresponding "^
364                     "part of the library?")
365               with
366               | `YES -> MatitacleanLib.clean_baseuris [u]
367               | `NO -> ()
368               | `CANCEL -> raise MatitaTypes.Cancel);
369         eval_with_engine 
370           guistuff status user_goal parsed_text (TA.Executable (loc, ex))
371       with MatitaTypes.Cancel -> [], 0)
372   | TA.Macro (_,mac) ->
373       eval_macro guistuff status user_goal unparsed_text parsed_text script mac
374
375 let parse_statement baseoffset parsedlen ?error_tag (buffer: GText.buffer) text 
376 =
377   try
378     GrafiteParser.parse_statement (Ulexing.from_utf8_string text)
379   with CicNotationParser.Parse_error (floc, err) as exn ->
380     match error_tag with
381     | None -> raise exn
382     | Some error_tag ->
383         let (x, y) = CicNotationPt.loc_of_floc floc in
384         let x = parsedlen + x in
385         let y = parsedlen + y in
386         let x' = baseoffset + x in
387         let y' = baseoffset + y in
388         let x_iter = buffer#get_iter (`OFFSET x') in
389         let y_iter = buffer#get_iter (`OFFSET y') in
390         buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
391         let id = ref None in
392         id := Some (buffer#connect#changed ~callback:(fun () ->
393           buffer#remove_tag error_tag ~start:buffer#start_iter
394             ~stop:buffer#end_iter;
395           match !id with
396           | None -> assert false (* a race condition occurred *)
397           | Some id ->
398               (new GObj.gobject_ops buffer#as_buffer)#disconnect id));
399         let flocb,floce = floc in
400         let floc =
401           { flocb with Lexing.pos_cnum = x }, { floce with Lexing.pos_cnum = y }
402         in
403         buffer#place_cursor (buffer#get_iter (`OFFSET x'));
404         raise (CicNotationParser.Parse_error (floc, err))
405
406 let rec eval_statement baseoffset parsedlen error_tag (buffer : GText.buffer)
407  guistuff status user_goal script statement
408 =
409   let st, unparsed_text =
410     match statement with
411     | `Raw text ->
412         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
413         parse_statement baseoffset parsedlen ~error_tag buffer text, text
414     | `Ast (st, text) -> st, text
415   in
416   let text_of_loc loc =
417     let parsed_text_length = snd (CicNotationPt.loc_of_floc loc) in
418     let parsed_text = safe_substring unparsed_text 0 parsed_text_length in
419     parsed_text, parsed_text_length
420   in
421   match st with
422   | GrafiteAst.Comment (loc, _) -> 
423       let parsed_text, parsed_text_length = text_of_loc loc in
424       let remain_len = String.length unparsed_text - parsed_text_length in
425       let s = String.sub unparsed_text parsed_text_length remain_len in
426       let s,len = 
427         eval_statement baseoffset (parsedlen + parsed_text_length) error_tag
428          buffer guistuff status user_goal script (`Raw s)
429       in
430       (match s with
431       | (status, (text, ast)) :: tl ->
432           ((status, (parsed_text ^ text, ast))::tl), (parsed_text_length + len)
433       | [] -> [], 0)
434   | GrafiteAst.Executable (loc, ex) ->
435       let parsed_text, parsed_text_length = text_of_loc loc in
436       eval_executable guistuff status user_goal unparsed_text parsed_text
437         script ex 
438   
439 let fresh_script_id =
440   let i = ref 0 in
441   fun () -> incr i; !i
442
443 class script  ~(source_view: GSourceView.source_view)
444               ~(init: MatitaTypes.status) 
445               ~(mathviewer: MatitaTypes.mathViewer) 
446               ~set_star
447               ~ask_confirmation
448               ~urichooser 
449               ~develcreator 
450               () =
451 let buffer = source_view#buffer in
452 let source_buffer = source_view#source_buffer in
453 object (self)
454   val scriptId = fresh_script_id ()
455   
456   val guistuff = {
457     mathviewer = mathviewer;
458     urichooser = urichooser;
459     ask_confirmation = ask_confirmation;
460     develcreator = develcreator;
461     filenamedata = (None, None)} 
462   
463   method private getFilename =
464     match guistuff.filenamedata with Some f,_ -> f | _ -> assert false
465
466   method filename = self#getFilename
467     
468   method private ppFilename =
469     match guistuff.filenamedata with 
470     | Some f,_ -> f 
471     | None,_ -> sprintf ".unnamed%d.ma" scriptId
472   
473   initializer 
474     ignore (GMain.Timeout.add ~ms:300000 
475        ~callback:(fun _ -> self#_saveToBackupFile ();true));
476     ignore (buffer#connect#modified_changed 
477       (fun _ -> set_star (Filename.basename self#ppFilename) buffer#modified))
478
479   val mutable statements = [];    (** executed statements *)
480   val mutable history = [ init ];
481     (** list of states before having executed statements. Head element of this
482       * list is the current state, last element is the state at the beginning of
483       * the script.
484       * Invariant: this list length is 1 + length of statements *)
485
486   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
487   val mutable userGoal = ~-1
488
489   (** text mark and tag representing locked part of a script *)
490   val locked_mark =
491     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
492   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
493   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
494
495   method locked_mark = locked_mark
496   method locked_tag = locked_tag
497
498     (* history can't be empty, the invariant above grant that it contains at
499      * least the init status *)
500   method status = match history with hd :: _ -> hd | _ -> assert false
501
502   method private _advance ?statement () =
503     let rec aux st =
504       let baseoffset = (buffer#get_iter_at_mark (`MARK locked_mark))#offset in
505       let (entries, parsed_len) = 
506         eval_statement baseoffset 0 error_tag buffer guistuff self#status
507           userGoal self st
508       in
509       let (new_statuses, new_statements, new_asts) =
510         let statuses, statements = List.split entries in
511         let texts, asts = List.split statements in
512         statuses, texts, asts
513       in
514       history <- List.rev new_statuses @ history;
515       statements <- List.rev new_statements @ statements;
516       let start = buffer#get_iter_at_mark (`MARK locked_mark) in
517       let new_text = String.concat "" new_statements in
518       if statement <> None then
519        buffer#insert ~iter:start new_text
520       else
521         let s = match st with `Raw s | `Ast (_, s) -> s in
522         if new_text <> String.sub s 0 parsed_len then
523         begin
524           let stop = start#copy#forward_chars parsed_len in
525           buffer#delete ~start ~stop;
526           buffer#insert ~iter:start new_text;
527         end;
528       self#moveMark (String.length new_text);
529       (*
530       (match List.rev new_asts with (* advance again on punctuation *)
531       | TA.Executable (_, TA.Tactical (_, tac, _)) :: _ ->
532           let baseoffset =
533             (buffer#get_iter_at_mark (`MARK locked_mark))#offset
534           in
535           let text = self#getFuture in
536           (try
537             (match parse_statement baseoffset 0 ?error_tag:None buffer text with
538             | TA.Executable (loc, TA.Tactical (_, tac, None)) as st
539               when GrafiteAst.is_punctuation tac ->
540                 let len = snd (CicNotationPt.loc_of_floc loc) in
541                 aux (`Ast (st, String.sub text 0 len))
542             | _ -> ())
543           with CicNotationParser.Parse_error _ | End_of_file -> ())
544       | _ -> ())
545       *)
546     in
547     let s = match statement with Some s -> s | None -> self#getFuture in
548     MatitaLog.debug ("evaluating: " ^ first_line s ^ " ...");
549     (try aux (`Raw s) with End_of_file -> raise Margin)
550
551   method private _retract offset status new_statements new_history =
552     let cur_status = match history with s::_ -> s | [] -> assert false in
553     MatitaSync.time_travel ~present:cur_status ~past:status;
554     statements <- new_statements;
555     history <- new_history;
556     self#moveMark (- offset)
557
558   method advance ?statement () =
559     try
560       self#_advance ?statement ();
561       self#notify
562     with 
563     | Margin -> self#notify
564     | exc -> self#notify; raise exc
565
566   method retract () =
567     try
568       let cmp,new_statements,new_history,status =
569        match statements,history with
570           stat::statements, _::(status::_ as history) ->
571            String.length stat, statements, history, status
572        | [],[_] -> raise Margin
573        | _,_ -> assert false
574       in
575        self#_retract cmp status new_statements new_history;
576        self#notify
577     with 
578     | Margin -> self#notify
579     | exc -> self#notify; raise exc
580
581   method private getFuture =
582     buffer#get_text ~start:(buffer#get_iter_at_mark (`MARK locked_mark))
583       ~stop:buffer#end_iter ()
584
585       
586   (** @param rel_offset relative offset from current position of locked_mark *)
587   method private moveMark rel_offset =
588     let mark = `MARK locked_mark in
589     let old_insert = buffer#get_iter_at_mark `INSERT in
590     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
591     let current_mark_pos = buffer#get_iter_at_mark mark in
592     let new_mark_pos =
593       match rel_offset with
594       | 0 -> current_mark_pos
595       | n when n > 0 -> current_mark_pos#forward_chars n
596       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
597     in
598     buffer#move_mark mark ~where:new_mark_pos;
599     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
600     buffer#move_mark `INSERT old_insert;
601     let mark_position = buffer#get_iter_at_mark mark in
602     if source_view#move_mark_onscreen mark then
603      begin
604       buffer#move_mark mark mark_position;
605       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
606      end;
607     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
608
609   method clean_dirty_lock =
610     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
611     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
612     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
613
614   val mutable observers = []
615
616   method addObserver (o: MatitaTypes.status -> unit) =
617     observers <- o :: observers
618
619   method private notify =
620     let status = self#status in
621     List.iter (fun o -> o status) observers
622
623   method loadFromFile f =
624     buffer#set_text (HExtlib.input_file f);
625     self#reset_buffer;
626     buffer#set_modified false
627     
628   method assignFileName file =
629     let abspath = MatitaMisc.absolute_path file in
630     let devel = MatitamakeLib.development_for_dir (Filename.dirname abspath) in
631     guistuff.filenamedata <- Some abspath, devel
632     
633   method saveToFile () =
634     let oc = open_out self#getFilename in
635     output_string oc (buffer#get_text ~start:buffer#start_iter
636                         ~stop:buffer#end_iter ());
637     close_out oc;
638     buffer#set_modified false
639   
640   method private _saveToBackupFile () =
641     if buffer#modified then
642       begin
643         let f = self#ppFilename ^ "~" in
644         let oc = open_out f in
645         output_string oc (buffer#get_text ~start:buffer#start_iter
646                             ~stop:buffer#end_iter ());
647         close_out oc;
648         MatitaLog.debug ("backup " ^ f ^ " saved")                    
649       end
650   
651   method private goto_top =
652     MatitaSync.time_travel ~present:self#status ~past:init
653
654   method private reset_buffer = 
655     statements <- [];
656     history <- [ init ];
657     userGoal <- ~-1;
658     self#notify;
659     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
660     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
661
662   method reset () =
663     self#reset_buffer;
664     source_buffer#begin_not_undoable_action ();
665     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
666     source_buffer#end_not_undoable_action ();
667     buffer#set_modified false
668   
669   method template () =
670     let template = HExtlib.input_file BuildTimeConf.script_template in 
671     buffer#insert ~iter:(buffer#get_iter `START) template;
672     guistuff.filenamedata <- 
673       (None,MatitamakeLib.development_for_dir (Unix.getcwd ()));
674     buffer#set_modified false;
675     set_star (Filename.basename self#ppFilename) false
676
677   method goto (pos: [`Top | `Bottom | `Cursor]) () =
678     let old_locked_mark =
679      `MARK
680        (buffer#create_mark ~name:"old_locked_mark"
681          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
682     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
683     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
684     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
685     match pos with
686     | `Top -> 
687         dispose_old_locked_mark (); 
688         self#goto_top; 
689         self#reset_buffer;
690         self#notify
691     | `Bottom ->
692         (try 
693           let rec dowhile () =
694             self#_advance ();
695             let newpos = getpos () in
696             if (getoldpos ())#compare newpos < 0 then
697               begin
698                 buffer#move_mark old_locked_mark newpos;
699                 dowhile ()
700               end
701           in
702           dowhile ();
703           dispose_old_locked_mark ();
704           self#notify 
705         with 
706         | Margin -> dispose_old_locked_mark (); self#notify
707         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
708     | `Cursor ->
709         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
710         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
711         let remember =
712          `MARK
713            (buffer#create_mark ~name:"initial_insert"
714              ~left_gravity:true (cursor_iter ())) in
715         let dispose_remember () = buffer#delete_mark remember in
716         let remember_iter () =
717          buffer#get_iter_at_mark (`NAME "initial_insert") in
718         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
719         let icmp = cmp () in
720         let forward_until_cursor () = (* go forward until locked > cursor *)
721           let rec aux () =
722             self#_advance ();
723             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
724             then
725              begin
726               buffer#move_mark old_locked_mark (getpos ());
727               aux ()
728              end
729           in
730           aux ()
731         in
732         let rec back_until_cursor len = (* go backward until locked < cursor *)
733          function
734             statements, (status::_ as history) when len <= 0 ->
735              self#_retract (icmp - len) status statements history
736           | statement::tl1, _::tl2 ->
737              back_until_cursor (len - String.length statement) (tl1,tl2)
738           | _,_ -> assert false
739         in
740         (try
741           begin
742            if icmp < 0 then       (* locked < cursor *)
743              (forward_until_cursor (); self#notify)
744            else if icmp > 0 then  (* locked > cursor *)
745              (back_until_cursor icmp (statements,history); self#notify)
746            else                  (* cursor = locked *)
747                ()
748           end ;
749           dispose_remember ();
750           dispose_old_locked_mark ();
751         with 
752         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
753         | exc -> dispose_remember (); dispose_old_locked_mark ();
754                  self#notify; raise exc)
755               
756   method onGoingProof () =
757     match self#status.proof_status with
758     | No_proof | Proof _ -> false
759     | Incomplete_proof _ -> true
760     | Intermediate _ -> assert false
761
762 (*   method proofStatus = MatitaTypes.get_proof_status self#status *)
763   method proofMetasenv = MatitaTypes.get_proof_metasenv self#status
764   method proofContext = MatitaTypes.get_proof_context self#status userGoal
765   method proofConclusion = MatitaTypes.get_proof_conclusion self#status userGoal
766   method stack = MatitaTypes.get_stack self#status
767   method setGoal n = userGoal <- n
768   method goal = userGoal
769
770   method eos = 
771     let s = self#getFuture in
772     let rec is_there_and_executable s = 
773       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
774       let st = GrafiteParser.parse_statement (Ulexing.from_utf8_string s) in
775       match st with
776       | GrafiteAst.Comment (loc,_)-> 
777           let parsed_text_length = snd (CicNotationPt.loc_of_floc loc) in
778           let remain_len = String.length s - parsed_text_length in
779           let next = String.sub s parsed_text_length remain_len in
780           is_there_and_executable next
781       | GrafiteAst.Executable (loc, ex) -> false
782     in
783     try
784       is_there_and_executable s
785     with 
786     | CicNotationParser.Parse_error _ -> false
787     | Margin | End_of_file -> true
788
789   (* debug *)
790   method dump () =
791     MatitaLog.debug "script status:";
792     MatitaLog.debug ("history size: " ^ string_of_int (List.length history));
793     MatitaLog.debug (sprintf "%d statements:" (List.length statements));
794     List.iter MatitaLog.debug statements;
795     MatitaLog.debug ("Current file name: " ^
796       (match guistuff.filenamedata with 
797       |None,_ -> "[ no name ]" 
798       | Some f,_ -> f));
799
800 end
801
802 let _script = ref None
803
804 let script ~source_view ~init ~mathviewer ~urichooser ~develcreator ~ask_confirmation ~set_star ()
805 =
806   let s = new script 
807     ~source_view ~init ~mathviewer ~ask_confirmation ~urichooser ~develcreator ~set_star () 
808   in
809   _script := Some s;
810   s
811
812 let current () = match !_script with None -> assert false | Some s -> s
813