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