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";
121 let _, ctx, _ = NCicUtils.lookup_meta g menv in ctx
122 with NCicUtils.Meta_not_found _ ->
123 HLog.warn "Current goal is closed. Using empty context.";
127 let m, s, status, t =
128 GrafiteDisambiguate.disambiguate_nterm
129 status `XTNone ctx menv subst (parsed_text,parsed_text_length,
130 NotationPt.Cast (t,NotationPt.Implicit `JustOne))
131 (* XXX use the metasenv, if possible *)
133 MatitaMathView.cicBrowser (Some (`NCic (t,ctx,m,s)));
134 [status, parsed_text], "", parsed_text_length
135 | TA.NIntroGuess _loc ->
136 let names_ref = ref [] in
137 let s = NTactics.intros_tac ~names_ref [] script#status in
138 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
139 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
140 [s, nl ^ "#" ^ String.concat " #" !names_ref], "", parsed_text_length
141 | TA.NAutoInteractive (_loc, (None,a)) ->
142 let trace_ref = ref [] in
143 let s = NnAuto.auto_tac ~params:(None,a) ~trace_ref script#status in
145 try List.assoc "depth" a
148 let trace = "/"^(if int_of_string depth > 1 then depth else "")^" by " in
150 match !trace_ref with
154 (HExtlib.filter_map (function
155 | NotationPt.NRef r -> Some (NCicPp.r2s status true r)
159 let rex = Pcre.regexp ~flags:[`MULTILINE] "\\A([\\n\\t\\r ]*).*\\Z" in
160 let nl = Pcre.replace ~rex ~templ:"$1" parsed_text in
161 [s, nl ^ trace ^ thms ^ "/"], "", parsed_text_length
162 | TA.NAutoInteractive (_, (Some _,_)) -> assert false
164 let rec eval_executable include_paths (buffer : GText.buffer)
165 status unparsed_text skipped_txt nonskipped_txt script ex loc
168 ignore (buffer#move_mark (`NAME "beginning_of_statement")
169 ~where:((buffer#get_iter_at_mark (`NAME "locked"))#forward_chars
170 (Glib.Utf8.length skipped_txt))) ;
171 eval_with_engine include_paths status skipped_txt nonskipped_txt
172 (TA.Executable (loc, ex))
174 MatitaTypes.Cancel -> [], "", 0
175 | GrafiteEngine.NMacro (_loc,macro) ->
176 eval_nmacro include_paths buffer status
177 unparsed_text (skipped_txt ^ nonskipped_txt) script macro
180 and eval_statement include_paths (buffer : GText.buffer) status script
183 let st,unparsed_text =
186 if Pcre.pmatch ~rex:only_dust_RE text then raise Margin;
188 GrafiteParser.parsable_statement status
189 (Ulexing.from_utf8_string text) in
190 let ast = MatitaEngine.get_ast status include_paths strm in
192 | `Ast (st, text) -> st, text
194 let text_of_loc floc =
195 let nonskipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
196 let start, stop = HExtlib.loc_of_floc floc in
197 let floc = HExtlib.floc_of_loc (0, start) in
198 let skipped_txt,_ = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
199 let floc = HExtlib.floc_of_loc (0, stop) in
200 let txt,len = MatitaGtkMisc.utf8_parsed_text unparsed_text floc in
201 txt,nonskipped_txt,skipped_txt,len
204 | GrafiteAst.Executable (loc, ex) ->
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, GrafiteAst.Code (_, ex))
209 when Helm_registry.get_bool "matita.execcomments" ->
210 let _, nonskipped, skipped, parsed_text_length = text_of_loc loc in
211 eval_executable include_paths buffer status unparsed_text
212 skipped nonskipped script ex loc
213 | GrafiteAst.Comment (loc, _) ->
214 let parsed_text, _, _, parsed_text_length = text_of_loc loc in
215 let remain_len = String.length unparsed_text - parsed_text_length in
216 let s = String.sub unparsed_text parsed_text_length remain_len in
219 eval_statement include_paths buffer status script (`Raw s)
221 HExtlib.Localized (floc, exn) ->
222 HExtlib.raise_localized_exception
223 ~offset:(MatitaGtkMisc.utf8_string_length parsed_text) floc exn
224 | MultiPassDisambiguator.DisambiguationError (offset,errorll) ->
226 (MultiPassDisambiguator.DisambiguationError
227 (offset+parsed_text_length, errorll))
229 assert (text=""); (* no macros inside comments, please! *)
231 | (statuses,text)::tl ->
232 (statuses,parsed_text ^ text)::tl,"",parsed_text_length + len
235 let fresh_script_id =
239 (** Selection handling
240 * Two clipboards are used: "clipboard" and "primary".
241 * "primary" is used by X, when you hit the middle button mouse is content is
242 * pasted between applications. In Matita this selection always contain the
243 * textual version of the selected term.
244 * "clipboard" is used inside Matita only and support ATM two different targets:
245 * "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
248 class script ~(parent:GBin.scrolled_window) ~tab_label () =
250 GSourceView2.source_view
252 ~insert_spaces_instead_of_tabs:true ~tab_width:2
253 ~right_margin_position:80 ~show_right_margin:true
254 ~smart_home_end:`AFTER
257 let buffer = source_view#buffer in
258 let source_buffer = source_view#source_buffer in
259 let similarsymbols_tag_name = "similarsymbolos" in
260 let similarsymbols_tag = `NAME similarsymbols_tag_name in
261 let initial_statuses current baseuri =
262 let status = new MatitaEngine.status baseuri in
264 Some current -> NCicLibrary.time_travel status;
266 (* MATITA 1.0: there is a known bug in invalidation; temporary fix here *)
267 NCicEnvironment.invalidate () *)
271 let default_buri = "cic:/matita/tests" in
272 let default_fname = ".unnamed.ma" in
274 val mutable include_paths_ = []
275 val clipboard = GData.clipboard Gdk.Atom.clipboard
276 (*val primary = GData.clipboard Gdk.Atom.primary*)
277 val mutable similarsymbols = []
278 val mutable similarsymbols_orig = []
279 val similar_memory = Hashtbl.create 97
280 val mutable old_used_memory = false
282 val scriptId = fresh_script_id ()
284 val mutable filename_ = (None : string option)
286 method has_name = filename_ <> None
288 method source_view = source_view
290 method include_paths =
292 Helm_registry.get_list Helm_registry.string "matita.includes"
294 method private curdir =
296 let root, _buri, _fname, _tgt =
297 Librarian.baseuri_of_script ~include_paths:self#include_paths
301 with Librarian.NoRootFor _ -> Sys.getcwd ()
303 method buri_of_current_file =
305 | None -> default_buri
308 let _root, buri, _fname, _tgt =
309 Librarian.baseuri_of_script ~include_paths:self#include_paths f
312 with Librarian.NoRootFor _ | Librarian.FileNotFound _ -> default_buri
314 method filename = match filename_ with None -> default_fname | Some f -> f
318 (source_view#source_buffer#begin_not_undoable_action ();
321 source_view#source_buffer#end_not_undoable_action ());
322 MatitaMisc.observe_font_size (fun font_size ->
323 source_view#misc#modify_font_by_name
324 (sprintf "%s %d" BuildTimeConf.script_font font_size));
325 source_view#misc#grab_focus ();
326 ignore(source_view#source_buffer#set_language
327 (Some MatitaGtkMisc.matita_lang));
328 ignore(source_view#source_buffer#set_highlight_syntax true);
329 ignore(source_view#connect#after#paste_clipboard
330 ~callback:(fun () -> self#clean_dirty_lock));
331 ignore (GMain.Timeout.add ~ms:300000
332 ~callback:(fun _ -> self#_saveToBackupFile ();true));
333 ignore (buffer#connect#modified_changed
334 (fun _ -> self#set_star buffer#modified));
335 (* clean_locked is set to true only "during" a PRIMARY paste
336 operation (i.e. by clicking with the second mouse button) *)
337 let clean_locked = ref false in
338 ignore(source_view#event#connect#button_press
341 if GdkEvent.Button.button button = 2 then
342 clean_locked := true;
345 ignore(source_view#event#connect#button_release
346 ~callback:(fun button -> clean_locked := false; false));
347 ignore(source_view#buffer#connect#after#apply_tag
349 fun tag ~start:_ ~stop:_ ->
351 tag#get_oid = self#locked_tag#get_oid
354 clean_locked := false;
355 self#clean_dirty_lock;
358 ignore(source_view#source_buffer#connect#after#insert_text
359 ~callback:(fun iter str ->
360 if (MatitaMisc.get_gui ())#main#menuitemAutoAltL#active && (str = " " || str = "\n") then
361 ignore(self#expand_virtual_if_any iter str)));
362 ignore(source_view#connect#after#populate_popup
363 ~callback:(fun pre_menu ->
364 let menu = new GMenu.menu pre_menu in
365 let menuItems = menu#children in
366 let undoMenuItem, redoMenuItem =
368 [undo;redo;sep1;cut;copy;paste;delete;sep2;
369 selectall;sep3;inputmethod;insertunicodecharacter] ->
370 List.iter menu#remove [ copy; cut; delete; paste ];
372 | _ -> assert false in
374 let i = ref 2 in (* last occupied position *)
375 fun ?label ?stock () ->
377 GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
380 let copy = add_menu_item ~stock:`COPY () in
381 let cut = add_menu_item ~stock:`CUT () in
382 let delete = add_menu_item ~stock:`DELETE () in
383 let paste = add_menu_item ~stock:`PASTE () in
384 let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
385 copy#misc#set_sensitive self#canCopy;
386 cut#misc#set_sensitive self#canCut;
387 delete#misc#set_sensitive self#canDelete;
388 paste#misc#set_sensitive self#canPaste;
389 paste_pattern#misc#set_sensitive self#canPastePattern;
390 MatitaGtkMisc.connect_menu_item copy self#copy;
391 MatitaGtkMisc.connect_menu_item cut self#cut;
392 MatitaGtkMisc.connect_menu_item delete self#delete;
393 MatitaGtkMisc.connect_menu_item paste self#paste;
394 MatitaGtkMisc.connect_menu_item paste_pattern self#pastePattern;
395 let new_undoMenuItem =
396 GMenu.image_menu_item
397 ~image:(GMisc.image ~stock:`UNDO ())
400 ~packing:(menu#insert ~pos:0) () in
401 new_undoMenuItem#misc#set_sensitive
402 (undoMenuItem#misc#get_flag `SENSITIVE);
403 menu#remove (undoMenuItem :> GMenu.menu_item);
404 MatitaGtkMisc.connect_menu_item new_undoMenuItem
405 (fun () -> self#safe_undo);
406 let new_redoMenuItem =
407 GMenu.image_menu_item
408 ~image:(GMisc.image ~stock:`REDO ())
411 ~packing:(menu#insert ~pos:1) () in
412 new_redoMenuItem#misc#set_sensitive
413 (redoMenuItem#misc#get_flag `SENSITIVE);
414 menu#remove (redoMenuItem :> GMenu.menu_item);
415 MatitaGtkMisc.connect_menu_item new_redoMenuItem
416 (fun () -> self#safe_redo)));
418 val mutable statements = [] (** executed statements *)
420 val mutable history = [ initial_statuses None default_buri ]
421 (** list of states before having executed statements. Head element of this
422 * list is the current state, last element is the state at the beginning of
424 * Invariant: this list length is 1 + length of statements *)
426 (** text mark and tag representing locked part of a script *)
428 buffer#create_mark ~name:"locked" ~left_gravity:true buffer#start_iter
429 val beginning_of_statement_mark =
430 buffer#create_mark ~name:"beginning_of_statement"
431 ~left_gravity:true buffer#start_iter
432 val locked_tag = buffer#create_tag [`BACKGROUND "lightblue"; `EDITABLE false]
433 val error_tag = buffer#create_tag [`UNDERLINE `SINGLE; `FOREGROUND "red"]
435 (** unicode handling *)
436 method nextSimilarSymbol =
437 let write_similarsymbol s =
438 let s = Glib.Utf8.from_unichar s in
439 let iter = source_view#source_buffer#get_iter_at_mark `INSERT in
440 assert(Glib.Utf8.validate s);
441 source_view#source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars 1);
442 source_view#source_buffer#insert ~iter:(source_view#source_buffer#get_iter_at_mark `INSERT) s;
443 (try source_view#source_buffer#delete_mark similarsymbols_tag
444 with GText.No_such_mark _ -> ());
445 ignore(source_view#source_buffer#create_mark ~name:similarsymbols_tag_name
446 (source_view#source_buffer#get_iter_at_mark `INSERT));
448 let new_similarsymbol =
450 let iter_ins = source_view#source_buffer#get_iter_at_mark `INSERT in
451 let iter_lig = source_view#source_buffer#get_iter_at_mark similarsymbols_tag in
452 not (iter_ins#equal iter_lig)
453 with GText.No_such_mark _ -> true
455 if new_similarsymbol then
456 (if not(self#expand_virtual_if_any (source_view#source_buffer#get_iter_at_mark `INSERT) "")then
458 let i = source_view#source_buffer#get_iter_at_mark `INSERT in
459 Glib.Utf8.first_char (i#get_slice ~stop:(i#copy#backward_chars 1))
461 (match Virtuals.similar_symbols last_symbol with
464 similarsymbols_orig <- eqclass;
466 try Hashtbl.find similar_memory similarsymbols_orig
468 let is_used = List.map (fun x -> x,false) eqclass in
469 Hashtbl.add similar_memory eqclass is_used;
474 List.partition (fun s -> List.assoc s is_used) eqclass
476 match used @ unused with a::b::c -> a,b,c | _ -> assert false
479 if hd = last_symbol then next, tl @ [hd] else hd, (next::tl)
481 old_used_memory <- List.assoc hd is_used;
483 (hd,true) :: List.filter (fun (x,_) -> x <> hd) is_used
485 Hashtbl.replace similar_memory similarsymbols_orig is_used;
486 write_similarsymbol hd;
487 similarsymbols <- tl @ [ hd ]))
489 match similarsymbols with
492 let is_used = Hashtbl.find similar_memory similarsymbols_orig in
493 let last = HExtlib.list_last tl in
494 let old_used_for_last = old_used_memory in
495 old_used_memory <- List.assoc hd is_used;
497 (hd, true) :: (last,old_used_for_last) ::
498 List.filter (fun (x,_) -> x <> last && x <> hd) is_used
500 Hashtbl.replace similar_memory similarsymbols_orig is_used;
501 similarsymbols <- tl @ [ hd ];
502 write_similarsymbol hd
504 method private reset_similarsymbols =
505 similarsymbols <- [];
506 similarsymbols_orig <- [];
507 try source_view#source_buffer#delete_mark similarsymbols_tag
508 with GText.No_such_mark _ -> ()
510 method private expand_virtual_if_any iter tok =
512 let len = MatitaGtkMisc.utf8_string_length tok in
514 let prev = iter#copy#backward_chars len in
515 prev#get_slice ~stop:(prev#copy#backward_find_char
516 (fun x -> Glib.Unichar.isspace x || x = Glib.Utf8.first_char "\\"))
518 let inplaceof, symb = Virtuals.symbol_of_virtual last_word in
519 self#reset_similarsymbols;
520 let s = Glib.Utf8.from_unichar symb in
521 assert(Glib.Utf8.validate s);
522 source_view#source_buffer#delete ~start:iter
523 ~stop:(iter#copy#backward_chars
524 (MatitaGtkMisc.utf8_string_length inplaceof + len));
525 source_view#source_buffer#insert ~iter
526 (if inplaceof.[0] = '\\' then s else (s ^ tok));
528 with Virtuals.Not_a_virtual -> false
530 (** selections / clipboards handling *)
532 method markupSelected = MatitaMathView.has_selection ()
533 method private textSelected =
534 (source_view#source_buffer#get_iter_at_mark `INSERT)#compare
535 (source_view#source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
536 method private markupStored = MatitaMathView.has_clipboard ()
537 method private textStored = clipboard#text <> None
538 method canCopy = self#textSelected
539 method canCut = self#textSelected
540 method canDelete = self#textSelected
541 (*CSC: WRONG CODE: we should look in the clipboard instead! *)
542 method canPaste = self#markupStored || self#textStored
543 method canPastePattern = self#markupStored
546 (* phase 1: we save the actual status of the marks and we undo *)
547 let locked_mark = `MARK (self#locked_mark) in
548 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
549 let locked_iter_offset = locked_iter#offset in
552 (source_view#buffer#create_mark ~name:"lock_point"
553 ~left_gravity:true locked_iter) in
554 source_view#source_buffer#undo ();
555 (* phase 2: we save the cursor position and we redo, restoring
556 the previous status of all the marks *)
557 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
560 (source_view#buffer#create_mark ~name:"undo_point"
561 ~left_gravity:true cursor_iter)
563 source_view#source_buffer#redo ();
564 let mark_iter = source_view#buffer#get_iter_at_mark mark in
565 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
566 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
567 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
568 source_view#buffer#delete_mark mark;
569 source_view#buffer#delete_mark mark2;
570 (* phase 3: if after the undo the cursor was in the locked area,
571 then we move it there again and we perform a goto *)
572 if mark_iter#offset < locked_iter_offset then
574 source_view#buffer#move_mark `INSERT ~where:mark_iter;
575 self#goto `Cursor ();
577 (* phase 4: we perform again the undo. This time we are sure that
578 the text to undo is not locked *)
579 source_view#source_buffer#undo ();
580 source_view#misc#grab_focus ()
583 (* phase 1: we save the actual status of the marks, we redo and
585 let locked_mark = `MARK (self#locked_mark) in
586 let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
587 let locked_iter_offset = locked_iter#offset in
590 (source_view#buffer#create_mark ~name:"lock_point"
591 ~left_gravity:true locked_iter) in
592 source_view#source_buffer#redo ();
593 source_view#source_buffer#undo ();
594 (* phase 2: we save the cursor position and we restore
595 the previous status of all the marks *)
596 let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
599 (source_view#buffer#create_mark ~name:"undo_point"
600 ~left_gravity:true cursor_iter)
602 let mark_iter = source_view#buffer#get_iter_at_mark mark in
603 let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
604 let mark2_iter = mark2_iter#set_offset locked_iter_offset in
605 source_view#buffer#move_mark locked_mark ~where:mark2_iter;
606 source_view#buffer#delete_mark mark;
607 source_view#buffer#delete_mark mark2;
608 (* phase 3: if after the undo the cursor is in the locked area,
609 then we move it there again and we perform a goto *)
610 if mark_iter#offset < locked_iter_offset then
612 source_view#buffer#move_mark `INSERT ~where:mark_iter;
613 self#goto `Cursor ();
615 (* phase 4: we perform again the redo. This time we are sure that
616 the text to redo is not locked *)
617 source_view#source_buffer#redo ();
618 source_view#misc#grab_focus ()
624 MatitaMathView.empty_clipboard ();
625 source_view#buffer#copy_clipboard clipboard;
627 MatitaMathView.copy_selection ()
630 source_view#buffer#cut_clipboard clipboard;
631 MatitaMathView.empty_clipboard ()
634 ignore (source_view#buffer#delete_selection ())
637 if MatitaMathView.has_clipboard ()
638 then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
639 else source_view#buffer#paste_clipboard clipboard;
640 self#clean_dirty_lock
642 method pastePattern () =
643 source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
645 method locked_mark = locked_mark
646 method locked_tag = locked_tag
647 method error_tag = error_tag
649 (* history can't be empty, the invariant above grant that it contains at
650 * least the init grafite_status *)
651 method status = match history with s::_ -> s | _ -> assert false
653 method private _advance ?statement () =
654 let s = match statement with Some s -> s | None -> self#getFuture in
655 if self#bos then LibraryClean.clean_baseuris [self#buri_of_current_file];
656 HLog.debug ("evaluating: " ^ first_line s ^ " ...");
657 let time1 = Unix.gettimeofday () in
658 let entries, newtext, parsed_len =
660 eval_statement self#include_paths buffer self#status self (`Raw s)
661 with End_of_file -> raise Margin
663 let time2 = Unix.gettimeofday () in
664 HLog.debug ("... done in " ^ string_of_float (time2 -. time1) ^ "s");
665 let new_statuses, new_statements =
666 let statuses, texts = List.split entries in
669 history <- new_statuses @ history;
670 statements <- new_statements @ statements;
671 let start = buffer#get_iter_at_mark (`MARK locked_mark) in
672 let new_text = String.concat "" (List.rev new_statements) in
673 if statement <> None then
674 buffer#insert ~iter:start new_text
676 let parsed_text = String.sub s 0 parsed_len in
677 if new_text <> parsed_text then begin
678 let stop = start#copy#forward_chars (Glib.Utf8.length parsed_text) in
679 buffer#delete ~start ~stop;
680 buffer#insert ~iter:start new_text;
683 self#moveMark (Glib.Utf8.length new_text);
684 buffer#insert ~iter:(buffer#get_iter_at_mark (`MARK locked_mark)) newtext
686 method private _retract offset status new_statements new_history =
687 NCicLibrary.time_travel status;
688 statements <- new_statements;
689 history <- new_history;
690 self#moveMark (- offset)
692 method advance ?statement () =
694 self#_advance ?statement ();
697 | Margin -> self#notify
698 | Not_found -> assert false
699 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
700 | exc -> self#notify; raise exc
704 let cmp,new_statements,new_history,status =
705 match statements,history with
706 stat::statements, _::(status::_ as history) ->
707 assert (Glib.Utf8.validate stat);
708 Glib.Utf8.length stat, statements, history, status
709 | [],[_] -> raise Margin
710 | _,_ -> assert false
712 self#_retract cmp status new_statements new_history;
715 | Margin -> self#notify
716 | Invalid_argument "Array.make" -> HLog.error "The script is too big!\n"
717 | exc -> self#notify; raise exc
719 method private getFuture =
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
724 method expandAllVirtuals =
725 let lock = buffer#get_iter_at_mark (`MARK locked_mark) in
726 let text = buffer#get_text ~start:lock ~stop:buffer#end_iter () in
727 buffer#delete ~start:lock ~stop:buffer#end_iter;
728 let text = Pcre.replace ~pat:":=" ~templ:"\\def" text in
729 let text = Pcre.replace ~pat:"->" ~templ:"\\to" text in
730 let text = Pcre.replace ~pat:"=>" ~templ:"\\Rightarrow" text in
732 Pcre.substitute_substrings
734 let pristine = Pcre.get_substring str 0 in
736 if pristine.[0] = ' ' then
737 String.sub pristine 1 (String.length pristine -1)
741 if input.[String.length input-1] = ' ' then
742 String.sub input 0 (String.length input -1)
746 if input = "\\forall" ||
747 input = "\\lambda" ||
748 input = "\\exists" then "","" else " ", " "
751 before ^ Glib.Utf8.from_unichar
752 (snd (Virtuals.symbol_of_virtual input)) ^ after
753 with Virtuals.Not_a_virtual -> pristine)
754 ~pat:" ?\\\\[a-zA-Z]+ ?" text
756 buffer#insert ~iter:lock text
758 (** @param rel_offset relative offset from current position of locked_mark *)
759 method private moveMark rel_offset =
760 let mark = `MARK locked_mark in
761 let old_insert = buffer#get_iter_at_mark `INSERT in
762 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
763 let current_mark_pos = buffer#get_iter_at_mark mark in
765 match rel_offset with
766 | 0 -> current_mark_pos
767 | n when n > 0 -> current_mark_pos#forward_chars n
768 | n (* when n < 0 *) -> current_mark_pos#backward_chars (abs n)
770 buffer#move_mark mark ~where:new_mark_pos;
771 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:new_mark_pos;
772 buffer#move_mark `INSERT old_insert;
773 let mark_position = buffer#get_iter_at_mark mark in
774 if source_view#move_mark_onscreen mark then
776 buffer#move_mark mark mark_position;
777 source_view#scroll_to_mark ~use_align:true ~xalign:1.0 ~yalign:0.1 mark;
779 while Glib.Main.pending () do ignore(Glib.Main.iteration false); done
781 method clean_dirty_lock =
782 let lock_mark_iter = buffer#get_iter_at_mark (`MARK locked_mark) in
783 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
784 buffer#apply_tag locked_tag ~start:buffer#start_iter ~stop:lock_mark_iter
786 val mutable observers = []
788 method addObserver (o: GrafiteTypes.status -> unit) =
789 observers <- o :: observers
791 method private notify =
792 let status = self#status in
793 List.iter (fun o -> o status) observers
796 NCicLibrary.replace self#status;
799 method loadFromFile f =
800 buffer#set_text (HExtlib.input_file f);
802 buffer#set_modified false
804 method assignFileName file =
807 tab_label#set_text default_fname;
809 include_paths_ <- [];
812 let f = Librarian.absolutize file in
813 tab_label#set_text (Filename.basename f);
815 include_paths_ <- MatitaEngine.read_include_paths ~include_paths:[] f;
819 tab_label#set_text ((if b then "*" else "")^Filename.basename self#filename);
820 tab_label#misc#set_tooltip_text
821 ("URI: " ^ self#buri_of_current_file ^ "\nPATH: " ^ self#filename);
823 method saveToFile () =
824 if self#has_name then
825 let oc = open_out self#filename in
826 output_string oc (buffer#get_text ~start:buffer#start_iter
827 ~stop:buffer#end_iter ());
830 buffer#set_modified false
832 HLog.error "Can't save, no filename selected"
834 method private _saveToBackupFile () =
835 if buffer#modified then
837 let f = self#filename ^ "~" in
838 let oc = open_out f in
839 output_string oc (buffer#get_text ~start:buffer#start_iter
840 ~stop:buffer#end_iter ());
842 HLog.debug ("backup " ^ f ^ " saved")
845 method private reset_buffer =
847 history <- [ initial_statuses (Some self#status) self#buri_of_current_file ];
849 buffer#remove_tag locked_tag ~start:buffer#start_iter ~stop:buffer#end_iter;
850 buffer#move_mark (`MARK locked_mark) ~where:buffer#start_iter
854 source_buffer#begin_not_undoable_action ();
855 buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter;
856 source_buffer#end_not_undoable_action ();
857 buffer#set_modified false;
860 let template = HExtlib.input_file BuildTimeConf.script_template in
861 buffer#insert ~iter:(buffer#get_iter `START) template;
862 buffer#set_modified false;
865 method goto (pos: [`Top | `Bottom | `Cursor]) () =
867 let old_locked_mark =
869 (buffer#create_mark ~name:"old_locked_mark"
870 ~left_gravity:true (buffer#get_iter_at_mark (`MARK locked_mark))) in
871 let getpos _ = buffer#get_iter_at_mark (`MARK locked_mark) in
872 let getoldpos _ = buffer#get_iter_at_mark old_locked_mark in
873 let dispose_old_locked_mark () = buffer#delete_mark old_locked_mark in
876 dispose_old_locked_mark ();
883 let newpos = getpos () in
884 if (getoldpos ())#compare newpos < 0 then
886 buffer#move_mark old_locked_mark newpos;
891 dispose_old_locked_mark ();
894 | Margin -> dispose_old_locked_mark (); self#notify
895 | exc -> dispose_old_locked_mark (); self#notify; raise exc)
897 let locked_iter () = buffer#get_iter_at_mark (`NAME "locked") in
898 let cursor_iter () = buffer#get_iter_at_mark `INSERT in
901 (buffer#create_mark ~name:"initial_insert"
902 ~left_gravity:true (cursor_iter ())) in
903 let dispose_remember () = buffer#delete_mark remember in
904 let remember_iter () =
905 buffer#get_iter_at_mark (`NAME "initial_insert") in
906 let cmp () = (locked_iter ())#offset - (remember_iter ())#offset in
908 let forward_until_cursor () = (* go forward until locked > cursor *)
911 if cmp () < 0 && (getoldpos ())#compare (getpos ()) < 0
914 buffer#move_mark old_locked_mark (getpos ());
920 let rec back_until_cursor len = (* go backward until locked < cursor *)
922 statements, ((status)::_ as history)
924 self#_retract (icmp - len) status statements
926 | statement::tl1, _::tl2 ->
927 back_until_cursor (len - MatitaGtkMisc.utf8_string_length statement) (tl1,tl2)
928 | _,_ -> assert false
932 if icmp < 0 then (* locked < cursor *)
933 (forward_until_cursor (); self#notify)
934 else if icmp > 0 then (* locked > cursor *)
935 (back_until_cursor icmp (statements,history); self#notify)
936 else (* cursor = locked *)
940 dispose_old_locked_mark ();
942 | Margin -> dispose_remember (); dispose_old_locked_mark (); self#notify
943 | exc -> dispose_remember (); dispose_old_locked_mark ();
944 self#notify; raise exc)
945 with Invalid_argument "Array.make" ->
946 HLog.error "The script is too big!\n"
954 let rec is_there_only_comments status s =
955 if Pcre.pmatch ~rex:only_dust_RE s then raise Margin;
957 GrafiteParser.parsable_statement status
958 (Ulexing.from_utf8_string s)in
959 match GrafiteParser.parse_statement status strm with
960 | GrafiteAst.Comment (loc,_) ->
961 let _,parsed_text_length = MatitaGtkMisc.utf8_parsed_text s loc in
962 (* CSC: why +1 in the following lines ???? *)
963 let parsed_text_length = parsed_text_length + 1 in
964 let remain_len = String.length s - parsed_text_length in
965 let next = String.sub s parsed_text_length remain_len in
966 is_there_only_comments status next
967 | GrafiteAst.Executable _ -> false
969 try is_there_only_comments self#status self#getFuture
971 | NCicLibrary.IncludedFileNotCompiled _
972 | HExtlib.Localized _
973 | CicNotationParser.Parse_error _ -> false
974 | Margin | End_of_file -> true
975 | Invalid_argument "Array.make" -> false
979 HLog.debug "script status:";
980 HLog.debug ("history size: " ^ string_of_int (List.length history));
981 HLog.debug (sprintf "%d statements:" (List.length statements));
982 List.iter HLog.debug statements;
983 HLog.debug ("Current file name: " ^ self#filename);
985 method has_parent (p : GObj.widget) = parent#coerce#misc#get_oid = p#misc#get_oid
990 let script ~parent ~tab_label ()
992 let s = new script ~parent ~tab_label () in
993 _script := s::!_script;
997 let notebook = (MatitaMisc.get_gui ())#main#scriptNotebook in
998 let parent = notebook#get_nth_page page in
1000 List.find (fun s -> s#has_parent parent) !_script
1002 Not_found -> assert false
1006 at_page ((MatitaMisc.get_gui ())#main#scriptNotebook#current_page)
1009 let s = at_page page in
1010 _script := List.filter ((<>) s) !_script
1013 let iter_scripts f = List.iter f !_script;;
1016 CicMathView.register_matita_script_current (current :> unit -> < advance: ?statement:string -> unit -> unit; status: GrafiteTypes.status >)