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
260 NCicLibrary.time_travel status;
262 (* MATITA 1.0: there is a known bug in invalidation; temporary fix here *)
263 NCicEnvironment.invalidate () *)
267 let default_buri = "cic:/matita/tests" in
268 let default_fname = ".unnamed.ma" in
270 val mutable include_paths_ = []
271 val clipboard = GData.clipboard Gdk.Atom.clipboard
272 (*val primary = GData.clipboard Gdk.Atom.primary*)
273 val mutable similarsymbols = []
274 val mutable similarsymbols_orig = []
275 val similar_memory = Hashtbl.create 97
276 val mutable old_used_memory = false
278 val scriptId = fresh_script_id ()
280 val mutable filename_ = (None : string option)
282 method has_name = filename_ <> None
284 method source_view = source_view
286 method include_paths =
288 Helm_registry.get_list Helm_registry.string "matita.includes"
290 method private curdir =
292 let root, _buri, _fname, _tgt =
293 Librarian.baseuri_of_script ~include_paths:self#include_paths
297 with Librarian.NoRootFor _ -> Sys.getcwd ()
299 method buri_of_current_file =
301 | None -> default_buri
304 let _root, buri, _fname, _tgt =
305 Librarian.baseuri_of_script ~include_paths:self#include_paths f
308 with Librarian.NoRootFor _ | Librarian.FileNotFound _ -> default_buri
310 method filename = match filename_ with None -> default_fname | Some f -> f
314 (source_view#source_buffer#begin_not_undoable_action ();
317 source_view#source_buffer#end_not_undoable_action ());
318 MatitaMisc.observe_font_size (fun font_size ->
319 source_view#misc#modify_font_by_name
320 (sprintf "%s %d" BuildTimeConf.script_font font_size));
321 source_view#misc#grab_focus ();
322 ignore(source_view#source_buffer#set_language
323 (Some MatitaGtkMisc.matita_lang));
324 ignore(source_view#source_buffer#set_highlight_syntax true);
325 ignore(source_view#connect#after#paste_clipboard
326 ~callback:(fun () -> self#clean_dirty_lock));
327 ignore (GMain.Timeout.add ~ms:300000
328 ~callback:(fun _ -> self#_saveToBackupFile ();true));
329 ignore (buffer#connect#modified_changed
330 (fun _ -> self#set_star buffer#modified));
331 (* clean_locked is set to true only "during" a PRIMARY paste
332 operation (i.e. by clicking with the second mouse button) *)
333 let clean_locked = ref false in
334 ignore(source_view#event#connect#button_press
337 if GdkEvent.Button.button button = 2 then
338 clean_locked := true;
341 ignore(source_view#event#connect#button_release
342 ~callback:(fun button -> clean_locked := false; false));
343 ignore(source_view#buffer#connect#after#apply_tag
345 fun tag ~start:_ ~stop:_ ->
347 tag#get_oid = self#locked_tag#get_oid
350 clean_locked := false;
351 self#clean_dirty_lock;
354 ignore(source_view#source_buffer#connect#after#insert_text
355 ~callback:(fun iter str ->
356 if (MatitaMisc.get_gui ())#main#menuitemAutoAltL#active && (str = " " || str = "\n") then
357 ignore(self#expand_virtual_if_any iter str)));
358 ignore(source_view#connect#after#populate_popup
359 ~callback:(fun pre_menu ->
360 let menu = new GMenu.menu pre_menu in
361 let menuItems = menu#children in
362 let undoMenuItem, redoMenuItem =
364 [undo;redo;sep1;cut;copy;paste;delete;sep2;
365 selectall;sep3;inputmethod;insertunicodecharacter] ->
366 List.iter menu#remove [ copy; cut; delete; paste ];
368 | _ -> assert false in
370 let i = ref 2 in (* last occupied position *)
371 fun ?label ?stock () ->
373 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
376 let copy = add_menu_item ~stock:`COPY () in
377 let cut = add_menu_item ~stock:`CUT () in
378 let delete = add_menu_item ~stock:`DELETE () in
379 let paste = add_menu_item ~stock:`PASTE () in
380 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
381 copy#misc#set_sensitive self#canCopy;
382 cut#misc#set_sensitive self#canCut;
383 delete#misc#set_sensitive self#canDelete;
384 paste#misc#set_sensitive self#canPaste;
385 paste_pattern#misc#set_sensitive self#canPastePattern;
386 MatitaGtkMisc.connect_menu_item copy self#copy;
387 MatitaGtkMisc.connect_menu_item cut self#cut;
388 MatitaGtkMisc.connect_menu_item delete self#delete;
389 MatitaGtkMisc.connect_menu_item paste self#paste;
390 MatitaGtkMisc.connect_menu_item paste_pattern self#pastePattern;
391 let new_undoMenuItem =
392 GMenu.image_menu_item
393 ~image:(GMisc.image ~stock:`UNDO ())
396 ~packing:(menu#insert ~pos:0) () in
397 new_undoMenuItem#misc#set_sensitive
398 (undoMenuItem#misc#get_flag `SENSITIVE);
399 menu#remove (undoMenuItem :> GMenu.menu_item);
400 MatitaGtkMisc.connect_menu_item new_undoMenuItem
401 (fun () -> self#safe_undo);
402 let new_redoMenuItem =
403 GMenu.image_menu_item
404 ~image:(GMisc.image ~stock:`REDO ())
407 ~packing:(menu#insert ~pos:1) () in
408 new_redoMenuItem#misc#set_sensitive
409 (redoMenuItem#misc#get_flag `SENSITIVE);
410 menu#remove (redoMenuItem :> GMenu.menu_item);
411 MatitaGtkMisc.connect_menu_item new_redoMenuItem
412 (fun () -> self#safe_redo)));
414 val mutable statements = [] (** executed statements *)
416 val mutable history = [ initial_statuses None default_buri ]
417 (** list of states before having executed statements. Head element of this
418 * list is the current state, last element is the state at the beginning of
420 * Invariant: this list length is 1 + length of statements *)
422 (** text mark and tag representing locked part of a script *)
424 buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
425 val beginning_of_statement_mark =
426 buffer#create_mark ~name:"beginning_of_statement"
427 ~left_gravity:true buffer#start_iter
428 val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
429 val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
431 (** unicode handling *)
432 method nextSimilarSymbol =
433 let write_similarsymbol s =
434 let s = Glib.Utf8.from_unichar s in
435 let iter = source_view#source_buffer#get_iter_at_mark `INSERT in
436 assert(Glib.Utf8.validate s);
437 source_view#source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
438 source_view#source_buffer#insert ~iter:(source_view#source_buffer#get_iter_at_mark `INSERT) s;
439 (try source_view#source_buffer#delete_mark similarsymbols_tag
440 with GText.No_such_mark _ -> ());
441 ignore(source_view#source_buffer#create_mark ~name:similarsymbols_tag_name
442 (source_view#source_buffer#get_iter_at_mark `INSERT));
444 let new_similarsymbol =
446 let iter_ins = source_view#source_buffer#get_iter_at_mark `INSERT in
447 let iter_lig = source_view#source_buffer#get_iter_at_mark similarsymbols_tag in
448 not (iter_ins#equal iter_lig)
449 with GText.No_such_mark _ -> true
451 if new_similarsymbol then
452 (if not(self#expand_virtual_if_any (source_view#source_buffer#get_iter_at_mark `INSERT) "")then
454 let i = source_view#source_buffer#get_iter_at_mark `INSERT in
455 Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
457 (match Virtuals.similar_symbols last_symbol with
460 similarsymbols_orig <- eqclass;
462 try Hashtbl.find similar_memory similarsymbols_orig
464 let is_used = List.map (fun x -> x,false) eqclass in
465 Hashtbl.add similar_memory eqclass is_used;
470 List.partition (fun s -> List.assoc s is_used) eqclass
472 match used @ unused with a::b::c -> a,b,c | _ -> assert false
475 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
477 old_used_memory <- List.assoc hd is_used;
479 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
481 Hashtbl.replace similar_memory similarsymbols_orig is_used;
482 write_similarsymbol hd;
483 similarsymbols <- tl @ [ hd ]))
485 match similarsymbols with
488 let is_used = Hashtbl.find similar_memory similarsymbols_orig in
489 let last = HExtlib.list_last tl in
490 let old_used_for_last = old_used_memory in
491 old_used_memory <- List.assoc hd is_used;
493 (hd, true) :: (last,old_used_for_last) ::
494 List.filter (fun (x,_) -> x <> last && x <> hd) is_used
496 Hashtbl.replace similar_memory similarsymbols_orig is_used;
497 similarsymbols <- tl @ [ hd ];
498 write_similarsymbol hd
500 method private reset_similarsymbols =
501 similarsymbols <- [];
502 similarsymbols_orig <- [];
503 try source_view#source_buffer#delete_mark similarsymbols_tag
504 with GText.No_such_mark _ -> ()
506 method private expand_virtual_if_any iter tok =
508 let len = MatitaGtkMisc.utf8_string_length tok in
510 let prev = iter#copy#backward_chars len in
511 prev#get_slice ~stop:(prev#copy#backward_find_char
512 (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
514 let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
515 self#reset_similarsymbols;
516 let s = Glib.Utf8.from_unichar symb in
517 assert(Glib.Utf8.validate s);
518 source_view#source_buffer#delete ~start:iter
519 ~stop:(iter#copy#backward_chars
520 (MatitaGtkMisc.utf8_string_length inplaceof + len));
521 source_view#source_buffer#insert ~iter
522 (if inplaceof.[0] = '\\' then s else (s ^ tok));
524 with Virtuals.Not_a_virtual -> false
526 (** selections / clipboards handling *)
528 method markupSelected = MatitaMathView.has_selection ()
529 method private textSelected =
530 (source_view#source_buffer#get_iter_at_mark `INSERT)#compare
531 (source_view#source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
532 method private markupStored = MatitaMathView.has_clipboard ()
533 method private textStored = clipboard#text <> None
534 method canCopy = self#textSelected
535 method canCut = self#textSelected
536 method canDelete = self#textSelected
537 (*CSC: WRONG CODE: we should look in the clipboard instead! *)
538 method canPaste = self#markupStored || self#textStored
539 method canPastePattern = self#markupStored
542 (* phase 1: we save the actual status of the marks and we undo *)
543 let locked_mark = `MARK (self#locked_mark) in
544 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
545 let locked_iter_offset = locked_iter#offset in
548 (source_view#buffer#create_mark ~name:"lock_point"
549 ~left_gravity:true locked_iter) in
550 source_view#source_buffer#undo ();
551 (* phase 2: we save the cursor position and we redo, restoring
552 the previous status of all the marks *)
553 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
556 (source_view#buffer#create_mark ~name:"undo_point"
557 ~left_gravity:true cursor_iter)
559 source_view#source_buffer#redo ();
560 let mark_iter = source_view#buffer#get_iter_at_mark mark in
561 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
562 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
563 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
564 source_view#buffer#delete_mark mark;
565 source_view#buffer#delete_mark mark2;
566 (* phase 3: if after the undo the cursor was in the locked area,
567 then we move it there again and we perform a goto *)
568 if mark_iter#offset < locked_iter_offset then
570 source_view#buffer#move_mark `INSERT ~where:mark_iter;
571 self#goto `Cursor ();
573 (* phase 4: we perform again the undo. This time we are sure that
574 the text to undo is not locked *)
575 source_view#source_buffer#undo ();
576 source_view#misc#grab_focus ()
579 (* phase 1: we save the actual status of the marks, we redo and
581 let locked_mark = `MARK (self#locked_mark) in
582 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
583 let locked_iter_offset = locked_iter#offset in
586 (source_view#buffer#create_mark ~name:"lock_point"
587 ~left_gravity:true locked_iter) in
588 source_view#source_buffer#redo ();
589 source_view#source_buffer#undo ();
590 (* phase 2: we save the cursor position and we restore
591 the previous status of all the marks *)
592 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
595 (source_view#buffer#create_mark ~name:"undo_point"
596 ~left_gravity:true cursor_iter)
598 let mark_iter = source_view#buffer#get_iter_at_mark mark in
599 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
600 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
601 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
602 source_view#buffer#delete_mark mark;
603 source_view#buffer#delete_mark mark2;
604 (* phase 3: if after the undo the cursor is in the locked area,
605 then we move it there again and we perform a goto *)
606 if mark_iter#offset < locked_iter_offset then
608 source_view#buffer#move_mark `INSERT ~where:mark_iter;
609 self#goto `Cursor ();
611 (* phase 4: we perform again the redo. This time we are sure that
612 the text to redo is not locked *)
613 source_view#source_buffer#redo ();
614 source_view#misc#grab_focus ()
620 MatitaMathView.empty_clipboard ();
621 source_view#buffer#copy_clipboard clipboard;
623 MatitaMathView.copy_selection ()
626 source_view#buffer#cut_clipboard clipboard;
627 MatitaMathView.empty_clipboard ()
630 ignore (source_view#buffer#delete_selection ())
633 if MatitaMathView.has_clipboard ()
634 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
635 else source_view#buffer#paste_clipboard clipboard;
636 self#clean_dirty_lock
638 method pastePattern () =
639 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
641 method locked_mark = locked_mark
642 method locked_tag = locked_tag
643 method error_tag = error_tag
645 (* history can't be empty, the invariant above grant that it contains at
646 * least the init grafite_status *)
647 method status = match history with s::_ -> s | _ -> assert false
649 method private _advance ?statement () =
650 let s = match statement with Some s -> s | None -> self#getFuture in
651 if self#bos then LibraryClean.clean_baseuris [self#buri_of_current_file];
652 HLog.debug ("evaluating: " ^ first_line s ^ " ...");
653 let time1 = Unix.gettimeofday () in
654 let entries, newtext, parsed_len =
656 eval_statement self#include_paths buffer self#status self (`Raw s)
657 with End_of_file -> raise Margin
659 let time2 = Unix.gettimeofday () in
660 HLog.debug ("... done in " ^ string_of_float (time2 -. time1) ^ "s");
661 let new_statuses, new_statements =
662 let statuses, texts = List.split entries in
665 history <- new_statuses @ history;
666 statements <- new_statements @ statements;
667 let start = buffer#get_iter_at_mark (`MARK locked_mark) in
668 let new_text = String.concat "" (List.rev new_statements) in
669 if statement <> None then
670 buffer#insert ~iter:start new_text
672 let parsed_text = String.sub s 0 parsed_len in
673 if new_text <> parsed_text then begin
674 let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
675 buffer#delete ~start ~stop;
676 buffer#insert ~iter:start new_text;
679 self#moveMark (Glib.Utf8.length new_text);
680 buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext
682 method private _retract offset status new_statements new_history =
683 NCicLibrary.time_travel status;
684 statements <- new_statements;
685 history <- new_history;
686 self#moveMark (- offset)
688 method advance ?statement () =
690 self#_advance ?statement ();
693 | Margin -> self#notify
694 | Not_found -> assert false
695 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
696 | exc -> self#notify; raise exc
700 let cmp,new_statements,new_history,status =
701 match statements,history with
702 stat::statements, _::(status::_ as history) ->
703 assert (Glib.Utf8.validate stat);
704 Glib.Utf8.length stat, statements, history, status
705 | [],[_] -> raise Margin
706 | _,_ -> assert false
708 self#_retract cmp status new_statements new_history;
711 | Margin -> self#notify
712 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
713 | exc -> self#notify; raise exc
715 method private getFuture =
716 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
717 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
720 method expandAllVirtuals =
721 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
722 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
723 buffer#delete ~start:lock ~stop:buffer#end_iter;
724 let text = Pcre.replace ~pat:":=" ~templ:"\\def" text in
725 let text = Pcre.replace ~pat:"->" ~templ:"\\to" text in
726 let text = Pcre.replace ~pat:"=>" ~templ:"\\Rightarrow" text in
728 Pcre.substitute_substrings
730 let pristine = Pcre.get_substring str 0 in
732 if pristine.[0] = ' ' then
733 String.sub pristine 1 (String.length pristine -1)
737 if input.[String.length input-1] = ' ' then
738 String.sub input 0 (String.length input -1)
742 if input = "\\forall" ||
743 input = "\\lambda" ||
744 input = "\\exists" then "","" else " ", " "
747 before ^ Glib.Utf8.from_unichar
748 (snd (Virtuals.symbol_of_virtual input)) ^ after
749 with Virtuals.Not_a_virtual -> pristine)
750 ~pat:" ?\\\\[a-zA-Z]+ ?" text
752 buffer#insert ~iter:lock text
754 (** @param rel_offset relative offset from current position of locked_mark *)
755 method private moveMark rel_offset =
756 let mark = `MARK locked_mark in
757 let old_insert = buffer#get_iter_at_mark `INSERT in
758 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
759 let current_mark_pos = buffer#get_iter_at_mark mark in
761 match rel_offset with
762 | 0 -> current_mark_pos
763 | n when n > 0 -> current_mark_pos#forward_chars n
764 | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
766 buffer#move_mark mark ~where:new_mark_pos;
767 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
768 buffer#move_mark `INSERT old_insert;
769 let mark_position = buffer#get_iter_at_mark mark in
770 if source_view#move_mark_onscreen mark then
772 buffer#move_mark mark mark_position;
773 source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
775 while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
777 method clean_dirty_lock =
778 let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
779 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
780 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
782 val mutable observers = []
784 method addObserver (o: GrafiteTypes.status -> unit) =
785 observers <- o :: observers
787 method private notify =
788 let status = self#status in
789 List.iter (fun o -> o status) observers
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 >)