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