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