]> matita.cs.unibo.it Git - helm.git/blob - matita/matita/matitaScript.ml
Propagation of changes to grafiteAst.
[helm.git] / matita / 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 let comment_RE = Pcre.regexp "\\(\\*(.|\n)*\\*\\)\n?" ~flags:[`UNGREEDY]
50  
51 let comment str =
52   if Pcre.pmatch ~rex:multiline_RE str then
53     "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " *)"
54   else
55     "\n(**\n" ^ str ^ "\n*)"
56
57 let strip_comments str =
58   Pcre.qreplace ~templ:"\n" ~pat:"\n\n" (Pcre.qreplace ~rex:comment_RE str)
59 ;;
60                      
61 let first_line s =
62   let s = Pcre.replace ~rex:heading_nl_RE s in
63   try
64     let nl_pos = String.index s '\n' in
65     String.sub s 0 nl_pos
66   with Not_found -> s
67
68 type guistuff = {
69   mathviewer:MatitaTypes.mathViewer;
70   urichooser: UriManager.uri list -> UriManager.uri list;
71   ask_confirmation: title:string -> message:string -> [`YES | `NO | `CANCEL];
72 }
73
74 let eval_with_engine include_paths guistuff grafite_status user_goal
75  skipped_txt nonskipped_txt st
76 =
77   let parsed_text_length =
78     String.length skipped_txt + String.length nonskipped_txt 
79   in
80   let text = skipped_txt ^ nonskipped_txt in
81   let prefix_len = MatitaGtkMisc.utf8_string_length skipped_txt in
82   let enriched_history_fragment =
83    MatitaEngine.eval_ast ~do_heavy_checks:(Helm_registry.get_bool
84      "matita.do_heavy_checks")
85     grafite_status (text,prefix_len,st)
86   in
87   let enriched_history_fragment = List.rev enriched_history_fragment in
88   (* really fragile *)
89   let res,_ = 
90     List.fold_left 
91       (fun (acc, to_prepend) (status,alias) ->
92        match alias with
93        | None -> (status,to_prepend ^ nonskipped_txt)::acc,""
94        | Some (k,value) ->
95             let newtxt = LexiconAstPp.pp_alias value in
96             (status,to_prepend ^ newtxt ^ "\n")::acc, "")
97       ([],skipped_txt) enriched_history_fragment
98   in
99   res,"",parsed_text_length
100 ;;
101
102 (* this function calls the parser in a way that it does not perform inclusions,
103  * so that we can ensure the inclusion is performed after the included file 
104  * is compiled (if needed). matitac does not need that, since it compiles files
105  * in the good order, here files may be compiled on demand. *)
106 let wrap_with_make include_paths (f : #LexiconEngine.status GrafiteParser.statement) x = 
107   try      
108     f ~never_include:true ~include_paths x
109   with
110   | GrafiteParser.NoInclusionPerformed mafilename ->
111       let root, buri, _, tgt = 
112         try Librarian.baseuri_of_script ~include_paths mafilename
113         with Librarian.NoRootFor _ -> 
114           HLog.error ("The included file '"^mafilename^"' has no root file,");
115           HLog.error "please create it.";
116           raise (Failure ("No root file for "^mafilename))
117       in
118       let b = MatitacLib.Make.make root [tgt] in
119       if b then 
120         try f ~include_paths x with LexiconEngine.IncludedFileNotCompiled _ ->
121          raise 
122            (Failure ("Including: "^tgt^
123              "\nNothing to do... did you run matitadep?"))
124       else raise (Failure ("Compiling: " ^ tgt))
125 ;;
126
127 let pp_eager_statement_ast = GrafiteAstPp.pp_statement 
128
129 let eval_nmacro include_paths (buffer : GText.buffer) guistuff grafite_status user_goal unparsed_text parsed_text script mac =
130   let parsed_text_length = String.length parsed_text in
131   match mac with
132   | TA.Screenshot (_,name) -> 
133        let status = script#grafite_status in
134        let _,_,menv,subst,_ = status#obj in
135        let name = Filename.dirname (script#filename) ^ "/" ^ name in
136        let sequents = 
137          let selected = Continuationals.Stack.head_goals status#stack in
138          List.filter (fun x,_ -> List.mem x selected) menv         
139        in
140        guistuff.mathviewer#screenshot status sequents menv subst name;
141        [status, parsed_text], "", parsed_text_length
142   | TA.NCheck (_,t) ->
143       let status = script#grafite_status in
144       let _,_,menv,subst,_ = status#obj in
145       let ctx = 
146         try let _,(_,ctx,_) = List.hd menv in ctx
147         with Failure "hd" -> []
148       in
149       let m, s, status, t = 
150         GrafiteDisambiguate.disambiguate_nterm 
151           None status ctx menv subst (parsed_text,parsed_text_length,
152             NotationPt.Cast (t,NotationPt.Implicit `JustOne))  
153           (* XXX use the metasenv, if possible *)
154       in
155       guistuff.mathviewer#show_entry (`NCic (t,ctx,m,s));
156       [status, parsed_text], "", parsed_text_length
157   | TA.NIntroGuess _loc ->
158       let names_ref = ref [] in
159       let s = 
160         NTactics.intros_tac ~names_ref [] script#grafite_status 
161       in
162       let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
163       let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
164       [s, nl ^ "#" ^ String.concat " " !names_ref ^ ";"], "", parsed_text_length
165   | TA.NAutoInteractive (_loc, (None,a)) -> 
166       let trace_ref = ref [] in
167       let s = 
168         NnAuto.auto_tac 
169           ~params:(None,a) ~trace_ref script#grafite_status 
170       in
171       let depth = 
172         try List.assoc "depth" a
173         with Not_found -> ""
174       in
175       let trace = "/"^(if int_of_string depth > 1 then depth else "")^"/ by " in
176       let thms = 
177         match !trace_ref with
178         | [] -> "{}"
179         | thms -> 
180            String.concat ", "  
181              (HExtlib.filter_map (function 
182                | NotationPt.NRef r -> Some (NCicPp.r2s true r) 
183                | _ -> None) 
184              thms)
185       in
186       let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
187       let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
188       [s, nl ^ trace ^ thms ^ ";"], "", parsed_text_length
189   | TA.NAutoInteractive (_, (Some _,_)) -> assert false
190
191 let rec eval_executable include_paths (buffer : GText.buffer) guistuff
192 grafite_status user_goal unparsed_text skipped_txt nonskipped_txt
193 script ex loc
194 =
195   try
196    ignore (buffer#move_mark (`NAME "beginning_of_statement")
197     ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
198        (Glib.Utf8.length skipped_txt))) ;
199    eval_with_engine include_paths 
200     guistuff grafite_status user_goal skipped_txt nonskipped_txt
201      (TA.Executable (loc, ex))
202   with
203      MatitaTypes.Cancel -> [], "", 0
204    | GrafiteEngine.NMacro (_loc,macro) ->
205        eval_nmacro include_paths buffer guistuff grafite_status
206         user_goal unparsed_text (skipped_txt ^ nonskipped_txt) script macro
207
208
209 and eval_statement include_paths (buffer : GText.buffer) guistuff 
210  grafite_status user_goal script statement
211 =
212   let (grafite_status,st), unparsed_text =
213     match statement with
214     | `Raw text ->
215         if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
216         let ast = 
217          wrap_with_make include_paths
218           (GrafiteParser.parse_statement (Ulexing.from_utf8_string text)) 
219             grafite_status
220         in
221           ast, text
222     | `Ast (st, text) -> (grafite_status, st), text
223   in
224   let text_of_loc floc = 
225     let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
226     let start, stop = HExtlib.loc_of_floc floc in 
227     let floc = HExtlib.floc_of_loc (0, start) in
228     let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
229     let floc = HExtlib.floc_of_loc (0, stop) in
230     let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
231     txt,nonskipped_txt,skipped_txt,len
232   in 
233   match st with
234   | GrafiteParser.LNone loc ->
235       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
236        [grafite_status,parsed_text],"",
237         parsed_text_length
238   | GrafiteParser.LSome (GrafiteAst.Executable (loc, ex)) ->
239      let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
240       eval_executable include_paths buffer guistuff 
241        grafite_status user_goal unparsed_text skipped nonskipped script ex loc
242   | GrafiteParser.LSome (GrafiteAst.Comment (loc, GrafiteAst.Code (_, ex))) 
243     when Helm_registry.get_bool "matita.execcomments" ->
244      let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
245       eval_executable include_paths buffer guistuff 
246        grafite_status user_goal unparsed_text skipped nonskipped script ex loc
247   | GrafiteParser.LSome (GrafiteAst.Comment (loc, _)) -> 
248       let parsed_text, _, _, parsed_text_length = text_of_loc loc in
249       let remain_len = String.length unparsed_text - parsed_text_length in
250       let s = String.sub unparsed_text parsed_text_length remain_len in
251       let s,text,len = 
252        try
253         eval_statement include_paths buffer guistuff 
254          grafite_status user_goal script (`Raw s)
255        with
256           HExtlib.Localized (floc, exn) ->
257            HExtlib.raise_localized_exception 
258              ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
259         | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
260            raise
261             (MultiPassDisambiguator.DisambiguationError
262               (offset+parsed_text_length, errorll))
263       in
264       assert (text=""); (* no macros inside comments, please! *)
265       (match s with
266       | (statuses,text)::tl ->
267          (statuses,parsed_text ^ text)::tl,"",parsed_text_length + len
268       | [] -> [], "", 0)
269   
270 let fresh_script_id =
271   let i = ref 0 in
272   fun () -> incr i; !i
273
274 class script  ~(source_view: GSourceView2.source_view)
275               ~(mathviewer: MatitaTypes.mathViewer) 
276               ~set_star
277               ~ask_confirmation
278               ~urichooser 
279               () =
280 let buffer = source_view#buffer in
281 let source_buffer = source_view#source_buffer in
282 let initial_statuses current baseuri =
283  let empty_lstatus = new LexiconEngine.status in
284  (match current with
285      Some current ->
286       LexiconSync.time_travel ~present:current ~past:empty_lstatus;
287       GrafiteSync.time_travel ~present:current ();
288       (* CSC: there is a known bug in invalidation; temporary fix here *)
289       NCicEnvironment.invalidate ()
290    | None -> ());
291  let lexicon_status =
292    CicNotation2.load_notation ~include_paths:[] empty_lstatus
293      BuildTimeConf.core_notation_script 
294  in
295  let grafite_status = GrafiteSync.init lexicon_status baseuri in
296   grafite_status
297 in
298 let read_include_paths file =
299  try 
300    let root, _buri, _fname, _tgt = 
301      Librarian.baseuri_of_script ~include_paths:[] file 
302    in 
303    let rc = 
304     Str.split (Str.regexp " ") 
305      (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
306    in
307    List.iter (HLog.debug) rc; rc
308  with Librarian.NoRootFor _ | Not_found -> []
309 in
310 let default_buri = "cic:/matita/tests" in
311 let default_fname = ".unnamed.ma" in
312 object (self)
313   val mutable include_paths_ = []
314
315   val scriptId = fresh_script_id ()
316
317   val guistuff = {
318     mathviewer = mathviewer;
319     urichooser = urichooser;
320     ask_confirmation = ask_confirmation;
321   }
322
323   val mutable filename_ = (None : string option)
324
325   method has_name = filename_ <> None
326   
327   method include_paths =
328     include_paths_ @ 
329     Helm_registry.get_list Helm_registry.string "matita.includes"
330
331   method private curdir =
332     try
333      let root, _buri, _fname, _tgt = 
334        Librarian.baseuri_of_script ~include_paths:self#include_paths
335        self#filename 
336      in 
337      root
338     with Librarian.NoRootFor _ -> Sys.getcwd ()
339
340   method buri_of_current_file =
341     match filename_ with
342     | None -> default_buri 
343     | Some f ->
344         try 
345           let _root, buri, _fname, _tgt = 
346             Librarian.baseuri_of_script ~include_paths:self#include_paths f 
347           in 
348           buri
349         with Librarian.NoRootFor _ -> default_buri
350
351   method filename = match filename_ with None -> default_fname | Some f -> f
352
353   initializer 
354     ignore (GMain.Timeout.add ~ms:300000 
355        ~callback:(fun _ -> self#_saveToBackupFile ();true));
356     ignore (buffer#connect#modified_changed 
357       (fun _ -> set_star buffer#modified))
358
359   val mutable statements = []    (** executed statements *)
360
361   val mutable history = [ initial_statuses None default_buri ]
362     (** list of states before having executed statements. Head element of this
363       * list is the current state, last element is the state at the beginning of
364       * the script.
365       * Invariant: this list length is 1 + length of statements *)
366
367   (** goal as seen by the user (i.e. metano corresponding to current tab) *)
368   val mutable userGoal = (None : int option)
369
370   (** text mark and tag representing locked part of a script *)
371   val locked_mark =
372     buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
373   val beginning_of_statement_mark =
374     buffer#create_mark ~name:"beginning_of_statement"
375      ~left_gravity:true buffer#start_iter
376   val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
377   val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
378
379   method locked_mark = locked_mark
380   method locked_tag = locked_tag
381   method error_tag = error_tag
382
383     (* history can't be empty, the invariant above grant that it contains at
384      * least the init grafite_status *)
385   method grafite_status = match history with s::_ -> s | _ -> assert false
386
387   method private _advance ?statement () =
388    let s = match statement with Some s -> s | None -> self#getFuture in
389    if self#bos then LibraryClean.clean_baseuris [self#buri_of_current_file];
390    HLog.debug ("evaluating: " ^ first_line s ^ " ...");
391    let time1 = Unix.gettimeofday () in
392    let entries, newtext, parsed_len = 
393     try
394      eval_statement self#include_paths buffer guistuff
395       self#grafite_status userGoal self (`Raw s)
396     with End_of_file -> raise Margin
397    in
398    let time2 = Unix.gettimeofday () in
399    HLog.debug ("... done in " ^ string_of_float (time2 -. time1) ^ "s");
400    let new_statuses, new_statements =
401      let statuses, texts = List.split entries in
402      statuses, texts
403    in
404    history <- new_statuses @ history;
405    statements <- new_statements @ statements;
406    let start = buffer#get_iter_at_mark (`MARK locked_mark) in
407    let new_text = String.concat "" (List.rev new_statements) in
408    if statement <> None then
409      buffer#insert ~iter:start new_text
410    else begin
411      let parsed_text = String.sub s 0 parsed_len in
412      if new_text <> parsed_text then begin
413        let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
414        buffer#delete ~start ~stop;
415        buffer#insert ~iter:start new_text;
416      end;
417    end;
418    self#moveMark (Glib.Utf8.length new_text);
419    buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext;
420    (* here we need to set the Goal in case we are going to cursor (or to
421       bottom) and we will face a macro *)
422     userGoal <- None
423
424   method private _retract offset grafite_status new_statements
425    new_history
426   =
427    let cur_grafite_status =
428     match history with s::_ -> s | [] -> assert false
429    in
430     LexiconSync.time_travel ~present:cur_grafite_status ~past:grafite_status;
431     GrafiteSync.time_travel ~present:cur_grafite_status ~past:grafite_status ();
432     statements <- new_statements;
433     history <- new_history;
434     self#moveMark (- offset)
435
436   method advance ?statement () =
437     try
438       self#_advance ?statement ();
439       self#notify
440     with 
441     | Margin -> self#notify
442     | Not_found -> assert false
443     | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
444     | exc -> self#notify; raise exc
445
446   method retract () =
447     try
448       let cmp,new_statements,new_history,grafite_status =
449        match statements,history with
450           stat::statements, _::(status::_ as history) ->
451            assert (Glib.Utf8.validate stat);
452            Glib.Utf8.length stat, statements, history, status
453        | [],[_] -> raise Margin
454        | _,_ -> assert false
455       in
456        self#_retract cmp grafite_status new_statements
457         new_history;
458        self#notify
459     with 
460     | Margin -> self#notify
461     | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
462     | exc -> self#notify; raise exc
463
464   method private getFuture =
465     let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
466     let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
467     text
468
469   method expandAllVirtuals =
470     let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
471     let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
472     buffer#delete ~start:lock ~stop:buffer#end_iter;
473     let text = Pcre.replace ~pat:":=" ~templ:"\\def" text in
474     let text = Pcre.replace ~pat:"->" ~templ:"\\to" text in
475     let text = Pcre.replace ~pat:"=>" ~templ:"\\Rightarrow" text in
476     let text = 
477       Pcre.substitute_substrings 
478         ~subst:(fun str -> 
479            let pristine = Pcre.get_substring str 0 in
480            let input = 
481              if pristine.[0] = ' ' then
482                String.sub pristine 1 (String.length pristine -1) 
483              else pristine 
484            in
485            let input = 
486              if input.[String.length input-1] = ' ' then
487                String.sub input 0 (String.length input -1) 
488              else input
489            in
490            let before, after =  
491              if input = "\\forall" || 
492                 input = "\\lambda" || 
493                 input = "\\exists" then "","" else " ", " " 
494            in
495            try 
496              before ^ Glib.Utf8.from_unichar 
497                (snd (Virtuals.symbol_of_virtual input)) ^ after
498            with Virtuals.Not_a_virtual -> pristine) 
499         ~pat:" ?\\\\[a-zA-Z]+ ?" text
500     in
501     buffer#insert ~iter:lock text
502       
503   (** @param rel_offset relative offset from current position of locked_mark *)
504   method private moveMark rel_offset =
505     let mark = `MARK locked_mark in
506     let old_insert = buffer#get_iter_at_mark `INSERT in
507     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
508     let current_mark_pos = buffer#get_iter_at_mark mark in
509     let new_mark_pos =
510       match rel_offset with
511       | 0 -> current_mark_pos
512       | n when n > 0 -> current_mark_pos#forward_chars n
513       | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
514     in
515     buffer#move_mark mark ~where:new_mark_pos;
516     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
517     buffer#move_mark `INSERT old_insert;
518     let mark_position = buffer#get_iter_at_mark mark in
519     if source_view#move_mark_onscreen mark then
520      begin
521       buffer#move_mark mark mark_position;
522       source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
523      end;
524     while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
525
526   method clean_dirty_lock =
527     let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
528     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
529     buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
530
531   val mutable observers = []
532
533   method addObserver (o: GrafiteTypes.status -> unit) =
534     observers <- o :: observers
535
536   method private notify =
537     let grafite_status = self#grafite_status in
538     List.iter (fun o -> o grafite_status) observers
539
540   method loadFromString s =
541     buffer#set_text s;
542     self#reset_buffer;
543     buffer#set_modified true
544
545   method loadFromFile f =
546     buffer#set_text (HExtlib.input_file f);
547     self#reset_buffer;
548     buffer#set_modified false
549
550   method assignFileName file =
551     let file = 
552       match file with 
553       | Some f -> Some (Librarian.absolutize f)
554       | None -> None
555     in
556     filename_ <- file; 
557     include_paths_ <- 
558       (match file with Some file -> read_include_paths file | None -> []);
559     self#reset_buffer;
560     Sys.chdir self#curdir;
561     HLog.debug ("Moving to " ^ Sys.getcwd ())
562     
563   method saveToFile () =
564     if self#has_name then
565       let oc = open_out self#filename in
566       output_string oc (buffer#get_text ~start:buffer#start_iter
567                         ~stop:buffer#end_iter ());
568       close_out oc;
569       set_star false;
570       buffer#set_modified false
571     else
572       HLog.error "Can't save, no filename selected"
573   
574   method private _saveToBackupFile () =
575     if buffer#modified then
576       begin
577         let f = self#filename in
578         let oc = open_out f in
579         output_string oc (buffer#get_text ~start:buffer#start_iter
580                             ~stop:buffer#end_iter ());
581         close_out oc;
582         HLog.debug ("backup " ^ f ^ " saved")                    
583       end
584   
585   method private reset_buffer = 
586     statements <- [];
587     history <- [ initial_statuses (Some self#grafite_status) self#buri_of_current_file ];
588     userGoal <- None;
589     self#notify;
590     buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
591     buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
592
593   method reset () =
594     self#reset_buffer;
595     source_buffer#begin_not_undoable_action ();
596     buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
597     source_buffer#end_not_undoable_action ();
598     buffer#set_modified false;
599   
600   method template () =
601     let template = HExtlib.input_file BuildTimeConf.script_template in 
602     buffer#insert ~iter:(buffer#get_iter `START) template;
603     buffer#set_modified false;
604     set_star false
605
606   method goto (pos: [`Top | `Bottom | `Cursor]) () =
607   try  
608     let old_locked_mark =
609      `MARK
610        (buffer#create_mark ~name:"old_locked_mark"
611          ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
612     let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in 
613     let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in 
614     let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
615     match pos with
616     | `Top -> 
617         dispose_old_locked_mark (); 
618         self#reset_buffer;
619         self#notify
620     | `Bottom ->
621         (try 
622           let rec dowhile () =
623             self#_advance ();
624             let newpos = getpos () in
625             if (getoldpos ())#compare newpos < 0 then
626               begin
627                 buffer#move_mark old_locked_mark newpos;
628                 dowhile ()
629               end
630           in
631           dowhile ();
632           dispose_old_locked_mark ();
633           self#notify 
634         with 
635         | Margin -> dispose_old_locked_mark (); self#notify
636         | exc -> dispose_old_locked_mark (); self#notify; raise exc)
637     | `Cursor ->
638         let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
639         let cursor_iter () = buffer#get_iter_at_mark `INSERT in
640         let remember =
641          `MARK
642            (buffer#create_mark ~name:"initial_insert"
643              ~left_gravity:true (cursor_iter ())) in
644         let dispose_remember () = buffer#delete_mark remember in
645         let remember_iter () =
646          buffer#get_iter_at_mark (`NAME "initial_insert") in
647         let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
648         let icmp = cmp () in
649         let forward_until_cursor () = (* go forward until locked > cursor *)
650           let rec aux () =
651             self#_advance ();
652             if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0 
653             then
654              begin
655               buffer#move_mark old_locked_mark (getpos ());
656               aux ()
657              end
658           in
659           aux ()
660         in
661         let rec back_until_cursor len = (* go backward until locked < cursor *)
662          function
663             statements, ((grafite_status)::_ as history)
664             when len <= 0 ->
665              self#_retract (icmp - len) grafite_status statements
666               history
667           | statement::tl1, _::tl2 ->
668              back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
669           | _,_ -> assert false
670         in
671         (try
672           begin
673            if icmp < 0 then       (* locked < cursor *)
674              (forward_until_cursor (); self#notify)
675            else if icmp > 0 then  (* locked > cursor *)
676              (back_until_cursor icmp (statements,history); self#notify)
677            else                  (* cursor = locked *)
678                ()
679           end ;
680           dispose_remember ();
681           dispose_old_locked_mark ();
682         with 
683         | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
684         | exc -> dispose_remember (); dispose_old_locked_mark ();
685                  self#notify; raise exc)
686   with Invalid_argument "Array.make" ->
687      HLog.error "The script is too big!\n"
688   
689   method stack = (assert false : Continuationals.Stack.t) (* MATITA 1.0 GrafiteTypes.get_stack
690   self#grafite_status *)
691   method setGoal n = userGoal <- n
692   method goal = userGoal
693
694   method bos = 
695     match history with
696     | _::[] -> true
697     | _ -> false
698
699   method eos = 
700     let rec is_there_only_comments lexicon_status s = 
701       if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
702       let lexicon_status,st =
703        GrafiteParser.parse_statement (Ulexing.from_utf8_string s)
704         ~include_paths:self#include_paths lexicon_status
705       in
706       match st with
707       | GrafiteParser.LSome (GrafiteAst.Comment (loc,_)) -> 
708           let _,parsed_text_length = MatitaGtkMisc.utf8_parsed_text s loc in
709           (* CSC: why +1 in the following lines ???? *)
710           let parsed_text_length = parsed_text_length + 1 in
711           let remain_len = String.length s - parsed_text_length in
712           let next = String.sub s parsed_text_length remain_len in
713           is_there_only_comments lexicon_status next
714       | GrafiteParser.LNone _
715       | GrafiteParser.LSome (GrafiteAst.Executable _) -> false
716     in
717     try is_there_only_comments self#grafite_status self#getFuture
718     with 
719     | LexiconEngine.IncludedFileNotCompiled _
720     | HExtlib.Localized _
721     | CicNotationParser.Parse_error _ -> false
722     | Margin | End_of_file -> true
723     | Invalid_argument "Array.make" -> false
724
725   (* debug *)
726   method dump () =
727     HLog.debug "script status:";
728     HLog.debug ("history size: " ^ string_of_int (List.length history));
729     HLog.debug (sprintf "%d statements:" (List.length statements));
730     List.iter HLog.debug statements;
731     HLog.debug ("Current file name: " ^ self#filename);
732 end
733
734 let _script = ref None
735
736 let script ~source_view ~mathviewer ~urichooser ~ask_confirmation ~set_star ()
737 =
738   let s = new script 
739     ~source_view ~mathviewer ~ask_confirmation ~urichooser ~set_star () 
740   in
741   _script := Some s;
742   s
743
744 let current () = match !_script with None -> assert false | Some s -> s
745