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