1 (* Copyright (C) 2004-2005, HELM Team.
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.
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.
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.
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,
22 * For details, see the HELM World-Wide-Web page,
23 * http://helm.cs.unibo.it/
31 module TA = GrafiteAst
34 let debug_print = if debug then prerr_endline else ignore
36 (** raised when one of the script margins (top or bottom) is reached *)
38 exception NoUnfinishedProof
39 exception ActionCancelled of string
41 let safe_substring s i j =
42 try String.sub s i j with Invalid_argument _ -> assert false
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]
52 if Pcre.pmatch ~rex:multiline_RE str then
53 "\n(** " ^ (Pcre.replace ~rex:newline_RE str) ^ " *)"
55 "\n(**\n" ^ str ^ "\n*)"
57 let strip_comments str =
58 Pcre.qreplace ~templ:"\n" ~pat:"\n\n" (Pcre.qreplace ~rex:comment_RE str)
62 let s = Pcre.replace ~rex:heading_nl_RE s in
64 let nl_pos = String.index s '\n' in
68 let eval_with_engine include_paths status skipped_txt nonskipped_txt st
70 let parsed_text_length =
71 String.length skipped_txt + String.length nonskipped_txt
73 let text = skipped_txt ^ nonskipped_txt in
74 let prefix_len = MatitaGtkMisc.utf8_string_length skipped_txt in
75 let enriched_history_fragment =
76 MatitaEngine.eval_ast ~include_paths ~do_heavy_checks:(Helm_registry.get_bool
77 "matita.do_heavy_checks")
78 status (text,prefix_len,st)
80 let enriched_history_fragment = List.rev enriched_history_fragment in
84 (fun (acc, to_prepend) (status,alias) ->
86 | None -> (status,to_prepend ^ nonskipped_txt)::acc,""
88 let newtxt = GrafiteAstPp.pp_alias value in
89 (status,to_prepend ^ newtxt ^ "\n")::acc, "")
90 ([],skipped_txt) enriched_history_fragment
92 res,"",parsed_text_length
95 let pp_eager_statement_ast = GrafiteAstPp.pp_statement
97 let eval_nmacro include_paths (buffer : GText.buffer) status unparsed_text parsed_text script mac =
98 let parsed_text_length = String.length parsed_text in
100 | TA.Screenshot (_,name) ->
101 let status = script#status in
102 let _,_,menv,subst,_ = status#obj in
103 let name = Filename.dirname (script#filename) ^ "/" ^ name in
105 let selected = Continuationals.Stack.head_goals status#stack in
106 List.filter (fun x,_ -> List.mem x selected) menv
108 CicMathView.screenshot status sequents menv subst name;
109 [status, parsed_text], "", parsed_text_length
111 let status = script#status in
112 let _,_,menv,subst,_ = status#obj in
114 match Continuationals.Stack.head_goals status#stack with
119 "Many goals focused. Using the context of the first one\n";
120 let _, ctx, _ = NCicUtils.lookup_meta g menv in
122 let m, s, status, t =
123 GrafiteDisambiguate.disambiguate_nterm
124 status None ctx menv subst (parsed_text,parsed_text_length,
125 NotationPt.Cast (t,NotationPt.Implicit `JustOne))
126 (* XXX use the metasenv, if possible *)
128 MatitaMathView.cicBrowser (Some (`NCic (t,ctx,m,s)));
129 [status, parsed_text], "", parsed_text_length
130 | TA.NIntroGuess _loc ->
131 let names_ref = ref [] in
132 let s = NTactics.intros_tac ~names_ref [] script#status in
133 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
134 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
135 [s, nl ^ "#" ^ String.concat " #" !names_ref], "", parsed_text_length
136 | TA.NAutoInteractive (_loc, (None,a)) ->
137 let trace_ref = ref [] in
138 let s = NnAuto.auto_tac ~params:(None,a) ~trace_ref script#status in
140 try List.assoc "depth" a
143 let trace = "/"^(if int_of_string depth > 1 then depth else "")^" by " in
145 match !trace_ref with
149 (HExtlib.filter_map (function
150 | NotationPt.NRef r -> Some (NCicPp.r2s status true r)
154 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
155 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
156 [s, nl ^ trace ^ thms ^ "/"], "", parsed_text_length
157 | TA.NAutoInteractive (_, (Some _,_)) -> assert false
159 let rec eval_executable include_paths (buffer : GText.buffer)
160 status unparsed_text skipped_txt nonskipped_txt script ex loc
163 ignore (buffer#move_mark (`NAME "beginning_of_statement")
164 ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
165 (Glib.Utf8.length skipped_txt))) ;
166 eval_with_engine include_paths status skipped_txt nonskipped_txt
167 (TA.Executable (loc, ex))
169 MatitaTypes.Cancel -> [], "", 0
170 | GrafiteEngine.NMacro (_loc,macro) ->
171 eval_nmacro include_paths buffer status
172 unparsed_text (skipped_txt ^ nonskipped_txt) script macro
175 and eval_statement include_paths (buffer : GText.buffer) status script
178 let st,unparsed_text =
181 if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
183 GrafiteParser.parsable_statement status
184 (Ulexing.from_utf8_string text) in
185 let ast = MatitaEngine.get_ast status include_paths strm in
187 | `Ast (st, text) -> st, text
189 let text_of_loc floc =
190 let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
191 let start, stop = HExtlib.loc_of_floc floc in
192 let floc = HExtlib.floc_of_loc (0, start) in
193 let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
194 let floc = HExtlib.floc_of_loc (0, stop) in
195 let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
196 txt,nonskipped_txt,skipped_txt,len
199 | GrafiteAst.Executable (loc, ex) ->
200 let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
201 eval_executable include_paths buffer status unparsed_text
202 skipped nonskipped script ex loc
203 | GrafiteAst.Comment (loc, GrafiteAst.Code (_, ex))
204 when Helm_registry.get_bool "matita.execcomments" ->
205 let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
206 eval_executable include_paths buffer status unparsed_text
207 skipped nonskipped script ex loc
208 | GrafiteAst.Comment (loc, _) ->
209 let parsed_text, _, _, parsed_text_length = text_of_loc loc in
210 let remain_len = String.length unparsed_text - parsed_text_length in
211 let s = String.sub unparsed_text parsed_text_length remain_len in
214 eval_statement include_paths buffer status script (`Raw s)
216 HExtlib.Localized (floc, exn) ->
217 HExtlib.raise_localized_exception
218 ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
219 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
221 (MultiPassDisambiguator.DisambiguationError
222 (offset+parsed_text_length, errorll))
224 assert (text=""); (* no macros inside comments, please! *)
226 | (statuses,text)::tl ->
227 (statuses,parsed_text ^ text)::tl,"",parsed_text_length + len
230 let fresh_script_id =
234 (** Selection handling
235 * Two clipboards are used: "clipboard" and "primary".
236 * "primary" is used by X, when you hit the middle button mouse is content is
237 * pasted between applications. In Matita this selection always contain the
238 * textual version of the selected term.
239 * "clipboard" is used inside Matita only and support ATM two different targets:
240 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
243 class script ~(parent:GBin.scrolled_window) ~tab_label () =
245 GSourceView2.source_view
247 ~insert_spaces_instead_of_tabs:true ~tab_width:2
248 ~right_margin_position:80 ~show_right_margin:true
249 ~smart_home_end:`AFTER
252 let buffer = source_view#buffer in
253 let source_buffer = source_view#source_buffer in
254 let similarsymbols_tag_name = "similarsymbolos" in
255 let similarsymbols_tag = `NAME similarsymbols_tag_name in
256 let initial_statuses current baseuri =
257 let status = new MatitaEngine.status baseuri in
259 Some current -> NCicLibrary.time_travel status;
261 (* MATITA 1.0: there is a known bug in invalidation; temporary fix here *)
262 NCicEnvironment.invalidate () *)
266 let default_buri = "cic:/matita/tests" in
267 let default_fname = ".unnamed.ma" in
269 val mutable include_paths_ = []
270 val clipboard = GData.clipboard Gdk.Atom.clipboard
271 (*val primary = GData.clipboard Gdk.Atom.primary*)
272 val mutable similarsymbols = []
273 val mutable similarsymbols_orig = []
274 val similar_memory = Hashtbl.create 97
275 val mutable old_used_memory = false
277 val scriptId = fresh_script_id ()
279 val mutable filename_ = (None : string option)
281 method has_name = filename_ <> None
283 method source_view = source_view
285 method include_paths =
287 Helm_registry.get_list Helm_registry.string "matita.includes"
289 method private curdir =
291 let root, _buri, _fname, _tgt =
292 Librarian.baseuri_of_script ~include_paths:self#include_paths
296 with Librarian.NoRootFor _ -> Sys.getcwd ()
298 method buri_of_current_file =
300 | None -> default_buri
303 let _root, buri, _fname, _tgt =
304 Librarian.baseuri_of_script ~include_paths:self#include_paths f
307 with Librarian.NoRootFor _ | Librarian.FileNotFound _ -> default_buri
309 method filename = match filename_ with None -> default_fname | Some f -> f
313 (source_view#source_buffer#begin_not_undoable_action ();
316 source_view#source_buffer#end_not_undoable_action ());
317 MatitaMisc.observe_font_size (fun font_size ->
318 source_view#misc#modify_font_by_name
319 (sprintf "%s %d" BuildTimeConf.script_font font_size));
320 source_view#misc#grab_focus ();
321 ignore(source_view#source_buffer#set_language
322 (Some MatitaGtkMisc.matita_lang));
323 ignore(source_view#source_buffer#set_highlight_syntax true);
324 ignore(source_view#connect#after#paste_clipboard
325 ~callback:(fun () -> self#clean_dirty_lock));
326 ignore (GMain.Timeout.add ~ms:300000
327 ~callback:(fun _ -> self#_saveToBackupFile ();true));
328 ignore (buffer#connect#modified_changed
329 (fun _ -> self#set_star buffer#modified));
330 (* clean_locked is set to true only "during" a PRIMARY paste
331 operation (i.e. by clicking with the second mouse button) *)
332 let clean_locked = ref false in
333 ignore(source_view#event#connect#button_press
336 if GdkEvent.Button.button button = 2 then
337 clean_locked := true;
340 ignore(source_view#event#connect#button_release
341 ~callback:(fun button -> clean_locked := false; false));
342 ignore(source_view#buffer#connect#after#apply_tag
344 fun tag ~start:_ ~stop:_ ->
346 tag#get_oid = self#locked_tag#get_oid
349 clean_locked := false;
350 self#clean_dirty_lock;
353 ignore(source_view#source_buffer#connect#after#insert_text
354 ~callback:(fun iter str ->
355 if (MatitaMisc.get_gui ())#main#menuitemAutoAltL#active && (str = " " || str = "\n") then
356 ignore(self#expand_virtual_if_any iter str)));
357 ignore(source_view#connect#after#populate_popup
358 ~callback:(fun pre_menu ->
359 let menu = new GMenu.menu pre_menu in
360 let menuItems = menu#children in
361 let undoMenuItem, redoMenuItem =
363 [undo;redo;sep1;cut;copy;paste;delete;sep2;
364 selectall;sep3;inputmethod;insertunicodecharacter] ->
365 List.iter menu#remove [ copy; cut; delete; paste ];
367 | _ -> assert false in
369 let i = ref 2 in (* last occupied position *)
370 fun ?label ?stock () ->
372 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
375 let copy = add_menu_item ~stock:`COPY () in
376 let cut = add_menu_item ~stock:`CUT () in
377 let delete = add_menu_item ~stock:`DELETE () in
378 let paste = add_menu_item ~stock:`PASTE () in
379 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
380 copy#misc#set_sensitive self#canCopy;
381 cut#misc#set_sensitive self#canCut;
382 delete#misc#set_sensitive self#canDelete;
383 paste#misc#set_sensitive self#canPaste;
384 paste_pattern#misc#set_sensitive self#canPastePattern;
385 MatitaGtkMisc.connect_menu_item copy self#copy;
386 MatitaGtkMisc.connect_menu_item cut self#cut;
387 MatitaGtkMisc.connect_menu_item delete self#delete;
388 MatitaGtkMisc.connect_menu_item paste self#paste;
389 MatitaGtkMisc.connect_menu_item paste_pattern self#pastePattern;
390 let new_undoMenuItem =
391 GMenu.image_menu_item
392 ~image:(GMisc.image ~stock:`UNDO ())
395 ~packing:(menu#insert ~pos:0) () in
396 new_undoMenuItem#misc#set_sensitive
397 (undoMenuItem#misc#get_flag `SENSITIVE);
398 menu#remove (undoMenuItem :> GMenu.menu_item);
399 MatitaGtkMisc.connect_menu_item new_undoMenuItem
400 (fun () -> self#safe_undo);
401 let new_redoMenuItem =
402 GMenu.image_menu_item
403 ~image:(GMisc.image ~stock:`REDO ())
406 ~packing:(menu#insert ~pos:1) () in
407 new_redoMenuItem#misc#set_sensitive
408 (redoMenuItem#misc#get_flag `SENSITIVE);
409 menu#remove (redoMenuItem :> GMenu.menu_item);
410 MatitaGtkMisc.connect_menu_item new_redoMenuItem
411 (fun () -> self#safe_redo)));
413 val mutable statements = [] (** executed statements *)
415 val mutable history = [ initial_statuses None default_buri ]
416 (** list of states before having executed statements. Head element of this
417 * list is the current state, last element is the state at the beginning of
419 * Invariant: this list length is 1 + length of statements *)
421 (** text mark and tag representing locked part of a script *)
423 buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
424 val beginning_of_statement_mark =
425 buffer#create_mark ~name:"beginning_of_statement"
426 ~left_gravity:true buffer#start_iter
427 val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
428 val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
430 (** unicode handling *)
431 method nextSimilarSymbol =
432 let write_similarsymbol s =
433 let s = Glib.Utf8.from_unichar s in
434 let iter = source_view#source_buffer#get_iter_at_mark `INSERT in
435 assert(Glib.Utf8.validate s);
436 source_view#source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
437 source_view#source_buffer#insert ~iter:(source_view#source_buffer#get_iter_at_mark `INSERT) s;
438 (try source_view#source_buffer#delete_mark similarsymbols_tag
439 with GText.No_such_mark _ -> ());
440 ignore(source_view#source_buffer#create_mark ~name:similarsymbols_tag_name
441 (source_view#source_buffer#get_iter_at_mark `INSERT));
443 let new_similarsymbol =
445 let iter_ins = source_view#source_buffer#get_iter_at_mark `INSERT in
446 let iter_lig = source_view#source_buffer#get_iter_at_mark similarsymbols_tag in
447 not (iter_ins#equal iter_lig)
448 with GText.No_such_mark _ -> true
450 if new_similarsymbol then
451 (if not(self#expand_virtual_if_any (source_view#source_buffer#get_iter_at_mark `INSERT) "")then
453 let i = source_view#source_buffer#get_iter_at_mark `INSERT in
454 Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
456 (match Virtuals.similar_symbols last_symbol with
459 similarsymbols_orig <- eqclass;
461 try Hashtbl.find similar_memory similarsymbols_orig
463 let is_used = List.map (fun x -> x,false) eqclass in
464 Hashtbl.add similar_memory eqclass is_used;
469 List.partition (fun s -> List.assoc s is_used) eqclass
471 match used @ unused with a::b::c -> a,b,c | _ -> assert false
474 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
476 old_used_memory <- List.assoc hd is_used;
478 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
480 Hashtbl.replace similar_memory similarsymbols_orig is_used;
481 write_similarsymbol hd;
482 similarsymbols <- tl @ [ hd ]))
484 match similarsymbols with
487 let is_used = Hashtbl.find similar_memory similarsymbols_orig in
488 let last = HExtlib.list_last tl in
489 let old_used_for_last = old_used_memory in
490 old_used_memory <- List.assoc hd is_used;
492 (hd, true) :: (last,old_used_for_last) ::
493 List.filter (fun (x,_) -> x <> last && x <> hd) is_used
495 Hashtbl.replace similar_memory similarsymbols_orig is_used;
496 similarsymbols <- tl @ [ hd ];
497 write_similarsymbol hd
499 method private reset_similarsymbols =
500 similarsymbols <- [];
501 similarsymbols_orig <- [];
502 try source_view#source_buffer#delete_mark similarsymbols_tag
503 with GText.No_such_mark _ -> ()
505 method private expand_virtual_if_any iter tok =
507 let len = MatitaGtkMisc.utf8_string_length tok in
509 let prev = iter#copy#backward_chars len in
510 prev#get_slice ~stop:(prev#copy#backward_find_char
511 (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
513 let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
514 self#reset_similarsymbols;
515 let s = Glib.Utf8.from_unichar symb in
516 assert(Glib.Utf8.validate s);
517 source_view#source_buffer#delete ~start:iter
518 ~stop:(iter#copy#backward_chars
519 (MatitaGtkMisc.utf8_string_length inplaceof + len));
520 source_view#source_buffer#insert ~iter
521 (if inplaceof.[0] = '\\' then s else (s ^ tok));
523 with Virtuals.Not_a_virtual -> false
525 (** selections / clipboards handling *)
527 method markupSelected = MatitaMathView.has_selection ()
528 method private textSelected =
529 (source_view#source_buffer#get_iter_at_mark `INSERT)#compare
530 (source_view#source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
531 method private markupStored = MatitaMathView.has_clipboard ()
532 method private textStored = clipboard#text <> None
533 method canCopy = self#textSelected
534 method canCut = self#textSelected
535 method canDelete = self#textSelected
536 (*CSC: WRONG CODE: we should look in the clipboard instead! *)
537 method canPaste = self#markupStored || self#textStored
538 method canPastePattern = self#markupStored
541 (* phase 1: we save the actual status of the marks and we undo *)
542 let locked_mark = `MARK (self#locked_mark) in
543 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
544 let locked_iter_offset = locked_iter#offset in
547 (source_view#buffer#create_mark ~name:"lock_point"
548 ~left_gravity:true locked_iter) in
549 source_view#source_buffer#undo ();
550 (* phase 2: we save the cursor position and we redo, restoring
551 the previous status of all the marks *)
552 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
555 (source_view#buffer#create_mark ~name:"undo_point"
556 ~left_gravity:true cursor_iter)
558 source_view#source_buffer#redo ();
559 let mark_iter = source_view#buffer#get_iter_at_mark mark in
560 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
561 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
562 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
563 source_view#buffer#delete_mark mark;
564 source_view#buffer#delete_mark mark2;
565 (* phase 3: if after the undo the cursor was in the locked area,
566 then we move it there again and we perform a goto *)
567 if mark_iter#offset < locked_iter_offset then
569 source_view#buffer#move_mark `INSERT ~where:mark_iter;
570 self#goto `Cursor ();
572 (* phase 4: we perform again the undo. This time we are sure that
573 the text to undo is not locked *)
574 source_view#source_buffer#undo ();
575 source_view#misc#grab_focus ()
578 (* phase 1: we save the actual status of the marks, we redo and
580 let locked_mark = `MARK (self#locked_mark) in
581 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
582 let locked_iter_offset = locked_iter#offset in
585 (source_view#buffer#create_mark ~name:"lock_point"
586 ~left_gravity:true locked_iter) in
587 source_view#source_buffer#redo ();
588 source_view#source_buffer#undo ();
589 (* phase 2: we save the cursor position and we restore
590 the previous status of all the marks *)
591 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
594 (source_view#buffer#create_mark ~name:"undo_point"
595 ~left_gravity:true cursor_iter)
597 let mark_iter = source_view#buffer#get_iter_at_mark mark in
598 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
599 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
600 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
601 source_view#buffer#delete_mark mark;
602 source_view#buffer#delete_mark mark2;
603 (* phase 3: if after the undo the cursor is in the locked area,
604 then we move it there again and we perform a goto *)
605 if mark_iter#offset < locked_iter_offset then
607 source_view#buffer#move_mark `INSERT ~where:mark_iter;
608 self#goto `Cursor ();
610 (* phase 4: we perform again the redo. This time we are sure that
611 the text to redo is not locked *)
612 source_view#source_buffer#redo ();
613 source_view#misc#grab_focus ()
619 MatitaMathView.empty_clipboard ();
620 source_view#buffer#copy_clipboard clipboard;
622 MatitaMathView.copy_selection ()
625 source_view#buffer#cut_clipboard clipboard;
626 MatitaMathView.empty_clipboard ()
629 ignore (source_view#buffer#delete_selection ())
632 if MatitaMathView.has_clipboard ()
633 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
634 else source_view#buffer#paste_clipboard clipboard;
635 self#clean_dirty_lock
637 method pastePattern () =
638 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
640 method locked_mark = locked_mark
641 method locked_tag = locked_tag
642 method error_tag = error_tag
644 (* history can't be empty, the invariant above grant that it contains at
645 * least the init grafite_status *)
646 method status = match history with s::_ -> s | _ -> assert false
648 method private _advance ?statement () =
649 let s = match statement with Some s -> s | None -> self#getFuture in
650 if self#bos then LibraryClean.clean_baseuris [self#buri_of_current_file];
651 HLog.debug ("evaluating: " ^ first_line s ^ " ...");
652 let time1 = Unix.gettimeofday () in
653 let entries, newtext, parsed_len =
655 eval_statement self#include_paths buffer self#status self (`Raw s)
656 with End_of_file -> raise Margin
658 let time2 = Unix.gettimeofday () in
659 HLog.debug ("... done in " ^ string_of_float (time2 -. time1) ^ "s");
660 let new_statuses, new_statements =
661 let statuses, texts = List.split entries in
664 history <- new_statuses @ history;
665 statements <- new_statements @ statements;
666 let start = buffer#get_iter_at_mark (`MARK locked_mark) in
667 let new_text = String.concat "" (List.rev new_statements) in
668 if statement <> None then
669 buffer#insert ~iter:start new_text
671 let parsed_text = String.sub s 0 parsed_len in
672 if new_text <> parsed_text then begin
673 let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
674 buffer#delete ~start ~stop;
675 buffer#insert ~iter:start new_text;
678 self#moveMark (Glib.Utf8.length new_text);
679 buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext
681 method private _retract offset status new_statements new_history =
682 NCicLibrary.time_travel status;
683 statements <- new_statements;
684 history <- new_history;
685 self#moveMark (- offset)
687 method advance ?statement () =
689 self#_advance ?statement ();
692 | Margin -> self#notify
693 | Not_found -> assert false
694 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
695 | exc -> self#notify; raise exc
699 let cmp,new_statements,new_history,status =
700 match statements,history with
701 stat::statements, _::(status::_ as history) ->
702 assert (Glib.Utf8.validate stat);
703 Glib.Utf8.length stat, statements, history, status
704 | [],[_] -> raise Margin
705 | _,_ -> assert false
707 self#_retract cmp status new_statements new_history;
710 | Margin -> self#notify
711 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
712 | exc -> self#notify; raise exc
714 method private getFuture =
715 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
716 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
719 method expandAllVirtuals =
720 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
721 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
722 buffer#delete ~start:lock ~stop:buffer#end_iter;
723 let text = Pcre.replace ~pat:":=" ~templ:"\\def" text in
724 let text = Pcre.replace ~pat:"->" ~templ:"\\to" text in
725 let text = Pcre.replace ~pat:"=>" ~templ:"\\Rightarrow" text in
727 Pcre.substitute_substrings
729 let pristine = Pcre.get_substring str 0 in
731 if pristine.[0] = ' ' then
732 String.sub pristine 1 (String.length pristine -1)
736 if input.[String.length input-1] = ' ' then
737 String.sub input 0 (String.length input -1)
741 if input = "\\forall" ||
742 input = "\\lambda" ||
743 input = "\\exists" then "","" else " ", " "
746 before ^ Glib.Utf8.from_unichar
747 (snd (Virtuals.symbol_of_virtual input)) ^ after
748 with Virtuals.Not_a_virtual -> pristine)
749 ~pat:" ?\\\\[a-zA-Z]+ ?" text
751 buffer#insert ~iter:lock text
753 (** @param rel_offset relative offset from current position of locked_mark *)
754 method private moveMark rel_offset =
755 let mark = `MARK locked_mark in
756 let old_insert = buffer#get_iter_at_mark `INSERT in
757 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
758 let current_mark_pos = buffer#get_iter_at_mark mark in
760 match rel_offset with
761 | 0 -> current_mark_pos
762 | n when n > 0 -> current_mark_pos#forward_chars n
763 | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
765 buffer#move_mark mark ~where:new_mark_pos;
766 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
767 buffer#move_mark `INSERT old_insert;
768 let mark_position = buffer#get_iter_at_mark mark in
769 if source_view#move_mark_onscreen mark then
771 buffer#move_mark mark mark_position;
772 source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
774 while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
776 method clean_dirty_lock =
777 let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
778 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
779 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
781 val mutable observers = []
783 method addObserver (o: GrafiteTypes.status -> unit) =
784 observers <- o :: observers
786 method private notify =
787 let status = self#status in
788 List.iter (fun o -> o status) observers
791 NCicLibrary.replace self#status;
794 method loadFromFile f =
795 buffer#set_text (HExtlib.input_file f);
797 buffer#set_modified false
799 method assignFileName file =
802 tab_label#set_text default_fname;
804 include_paths_ <- [];
807 let f = Librarian.absolutize file in
808 tab_label#set_text (Filename.basename f);
810 include_paths_ <- MatitaEngine.read_include_paths ~include_paths:[] f;
814 tab_label#set_text ((if b then "*" else "")^Filename.basename self#filename);
815 tab_label#misc#set_tooltip_text
816 ("URI: " ^ self#buri_of_current_file ^ "\nPATH: " ^ self#filename);
818 method saveToFile () =
819 if self#has_name then
820 let oc = open_out self#filename in
821 output_string oc (buffer#get_text ~start:buffer#start_iter
822 ~stop:buffer#end_iter ());
825 buffer#set_modified false
827 HLog.error "Can't save, no filename selected"
829 method private _saveToBackupFile () =
830 if buffer#modified then
832 let f = self#filename ^ "~" in
833 let oc = open_out f in
834 output_string oc (buffer#get_text ~start:buffer#start_iter
835 ~stop:buffer#end_iter ());
837 HLog.debug ("backup " ^ f ^ " saved")
840 method private reset_buffer =
842 history <- [ initial_statuses (Some self#status) self#buri_of_current_file ];
844 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
845 buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
849 source_buffer#begin_not_undoable_action ();
850 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
851 source_buffer#end_not_undoable_action ();
852 buffer#set_modified false;
855 let template = HExtlib.input_file BuildTimeConf.script_template in
856 buffer#insert ~iter:(buffer#get_iter `START) template;
857 buffer#set_modified false;
860 method goto (pos: [`Top | `Bottom | `Cursor]) () =
862 let old_locked_mark =
864 (buffer#create_mark ~name:"old_locked_mark"
865 ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
866 let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in
867 let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in
868 let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
871 dispose_old_locked_mark ();
878 let newpos = getpos () in
879 if (getoldpos ())#compare newpos < 0 then
881 buffer#move_mark old_locked_mark newpos;
886 dispose_old_locked_mark ();
889 | Margin -> dispose_old_locked_mark (); self#notify
890 | exc -> dispose_old_locked_mark (); self#notify; raise exc)
892 let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
893 let cursor_iter () = buffer#get_iter_at_mark `INSERT in
896 (buffer#create_mark ~name:"initial_insert"
897 ~left_gravity:true (cursor_iter ())) in
898 let dispose_remember () = buffer#delete_mark remember in
899 let remember_iter () =
900 buffer#get_iter_at_mark (`NAME "initial_insert") in
901 let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
903 let forward_until_cursor () = (* go forward until locked > cursor *)
906 if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0
909 buffer#move_mark old_locked_mark (getpos ());
915 let rec back_until_cursor len = (* go backward until locked < cursor *)
917 statements, ((status)::_ as history)
919 self#_retract (icmp - len) status statements
921 | statement::tl1, _::tl2 ->
922 back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
923 | _,_ -> assert false
927 if icmp < 0 then (* locked < cursor *)
928 (forward_until_cursor (); self#notify)
929 else if icmp > 0 then (* locked > cursor *)
930 (back_until_cursor icmp (statements,history); self#notify)
931 else (* cursor = locked *)
935 dispose_old_locked_mark ();
937 | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
938 | exc -> dispose_remember (); dispose_old_locked_mark ();
939 self#notify; raise exc)
940 with Invalid_argument "Array.make" ->
941 HLog.error "The script is too big!\n"
949 let rec is_there_only_comments status s =
950 if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
952 GrafiteParser.parsable_statement status
953 (Ulexing.from_utf8_string s)in
954 match GrafiteParser.parse_statement status strm with
955 | GrafiteAst.Comment (loc,_) ->
956 let _,parsed_text_length = MatitaGtkMisc.utf8_parsed_text s loc in
957 (* CSC: why +1 in the following lines ???? *)
958 let parsed_text_length = parsed_text_length + 1 in
959 let remain_len = String.length s - parsed_text_length in
960 let next = String.sub s parsed_text_length remain_len in
961 is_there_only_comments status next
962 | GrafiteAst.Executable _ -> false
964 try is_there_only_comments self#status self#getFuture
966 | NCicLibrary.IncludedFileNotCompiled _
967 | HExtlib.Localized _
968 | CicNotationParser.Parse_error _ -> false
969 | Margin | End_of_file -> true
970 | Invalid_argument "Array.make" -> false
974 HLog.debug "script status:";
975 HLog.debug ("history size: " ^ string_of_int (List.length history));
976 HLog.debug (sprintf "%d statements:" (List.length statements));
977 List.iter HLog.debug statements;
978 HLog.debug ("Current file name: " ^ self#filename);
980 method has_parent (p : GObj.widget) = parent#coerce#misc#get_oid = p#misc#get_oid
985 let script ~parent ~tab_label ()
987 let s = new script ~parent ~tab_label () in
988 _script := s::!_script;
992 let notebook = (MatitaMisc.get_gui ())#main#scriptNotebook in
993 let parent = notebook#get_nth_page page in
995 List.find (fun s -> s#has_parent parent) !_script
997 Not_found -> assert false
1001 at_page ((MatitaMisc.get_gui ())#main#scriptNotebook#current_page)
1004 let s = at_page page in
1005 _script := List.filter ((<>) s) !_script
1008 let iter_scripts f = List.iter f !_script;;
1011 CicMathView.register_matita_script_current (current :> unit -> < advance: ?statement:string -> unit -> unit; status: GrafiteTypes.status >)