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 (* WR: skipped_txt, nonskipped_txt servono ancora?
69 * (ora non abbiamo più gli alias e il codice sembra più complicato
71 * (rif. nota 11/05/11 *)
72 let eval_with_engine include_paths status skipped_txt nonskipped_txt st
74 let parsed_text_length =
75 String.length skipped_txt + String.length nonskipped_txt
77 let text = skipped_txt ^ nonskipped_txt in
78 let prefix_len = MatitaGtkMisc.utf8_string_length skipped_txt in
80 MatitaEngine.eval_ast ~include_paths ~do_heavy_checks:(Helm_registry.get_bool
81 "matita.do_heavy_checks")
82 status (text,prefix_len,st)
84 let res = new_status,skipped_txt ^ nonskipped_txt in
85 res,"",parsed_text_length
88 let pp_eager_statement_ast = GrafiteAstPp.pp_statement
90 let eval_nmacro include_paths (buffer : GText.buffer) status unparsed_text parsed_text script mac =
91 let parsed_text_length = String.length parsed_text in
93 | TA.Screenshot (_,name) ->
94 let status = script#status in
95 let _,_,menv,subst,_ = status#obj in
96 let name = Filename.dirname (script#filename) ^ "/" ^ name in
98 let selected = Continuationals.Stack.head_goals status#stack in
99 List.filter (fun x,_ -> List.mem x selected) menv
101 CicMathView.screenshot status sequents menv subst name;
102 (status, parsed_text), "", parsed_text_length
104 let status = script#status in
105 let _,_,menv,subst,_ = status#obj in
107 match Continuationals.Stack.head_goals status#stack with
112 "Many goals focused. Using the context of the first one\n";
113 let _, ctx, _ = NCicUtils.lookup_meta g menv in
115 let m, s, status, t =
116 GrafiteDisambiguate.disambiguate_nterm
117 status None ctx menv subst (parsed_text,parsed_text_length,
118 NotationPt.Cast (t,NotationPt.Implicit `JustOne))
119 (* XXX use the metasenv, if possible *)
121 MatitaMathView.cicBrowser (Some (`NCic (t,ctx,m,s)));
122 (status, parsed_text), "", parsed_text_length
123 | TA.NIntroGuess _loc ->
124 let names_ref = ref [] in
125 let s = NTactics.intros_tac ~names_ref [] script#status in
126 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
127 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
128 (s, nl ^ "#" ^ String.concat " " !names_ref ^ ";"), "", parsed_text_length
129 | TA.NAutoInteractive (_loc, (None,a)) ->
130 let trace_ref = ref [] in
131 let s = NnAuto.auto_tac ~params:(None,a) ~trace_ref script#status in
133 try List.assoc "depth" a
136 let trace = "/"^(if int_of_string depth > 1 then depth else "")^"/ by " in
138 match !trace_ref with
142 (HExtlib.filter_map (function
143 | NotationPt.NRef r -> Some (NCicPp.r2s status true r)
147 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
148 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
149 (s, nl ^ trace ^ thms ^ ";"), "", parsed_text_length
150 | TA.NAutoInteractive (_, (Some _,_)) -> assert false
152 let rec eval_executable include_paths (buffer : GText.buffer)
153 status unparsed_text skipped_txt nonskipped_txt script ex loc
156 ignore (buffer#move_mark (`NAME "beginning_of_statement")
157 ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
158 (Glib.Utf8.length skipped_txt))) ;
159 eval_with_engine include_paths status skipped_txt nonskipped_txt
160 (TA.Executable (loc, ex))
162 MatitaTypes.Cancel -> (status,skipped_txt), "", 0
163 | GrafiteEngine.NMacro (_loc,macro) ->
164 eval_nmacro include_paths buffer status
165 unparsed_text (skipped_txt ^ nonskipped_txt) script macro
168 and eval_statement include_paths (buffer : GText.buffer) status script
171 let st,unparsed_text =
174 if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
176 GrafiteParser.parsable_statement status
177 (Ulexing.from_utf8_string text) in
178 let ast = MatitaEngine.get_ast status include_paths strm in
180 | `Ast (st, text) -> st, text
182 let text_of_loc floc =
183 let nonskipped_txt,_ = HExtlib.utf8_parsed_text unparsed_text floc in
184 let start, stop = HExtlib.loc_of_floc floc in
185 let floc = HExtlib.floc_of_loc (0, start) in
186 let skipped_txt,_ = HExtlib.utf8_parsed_text unparsed_text floc in
187 let floc = HExtlib.floc_of_loc (0, stop) in
188 let txt,len = HExtlib.utf8_parsed_text unparsed_text floc in
189 txt,nonskipped_txt,skipped_txt,len
192 | GrafiteAst.Executable (loc, ex) ->
193 let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
194 eval_executable include_paths buffer status unparsed_text
195 skipped nonskipped script ex loc
196 | GrafiteAst.Comment (loc, GrafiteAst.Code (_, ex))
197 when Helm_registry.get_bool "matita.execcomments" ->
198 let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
199 eval_executable include_paths buffer status unparsed_text
200 skipped nonskipped script ex loc
201 | GrafiteAst.Comment (loc, _) ->
202 let parsed_text, _, _, parsed_text_length = text_of_loc loc in
203 let remain_len = String.length unparsed_text - parsed_text_length in
204 let s = String.sub unparsed_text parsed_text_length remain_len in
207 eval_statement include_paths buffer status script (`Raw s)
209 HExtlib.Localized (floc, exn) ->
210 HExtlib.raise_localized_exception
211 ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
212 (* | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
214 (MultiPassDisambiguator.DisambiguationError
215 (offset+parsed_text_length, errorll)) *)
217 assert (text=""); (* no macros inside comments, please! *)
219 (st,parsed_text ^ text),"",parsed_text_length + len
221 let fresh_script_id =
225 (** Selection handling
226 * Two clipboards are used: "clipboard" and "primary".
227 * "primary" is used by X, when you hit the middle button mouse is content is
228 * pasted between applications. In Matita this selection always contain the
229 * textual version of the selected term.
230 * "clipboard" is used inside Matita only and support ATM two different targets:
231 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
234 class script ~(parent:GBin.scrolled_window) ~tab_label () =
236 GSourceView2.source_view
238 ~insert_spaces_instead_of_tabs:true ~tab_width:2
239 ~right_margin_position:80 ~show_right_margin:true
240 ~smart_home_end:`AFTER
243 let buffer = source_view#buffer in
244 let source_buffer = source_view#source_buffer in
245 let similarsymbols_tag_name = "similarsymbolos" in
246 let similarsymbols_tag = `NAME similarsymbols_tag_name in
247 let initial_statuses current baseuri =
248 (* FIXME : currently hard coded to single user mode *)
249 let status = new MatitaEngine.status None baseuri in
252 NCicLibrary.time_travel status;
254 (* MATITA 1.0: there is a known bug in invalidation; temporary fix here *)
255 NCicEnvironment.invalidate () *)
259 let read_include_paths file =
261 let root, _buri, _fname, _tgt =
262 Librarian.baseuri_of_script ~include_paths:[] file in
265 Str.split (Str.regexp " ")
266 (List.assoc "include_paths" (Librarian.load_root_file (root^"/root")))
269 let rc = root :: includes in
270 List.iter (HLog.debug) rc; rc
271 with Librarian.NoRootFor _ | Librarian.FileNotFound _ ->
274 let default_buri = "cic:/matita/tests" in
275 let default_fname = ".unnamed.ma" in
277 val mutable include_paths_ = []
278 val clipboard = GData.clipboard Gdk.Atom.clipboard
279 (*val primary = GData.clipboard Gdk.Atom.primary*)
280 val mutable similarsymbols = []
281 val mutable similarsymbols_orig = []
282 val similar_memory = Hashtbl.create 97
283 val mutable old_used_memory = false
285 val scriptId = fresh_script_id ()
287 val mutable filename_ = (None : string option)
289 method has_name = filename_ <> None
291 method source_view = source_view
293 method include_paths =
295 Helm_registry.get_list Helm_registry.string "matita.includes"
297 method private curdir =
299 let root, _buri, _fname, _tgt =
300 Librarian.baseuri_of_script ~include_paths:self#include_paths
304 with Librarian.NoRootFor _ -> Sys.getcwd ()
306 method buri_of_current_file =
308 | None -> default_buri
311 let _root, buri, _fname, _tgt =
312 Librarian.baseuri_of_script ~include_paths:self#include_paths f
315 with Librarian.NoRootFor _ | Librarian.FileNotFound _ -> default_buri
317 method filename = match filename_ with None -> default_fname | Some f -> f
321 (source_view#source_buffer#begin_not_undoable_action ();
324 source_view#source_buffer#end_not_undoable_action ());
325 MatitaMisc.observe_font_size (fun font_size ->
326 source_view#misc#modify_font_by_name
327 (sprintf "%s %d" BuildTimeConf.script_font font_size));
328 source_view#misc#grab_focus ();
329 ignore(source_view#source_buffer#set_language
330 (Some MatitaGtkMisc.matita_lang));
331 ignore(source_view#source_buffer#set_highlight_syntax true);
332 ignore(source_view#connect#after#paste_clipboard
333 ~callback:(fun () -> self#clean_dirty_lock));
334 ignore (GMain.Timeout.add ~ms:300000
335 ~callback:(fun _ -> self#_saveToBackupFile ();true));
336 ignore (buffer#connect#changed
338 let curpos = buffer#cursor_position in
339 HLog.debug ("cursor at " ^ (string_of_int curpos))));
340 ignore (buffer#connect#modified_changed
341 (fun _ -> self#set_star buffer#modified));
342 (* clean_locked is set to true only "during" a PRIMARY paste
343 operation (i.e. by clicking with the second mouse button) *)
344 let clean_locked = ref false in
345 ignore(source_view#event#connect#button_press
348 if GdkEvent.Button.button button = 2 then
349 clean_locked := true;
352 ignore(source_view#event#connect#button_release
353 ~callback:(fun button -> clean_locked := false; false));
354 ignore(source_view#buffer#connect#after#apply_tag
356 fun tag ~start:_ ~stop:_ ->
358 tag#get_oid = self#locked_tag#get_oid
361 clean_locked := false;
362 self#clean_dirty_lock;
365 ignore(source_view#source_buffer#connect#after#insert_text
366 ~callback:(fun iter str ->
367 if (MatitaMisc.get_gui ())#main#menuitemAutoAltL#active && (str = " " || str = "\n") then
368 ignore(self#expand_virtual_if_any iter str)));
369 ignore(source_view#connect#after#populate_popup
370 ~callback:(fun pre_menu ->
371 let menu = new GMenu.menu pre_menu in
372 let menuItems = menu#children in
373 let undoMenuItem, redoMenuItem =
375 [undo;redo;sep1;cut;copy;paste;delete;sep2;
376 selectall;sep3;inputmethod;insertunicodecharacter] ->
377 List.iter menu#remove [ copy; cut; delete; paste ];
379 | _ -> assert false in
381 let i = ref 2 in (* last occupied position *)
382 fun ?label ?stock () ->
384 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
387 let copy = add_menu_item ~stock:`COPY () in
388 let cut = add_menu_item ~stock:`CUT () in
389 let delete = add_menu_item ~stock:`DELETE () in
390 let paste = add_menu_item ~stock:`PASTE () in
391 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
392 copy#misc#set_sensitive self#canCopy;
393 cut#misc#set_sensitive self#canCut;
394 delete#misc#set_sensitive self#canDelete;
395 paste#misc#set_sensitive self#canPaste;
396 paste_pattern#misc#set_sensitive self#canPastePattern;
397 MatitaGtkMisc.connect_menu_item copy self#copy;
398 MatitaGtkMisc.connect_menu_item cut self#cut;
399 MatitaGtkMisc.connect_menu_item delete self#delete;
400 MatitaGtkMisc.connect_menu_item paste self#paste;
401 MatitaGtkMisc.connect_menu_item paste_pattern self#pastePattern;
402 let new_undoMenuItem =
403 GMenu.image_menu_item
404 ~image:(GMisc.image ~stock:`UNDO ())
407 ~packing:(menu#insert ~pos:0) () in
408 new_undoMenuItem#misc#set_sensitive
409 (undoMenuItem#misc#get_flag `SENSITIVE);
410 menu#remove (undoMenuItem :> GMenu.menu_item);
411 MatitaGtkMisc.connect_menu_item new_undoMenuItem
412 (fun () -> self#safe_undo);
413 let new_redoMenuItem =
414 GMenu.image_menu_item
415 ~image:(GMisc.image ~stock:`REDO ())
418 ~packing:(menu#insert ~pos:1) () in
419 new_redoMenuItem#misc#set_sensitive
420 (redoMenuItem#misc#get_flag `SENSITIVE);
421 menu#remove (redoMenuItem :> GMenu.menu_item);
422 MatitaGtkMisc.connect_menu_item new_redoMenuItem
423 (fun () -> self#safe_redo)));
425 val mutable statements = [] (** executed statements *)
427 val mutable history = [ initial_statuses None default_buri ]
428 (** list of states before having executed statements. Head element of this
429 * list is the current state, last element is the state at the beginning of
431 * Invariant: this list length is 1 + length of statements *)
433 (** text mark and tag representing locked part of a script *)
435 buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
436 val beginning_of_statement_mark =
437 buffer#create_mark ~name:"beginning_of_statement"
438 ~left_gravity:true buffer#start_iter
439 val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
440 val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
442 (** unicode handling *)
443 method nextSimilarSymbol =
444 let write_similarsymbol s =
445 let s = Glib.Utf8.from_unichar s in
446 let iter = source_view#source_buffer#get_iter_at_mark `INSERT in
447 assert(Glib.Utf8.validate s);
448 source_view#source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
449 source_view#source_buffer#insert ~iter:(source_view#source_buffer#get_iter_at_mark `INSERT) s;
450 (try source_view#source_buffer#delete_mark similarsymbols_tag
451 with GText.No_such_mark _ -> ());
452 ignore(source_view#source_buffer#create_mark ~name:similarsymbols_tag_name
453 (source_view#source_buffer#get_iter_at_mark `INSERT));
455 let new_similarsymbol =
457 let iter_ins = source_view#source_buffer#get_iter_at_mark `INSERT in
458 let iter_lig = source_view#source_buffer#get_iter_at_mark similarsymbols_tag in
459 not (iter_ins#equal iter_lig)
460 with GText.No_such_mark _ -> true
462 if new_similarsymbol then
463 (if not(self#expand_virtual_if_any (source_view#source_buffer#get_iter_at_mark `INSERT) "")then
465 let i = source_view#source_buffer#get_iter_at_mark `INSERT in
466 Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
468 (match Virtuals.similar_symbols last_symbol with
471 similarsymbols_orig <- eqclass;
473 try Hashtbl.find similar_memory similarsymbols_orig
475 let is_used = List.map (fun x -> x,false) eqclass in
476 Hashtbl.add similar_memory eqclass is_used;
481 List.partition (fun s -> List.assoc s is_used) eqclass
483 match used @ unused with a::b::c -> a,b,c | _ -> assert false
486 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
488 old_used_memory <- List.assoc hd is_used;
490 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
492 Hashtbl.replace similar_memory similarsymbols_orig is_used;
493 write_similarsymbol hd;
494 similarsymbols <- tl @ [ hd ]))
496 match similarsymbols with
499 let is_used = Hashtbl.find similar_memory similarsymbols_orig in
500 let last = HExtlib.list_last tl in
501 let old_used_for_last = old_used_memory in
502 old_used_memory <- List.assoc hd is_used;
504 (hd, true) :: (last,old_used_for_last) ::
505 List.filter (fun (x,_) -> x <> last && x <> hd) is_used
507 Hashtbl.replace similar_memory similarsymbols_orig is_used;
508 similarsymbols <- tl @ [ hd ];
509 write_similarsymbol hd
511 method private reset_similarsymbols =
512 similarsymbols <- [];
513 similarsymbols_orig <- [];
514 try source_view#source_buffer#delete_mark similarsymbols_tag
515 with GText.No_such_mark _ -> ()
517 method private expand_virtual_if_any iter tok =
519 let len = MatitaGtkMisc.utf8_string_length tok in
521 let prev = iter#copy#backward_chars len in
522 prev#get_slice ~stop:(prev#copy#backward_find_char
523 (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
525 let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
526 self#reset_similarsymbols;
527 let s = Glib.Utf8.from_unichar symb in
528 assert(Glib.Utf8.validate s);
529 source_view#source_buffer#delete ~start:iter
530 ~stop:(iter#copy#backward_chars
531 (MatitaGtkMisc.utf8_string_length inplaceof + len));
532 source_view#source_buffer#insert ~iter
533 (if inplaceof.[0] = '\\' then s else (s ^ tok));
535 with Virtuals.Not_a_virtual -> false
537 (** selections / clipboards handling *)
539 method markupSelected = MatitaMathView.has_selection ()
540 method private textSelected =
541 (source_view#source_buffer#get_iter_at_mark `INSERT)#compare
542 (source_view#source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
543 method private markupStored = MatitaMathView.has_clipboard ()
544 method private textStored = clipboard#text <> None
545 method canCopy = self#textSelected
546 method canCut = self#textSelected
547 method canDelete = self#textSelected
548 (*CSC: WRONG CODE: we should look in the clipboard instead! *)
549 method canPaste = self#markupStored || self#textStored
550 method canPastePattern = self#markupStored
553 (* phase 1: we save the actual status of the marks and we undo *)
554 let locked_mark = `MARK (self#locked_mark) in
555 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
556 let locked_iter_offset = locked_iter#offset in
559 (source_view#buffer#create_mark ~name:"lock_point"
560 ~left_gravity:true locked_iter) in
561 source_view#source_buffer#undo ();
562 (* phase 2: we save the cursor position and we redo, restoring
563 the previous status of all the marks *)
564 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
567 (source_view#buffer#create_mark ~name:"undo_point"
568 ~left_gravity:true cursor_iter)
570 source_view#source_buffer#redo ();
571 let mark_iter = source_view#buffer#get_iter_at_mark mark in
572 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
573 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
574 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
575 source_view#buffer#delete_mark mark;
576 source_view#buffer#delete_mark mark2;
577 (* phase 3: if after the undo the cursor was in the locked area,
578 then we move it there again and we perform a goto *)
579 if mark_iter#offset < locked_iter_offset then
581 source_view#buffer#move_mark `INSERT ~where:mark_iter;
582 self#goto `Cursor ();
584 (* phase 4: we perform again the undo. This time we are sure that
585 the text to undo is not locked *)
586 source_view#source_buffer#undo ();
587 source_view#misc#grab_focus ()
590 (* phase 1: we save the actual status of the marks, we redo and
592 let locked_mark = `MARK (self#locked_mark) in
593 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
594 let locked_iter_offset = locked_iter#offset in
597 (source_view#buffer#create_mark ~name:"lock_point"
598 ~left_gravity:true locked_iter) in
599 source_view#source_buffer#redo ();
600 source_view#source_buffer#undo ();
601 (* phase 2: we save the cursor position and we restore
602 the previous status of all the marks *)
603 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
606 (source_view#buffer#create_mark ~name:"undo_point"
607 ~left_gravity:true cursor_iter)
609 let mark_iter = source_view#buffer#get_iter_at_mark mark in
610 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
611 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
612 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
613 source_view#buffer#delete_mark mark;
614 source_view#buffer#delete_mark mark2;
615 (* phase 3: if after the undo the cursor is in the locked area,
616 then we move it there again and we perform a goto *)
617 if mark_iter#offset < locked_iter_offset then
619 source_view#buffer#move_mark `INSERT ~where:mark_iter;
620 self#goto `Cursor ();
622 (* phase 4: we perform again the redo. This time we are sure that
623 the text to redo is not locked *)
624 source_view#source_buffer#redo ();
625 source_view#misc#grab_focus ()
631 MatitaMathView.empty_clipboard ();
632 source_view#buffer#copy_clipboard clipboard;
634 MatitaMathView.copy_selection ()
637 source_view#buffer#cut_clipboard clipboard;
638 MatitaMathView.empty_clipboard ()
641 ignore (source_view#buffer#delete_selection ())
644 if MatitaMathView.has_clipboard ()
645 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
646 else source_view#buffer#paste_clipboard clipboard;
647 self#clean_dirty_lock
649 method pastePattern () =
650 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
652 method locked_mark = locked_mark
653 method locked_tag = locked_tag
654 method error_tag = error_tag
656 (* history can't be empty, the invariant above grant that it contains at
657 * least the init grafite_status *)
658 method status = match history with s::_ -> s | _ -> assert false
660 method private _advance ?statement () =
661 let s = match statement with Some s -> s | None -> self#getFuture in
662 if self#bos then LibraryClean.clean_baseuris [self#buri_of_current_file];
663 HLog.debug ("evaluating: " ^ first_line s ^ " ...");
664 let time1 = Unix.gettimeofday () in
665 let entries, newtext, parsed_len =
667 eval_statement self#include_paths buffer self#status self (`Raw s)
668 with End_of_file -> raise Margin
670 let time2 = Unix.gettimeofday () in
671 HLog.debug ("... done in " ^ string_of_float (time2 -. time1) ^ "s");
672 let new_statuses, new_statements = entries in
673 history <- new_statuses :: history;
674 statements <- new_statements :: statements;
675 let start = buffer#get_iter_at_mark (`MARK locked_mark) in
676 if statement <> None then
677 buffer#insert ~iter:start new_statements
679 let parsed_text = String.sub s 0 parsed_len in
680 if new_statements <> parsed_text then begin
681 let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
682 buffer#delete ~start ~stop;
683 buffer#insert ~iter:start new_statements;
686 self#moveMark (Glib.Utf8.length new_statements);
687 buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark))
690 method private _retract offset status new_statements new_history =
691 NCicLibrary.time_travel status;
692 statements <- new_statements;
693 history <- new_history;
694 self#moveMark (- offset)
696 method advance ?statement () =
698 self#_advance ?statement ();
701 | Margin -> self#notify
702 | Not_found -> assert false
703 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
704 | exc -> self#notify; raise exc
708 let cmp,new_statements,new_history,status =
709 match statements,history with
710 stat::statements, _::(status::_ as history) ->
711 assert (Glib.Utf8.validate stat);
712 Glib.Utf8.length stat, statements, history, status
713 | [],[_] -> raise Margin
714 | _,_ -> assert false
716 self#_retract cmp status new_statements new_history;
719 | Margin -> self#notify
720 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
721 | exc -> self#notify; raise exc
723 method private getFuture =
724 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
725 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
728 method expandAllVirtuals =
729 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
730 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
731 buffer#delete ~start:lock ~stop:buffer#end_iter;
732 let text = Pcre.replace ~pat:":=" ~templ:"\\def" text in
733 let text = Pcre.replace ~pat:"->" ~templ:"\\to" text in
734 let text = Pcre.replace ~pat:"=>" ~templ:"\\Rightarrow" text in
736 Pcre.substitute_substrings
738 let pristine = Pcre.get_substring str 0 in
740 if pristine.[0] = ' ' then
741 String.sub pristine 1 (String.length pristine -1)
745 if input.[String.length input-1] = ' ' then
746 String.sub input 0 (String.length input -1)
750 if input = "\\forall" ||
751 input = "\\lambda" ||
752 input = "\\exists" then "","" else " ", " "
755 before ^ Glib.Utf8.from_unichar
756 (snd (Virtuals.symbol_of_virtual input)) ^ after
757 with Virtuals.Not_a_virtual -> pristine)
758 ~pat:" ?\\\\[a-zA-Z]+ ?" text
760 buffer#insert ~iter:lock text
762 (** @param rel_offset relative offset from current position of locked_mark *)
763 method private moveMark rel_offset =
764 let mark = `MARK locked_mark in
765 let old_insert = buffer#get_iter_at_mark `INSERT in
766 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
767 let current_mark_pos = buffer#get_iter_at_mark mark in
769 match rel_offset with
770 | 0 -> current_mark_pos
771 | n when n > 0 -> current_mark_pos#forward_chars n
772 | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
774 buffer#move_mark mark ~where:new_mark_pos;
775 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
776 buffer#move_mark `INSERT old_insert;
777 let mark_position = buffer#get_iter_at_mark mark in
778 if source_view#move_mark_onscreen mark then
780 buffer#move_mark mark mark_position;
781 source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
783 while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
785 method clean_dirty_lock =
786 let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
787 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
788 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
790 val mutable observers = []
792 method addObserver (o: GrafiteTypes.status -> unit) =
793 observers <- o :: observers
795 method private notify =
796 let status = self#status in
797 List.iter (fun o -> o status) observers
802 method loadFromFile f =
803 let script = HExtlib.input_file f in
804 let hs = MatitaScriptLexer.get_hot_spots script in
806 String.concat "\n" (List.map (fun (l1,l2,uri,desc) ->
807 let a,b = HExtlib.loc_of_floc l1 in
808 let c,d = HExtlib.loc_of_floc l2 in
809 let uri = match uri with None -> "()" | Some s -> s in
810 let desc = match desc with None -> "()" | Some s -> s in
811 Printf.sprintf "[%d,%d] [%d,%d] '%s' '%s'" a b c d uri desc) hs)
814 buffer#set_text script;
816 (* this is the default tag for the whole script (mainly used for
817 * setting the default behaviour when needed *)
818 let all_tag = buffer#create_tag [] in
819 buffer#apply_tag all_tag ~start:(buffer#get_iter `START)
820 ~stop:(buffer#get_iter `END);
821 ignore(all_tag#connect#event
822 ~callback:(fun ~origin event pos ->
823 match GdkEvent.get_type event with
825 Gdk.Window.set_cursor
826 (match source_view#get_window `TEXT with None -> assert false | Some x -> x)
827 (Gdk.Cursor.create `ARROW);
828 (* code for removing message from statusbar *)
832 let invisible_tag = buffer#create_tag [ `INVISIBLE true ] in
833 let apply_tag (l1,l2,uri,desc) =
835 buffer#create_tag [ `FOREGROUND "blue" ; `UNDERLINE `SINGLE] in
836 (* hyperlink_tag#connect#after#changed ~callback:(fun _ -> HLog.debug "***"); *)
837 let a,b = HExtlib.loc_of_floc l1 in
838 let c,d = HExtlib.loc_of_floc l2 in
839 (* setting invisibility for <A...> and </A> *)
840 buffer#apply_tag invisible_tag
841 ~start:(buffer#get_iter_at_char a)
842 ~stop:(buffer#get_iter_at_char b);
843 buffer#apply_tag invisible_tag
844 ~start:(buffer#get_iter_at_char c)
845 ~stop:(buffer#get_iter_at_char d);
846 (* setting hyperlink inside <A...> and </A> *)
847 (* XXX: I'm not sure why I'm required to put those -1 and +1
848 * otherwise I get too small a clickable area, especially for
849 * single characters hyperlinks. *)
850 buffer#apply_tag hyperlink_tag
851 ~start:(buffer#get_iter_at_char (b-1))
852 ~stop:(buffer#get_iter_at_char (c+1));
856 ignore(hyperlink_tag#connect#event
857 ~callback:(fun ~origin event pos ->
858 match GdkEvent.get_type event with
860 let uri' = NReference.reference_of_string uri in
861 MatitaMathView.cicBrowser (Some (`NRef uri'));
864 Gdk.Window.set_cursor
865 (match source_view#get_window `TEXT with None -> assert false | Some x -> x)
866 (Gdk.Cursor.create `HAND1);
867 (* let ctxt = (MatitaMisc.get_gui ())#main#statusBar#new_context ~name:"href" in
868 let msg = ctxt#push uri in
869 (* href_statusbar_msg <- Some (ctxt, msg);*) *)
874 List.iter apply_tag hs;
875 buffer#set_modified false
877 method assignFileName file =
880 tab_label#set_text default_fname;
882 include_paths_ <- [];
885 let f = Librarian.absolutize file in
886 tab_label#set_text (Filename.basename f);
888 include_paths_ <- read_include_paths f;
892 tab_label#set_text ((if b then "*" else "")^Filename.basename self#filename);
893 tab_label#misc#set_tooltip_text
894 ("URI: " ^ self#buri_of_current_file ^ "\nPATH: " ^ self#filename);
896 method saveToFile () =
897 if self#has_name then
898 let oc = open_out self#filename in
899 output_string oc (buffer#get_text ~start:buffer#start_iter
900 ~stop:buffer#end_iter ());
903 buffer#set_modified false
905 HLog.error "Can't save, no filename selected"
907 method private _saveToBackupFile () =
908 if buffer#modified then
910 let f = self#filename in
911 let oc = open_out f in
912 output_string oc (buffer#get_text ~start:buffer#start_iter
913 ~stop:buffer#end_iter ());
915 HLog.debug ("backup " ^ f ^ " saved")
918 method private reset_buffer =
920 history <- [ initial_statuses (Some self#status) self#buri_of_current_file ];
922 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
923 buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
927 source_buffer#begin_not_undoable_action ();
928 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
929 source_buffer#end_not_undoable_action ();
930 buffer#set_modified false;
933 let template = HExtlib.input_file BuildTimeConf.script_template in
934 buffer#insert ~iter:(buffer#get_iter `START) template;
935 buffer#set_modified false;
938 method goto (pos: [`Top | `Bottom | `Cursor]) () =
940 let old_locked_mark =
942 (buffer#create_mark ~name:"old_locked_mark"
943 ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
944 let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in
945 let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in
946 let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
949 dispose_old_locked_mark ();
956 let newpos = getpos () in
957 if (getoldpos ())#compare newpos < 0 then
959 buffer#move_mark old_locked_mark newpos;
964 dispose_old_locked_mark ();
967 | Margin -> dispose_old_locked_mark (); self#notify
968 | exc -> dispose_old_locked_mark (); self#notify; raise exc)
970 let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
971 let cursor_iter () = buffer#get_iter_at_mark `INSERT in
974 (buffer#create_mark ~name:"initial_insert"
975 ~left_gravity:true (cursor_iter ())) in
976 let dispose_remember () = buffer#delete_mark remember in
977 let remember_iter () =
978 buffer#get_iter_at_mark (`NAME "initial_insert") in
979 let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
981 let forward_until_cursor () = (* go forward until locked > cursor *)
984 if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0
987 buffer#move_mark old_locked_mark (getpos ());
993 let rec back_until_cursor len = (* go backward until locked < cursor *)
995 statements, ((status)::_ as history)
997 self#_retract (icmp - len) status statements
999 | statement::tl1, _::tl2 ->
1000 back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
1001 | _,_ -> assert false
1005 if icmp < 0 then (* locked < cursor *)
1006 (forward_until_cursor (); self#notify)
1007 else if icmp > 0 then (* locked > cursor *)
1008 (back_until_cursor icmp (statements,history); self#notify)
1009 else (* cursor = locked *)
1012 dispose_remember ();
1013 dispose_old_locked_mark ();
1015 | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
1016 | exc -> dispose_remember (); dispose_old_locked_mark ();
1017 self#notify; raise exc)
1018 with Invalid_argument "Array.make" ->
1019 HLog.error "The script is too big!\n"
1026 method eos = MatitaEngine.eos self#status self#getFuture
1030 HLog.debug "script status:";
1031 HLog.debug ("history size: " ^ string_of_int (List.length history));
1032 HLog.debug (sprintf "%d statements:" (List.length statements));
1033 List.iter HLog.debug statements;
1034 HLog.debug ("Current file name: " ^ self#filename);
1036 method has_parent (p : GObj.widget) = parent#coerce#misc#get_oid = p#misc#get_oid
1039 let _script = ref []
1041 let script ~parent ~tab_label ()
1043 let s = new script ~parent ~tab_label () in
1044 _script := s::!_script;
1048 let notebook = (MatitaMisc.get_gui ())#main#scriptNotebook in
1049 let parent = notebook#get_nth_page page in
1051 List.find (fun s -> s#has_parent parent) !_script
1053 Not_found -> assert false
1057 at_page ((MatitaMisc.get_gui ())#main#scriptNotebook#current_page)
1060 let s = at_page page in
1061 _script := List.filter ((<>) s) !_script
1064 let iter_scripts f = List.iter f !_script;;
1067 CicMathView.register_matita_script_current (current :> unit -> < advance: ?statement:string -> unit -> unit; status: GrafiteTypes.status >)