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