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