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