]> matita.cs.unibo.it Git - helm.git/blob - matita/matitaGui.ml
fixed coercion graph print, moved coercion graph and auto gui to the view menu, added...
[helm.git] / matita / matitaGui.ml
1 (* Copyright (C) 2004-2005, HELM Team.
2  * 
3  * This file is part of HELM, an Hypertextual, Electronic
4  * Library of Mathematics, developed at the Computer Science
5  * Department, University of Bologna, Italy.
6  * 
7  * HELM is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  * 
12  * HELM is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with HELM; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://helm.cs.unibo.it/
24  *)
25
26 (* $Id$ *)
27
28 open Printf
29
30 open MatitaGeneratedGui
31 open MatitaGtkMisc
32 open MatitaMisc
33
34 exception Found of int
35
36 let gui_instance = ref None
37
38 class type browserWin =
39   (* this class exists only because GEdit.combo_box_entry is not supported by
40    * lablgladecc :-(((( *)
41 object
42   inherit MatitaGeneratedGui.browserWin
43   method browserUri: GEdit.combo_box_entry
44 end
45
46 class console ~(buffer: GText.buffer) () =
47   object (self)
48     val error_tag   = buffer#create_tag [ `FOREGROUND "red" ]
49     val warning_tag = buffer#create_tag [ `FOREGROUND "orange" ]
50     val message_tag = buffer#create_tag []
51     val debug_tag   = buffer#create_tag [ `FOREGROUND "#888888" ]
52     method message s = buffer#insert ~iter:buffer#end_iter ~tags:[message_tag] s
53     method error s   = buffer#insert ~iter:buffer#end_iter ~tags:[error_tag] s
54     method warning s = buffer#insert ~iter:buffer#end_iter ~tags:[warning_tag] s
55     method debug s   = buffer#insert ~iter:buffer#end_iter ~tags:[debug_tag] s
56     method clear () =
57       buffer#delete ~start:buffer#start_iter ~stop:buffer#end_iter
58     method log_callback (tag: HLog.log_tag) s =
59       match tag with
60       | `Debug -> self#debug (s ^ "\n")
61       | `Error -> self#error (s ^ "\n")
62       | `Message -> self#message (s ^ "\n")
63       | `Warning -> self#warning (s ^ "\n")
64   end
65         
66 let clean_current_baseuri grafite_status = 
67     try  
68       let baseuri = GrafiteTypes.get_string_option grafite_status "baseuri" in
69       LibraryClean.clean_baseuris [baseuri]
70     with GrafiteTypes.Option_error _ -> ()
71
72 let ask_and_save_moo_if_needed parent fname lexicon_status grafite_status = 
73   let baseuri =
74    try Some (GrafiteTypes.get_string_option grafite_status "baseuri")
75    with GrafiteTypes.Option_error _ -> None
76   in
77   if (MatitaScript.current ())#eos &&
78      grafite_status.GrafiteTypes.proof_status = GrafiteTypes.No_proof &&
79      baseuri <> None
80   then
81    begin
82     let baseuri = match baseuri with Some b -> b | None -> assert false in
83     let moo_fname = 
84      LibraryMisc.obj_file_of_baseuri ~must_exist:false ~baseuri
85       ~writable:true in
86     let save () =
87       let lexicon_fname =
88        LibraryMisc.lexicon_file_of_baseuri 
89          ~must_exist:false ~baseuri ~writable:true
90       in
91        GrafiteMarshal.save_moo moo_fname
92         grafite_status.GrafiteTypes.moo_content_rev;
93        LexiconMarshal.save_lexicon lexicon_fname
94         lexicon_status.LexiconEngine.lexicon_content_rev
95     in
96      begin
97        let rc = 
98          MatitaGtkMisc.ask_confirmation
99          ~title:"A .moo can be generated"
100          ~message:(Printf.sprintf 
101            "%s can be generated for %s.\n<i>Should I generate it?</i>"
102            (Filename.basename moo_fname) (Filename.basename fname))
103          ~parent ()
104        in
105        let b = 
106          match rc with 
107          | `YES -> true 
108          | `NO -> false 
109          | `CANCEL -> raise MatitaTypes.Cancel 
110        in
111        if b then
112            save ()
113        else
114          clean_current_baseuri grafite_status
115      end
116    end
117   else
118     clean_current_baseuri grafite_status 
119     
120 let ask_unsaved parent =
121   MatitaGtkMisc.ask_confirmation 
122     ~parent ~title:"Unsaved work!" 
123     ~message:("Your work is <b>unsaved</b>!\n\n"^
124          "<i>Do you want to save the script before continuing?</i>")
125     ()
126
127 class interpErrorModel =
128   let cols = new GTree.column_list in
129   let id_col = cols#add Gobject.Data.string in
130   let dsc_col = cols#add Gobject.Data.string in
131   let interp_no_col = cols#add Gobject.Data.caml in
132   let tree_store = GTree.tree_store cols in
133   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
134   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
135   let id_view_col = GTree.view_column ~renderer:id_renderer () in
136   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
137   fun (tree_view: GTree.view) choices ->
138     object
139       initializer
140         tree_view#set_model (Some (tree_store :> GTree.model));
141         ignore (tree_view#append_column id_view_col);
142         ignore (tree_view#append_column dsc_view_col);
143         tree_store#clear ();
144         let idx1 = ref ~-1 in
145         List.iter
146           (fun _,lll ->
147             incr idx1;
148             let loc_row =
149              if List.length choices = 1 then
150               None
151              else
152               (let loc_row = tree_store#append () in
153                 begin
154                  match lll with
155                     [passes,envs_and_diffs,_,_] ->
156                       tree_store#set ~row:loc_row ~column:id_col
157                        ("Error location " ^ string_of_int (!idx1+1) ^
158                         ", error message " ^ string_of_int (!idx1+1) ^ ".1" ^
159                         " (in passes " ^
160                         String.concat " " (List.map string_of_int passes) ^
161                         ")");
162                       tree_store#set ~row:loc_row ~column:interp_no_col
163                        (!idx1,Some 0,None);
164                   | _ ->
165                     tree_store#set ~row:loc_row ~column:id_col
166                      ("Error location " ^ string_of_int (!idx1+1));
167                     tree_store#set ~row:loc_row ~column:interp_no_col
168                      (!idx1,None,None);
169                 end ;
170                 Some loc_row) in
171             let idx2 = ref ~-1 in
172              List.iter
173               (fun passes,envs_and_diffs,_,_ ->
174                 incr idx2;
175                 let msg_row =
176                  if List.length lll = 1 then
177                   loc_row
178                  else
179                   let msg_row = tree_store#append ?parent:loc_row () in
180                    (tree_store#set ~row:msg_row ~column:id_col
181                      ("Error message " ^ string_of_int (!idx1+1) ^ "." ^
182                       string_of_int (!idx2+1) ^
183                       " (in passes " ^
184                       String.concat " " (List.map string_of_int passes) ^
185                       ")");
186                     tree_store#set ~row:msg_row ~column:interp_no_col
187                      (!idx1,Some !idx2,None);
188                     Some msg_row) in
189                 let idx3 = ref ~-1 in
190                 List.iter
191                  (fun (passes,env,_) ->
192                    incr idx3;
193                    let interp_row =
194                     match envs_and_diffs with
195                        _::_::_ ->
196                         let interp_row = tree_store#append ?parent:msg_row () in
197                         tree_store#set ~row:interp_row ~column:id_col
198                           ("Interpretation " ^ string_of_int (!idx3+1) ^
199                            " (in passes " ^
200                            String.concat " " (List.map string_of_int passes) ^
201                            ")");
202                         tree_store#set ~row:interp_row ~column:interp_no_col
203                          (!idx1,Some !idx2,Some !idx3);
204                         Some interp_row
205                      | [_] -> msg_row
206                      | [] -> assert false
207                    in
208                     List.iter
209                      (fun (_, id, dsc) ->
210                        let row = tree_store#append ?parent:interp_row () in
211                        tree_store#set ~row ~column:id_col id;
212                        tree_store#set ~row ~column:dsc_col dsc;
213                        tree_store#set ~row ~column:interp_no_col
214                         (!idx1,Some !idx2,Some !idx3)
215                      ) env
216                  ) envs_and_diffs
217               ) lll ;
218              if List.length lll > 1 then
219               HExtlib.iter_option
220                (fun p -> tree_view#expand_row (tree_store#get_path p))
221                loc_row
222           ) choices
223
224       method get_interp_no tree_path =
225         let iter = tree_store#get_iter tree_path in
226         tree_store#get ~row:iter ~column:interp_no_col
227     end
228
229
230 let rec interactive_error_interp ?(all_passes=false) (source_buffer:GSourceView.source_buffer) notify_exn offset errorll
231
232   assert (List.flatten errorll <> []);
233   let errorll' =
234    let remove_non_significant =
235      List.filter (fun (_env,_diff,_loc,_msg,significant) -> significant) in
236    if all_passes then errorll else
237      let safe_list_nth l n = try List.nth l n with Failure _ -> [] in
238     (* We remove passes 1,2 and 5,6 *)
239      let res =
240       []::[]
241       ::(remove_non_significant (safe_list_nth errorll 2))
242       ::(remove_non_significant (safe_list_nth errorll 3))
243       ::[]::[]
244      in
245       if List.flatten res <> [] then res
246       else
247        (* all errors (if any) are not significant: we keep them *)
248        let res =
249         []::[]
250         ::(safe_list_nth errorll 2)
251         ::(safe_list_nth errorll 3)
252         ::[]::[]
253        in
254         if List.flatten res <> [] then
255          begin
256           HLog.warn
257            "All disambiguation errors are not significant. Showing them anyway." ;
258           res
259          end
260         else
261          begin
262           HLog.warn
263            "No errors in phases 2 and 3. Showing all errors in all phases" ;
264           errorll
265          end
266    in
267   let choices =
268    let pass = ref 0 in
269    List.flatten
270     (List.map
271       (fun l ->
272         incr pass;
273         List.map
274          (fun (env,diff,offset,msg,significant) ->
275            offset, [[!pass], [[!pass], env, diff], msg, significant]) l
276       ) errorll') in
277   (* Here we are doing a stable sort and list_uniq returns the latter
278      "equal" element. I.e. we are showing the error corresponding to the
279      most advanced disambiguation pass *)
280   let choices =
281    let choices_compare (o1,_) (o2,_) = compare o1 o2 in
282    let choices_compare_by_passes (p1,_,_,_) (p2,_,_,_) =
283     compare p1 p2 in
284    let rec uniq =
285     function
286        [] -> []
287      | h::[] -> [h]
288      | (o1,res1)::(o2,res2)::tl when o1 = o2 ->
289         let merge_by_name errors =
290          let merge_by_env errors =
291           let choices_compare_by_env (_,e1,_) (_,e2,_) = compare e1 e2 in
292           let choices_compare_by_passes (p1,_,_) (p2,_,_) =
293            compare p1 p2 in
294           let rec uniq_by_env =
295            function
296               [] -> []
297             | h::[] -> [h]
298             | (p1,e1,_)::(p2,e2,d2)::tl when e1 = e2 ->
299                 uniq_by_env ((p1@p2,e2,d2) :: tl) 
300             | h1::tl -> h1 :: uniq_by_env tl
301           in
302            List.sort choices_compare_by_passes
303             (uniq_by_env (List.stable_sort choices_compare_by_env errors))
304          in
305          let choices_compare_by_msg (_,_,m1,_) (_,_,m2,_) =
306           compare (Lazy.force m1) (Lazy.force m2) in
307          let rec uniq_by_msg =
308           function
309              [] -> []
310            | h::[] -> [h]
311            | (p1,i1,m1,s1)::(p2,i2,m2,s2)::tl
312              when Lazy.force m1 = Lazy.force m2 && s1 = s2 ->
313                uniq_by_msg ((p1@p2,merge_by_env (i1@i2),m2,s2) :: tl)
314            | h1::tl -> h1 :: uniq_by_msg tl
315          in
316           List.sort choices_compare_by_msg
317            (uniq_by_msg (List.stable_sort choices_compare_by_msg errors))
318         in
319          let res = merge_by_name (res1@res2) in
320           uniq ((o1,res) :: tl)
321      | h1::tl -> h1 :: uniq tl
322    in
323    (* Errors in phase 3 that are not also in phase 4 are filtered out *)
324    let filter_phase_3 choices =
325     if all_passes then choices
326     else
327      let filter =
328       HExtlib.filter_map
329        (function
330            (loffset,messages) ->
331               let filtered_messages =
332                HExtlib.filter_map
333                 (function
334                     [3],_,_,_ -> None
335                   | item -> Some item
336                 ) messages
337               in
338                if filtered_messages = [] then
339                 None
340                else
341                 Some (loffset,filtered_messages))
342      in
343       filter choices
344    in
345     filter_phase_3
346      (List.map (fun o,l -> o,List.sort choices_compare_by_passes l)
347        (uniq (List.stable_sort choices_compare choices)))
348   in
349    match choices with
350       [] -> assert false
351     | [loffset,[_,envs_and_diffs,msg,significant]] ->
352         let _,env,diff = List.hd envs_and_diffs in
353          notify_exn
354           (GrafiteDisambiguator.DisambiguationError
355             (offset,[[env,diff,loffset,msg,significant]]));
356     | _::_ ->
357        let dialog = new disambiguationErrors () in
358        dialog#check_widgets ();
359        if all_passes then
360         dialog#disambiguationErrorsMoreErrors#misc#set_sensitive false;
361        let model = new interpErrorModel dialog#treeview choices in
362        dialog#disambiguationErrors#set_title "Disambiguation error";
363        dialog#disambiguationErrorsLabel#set_label
364         "Click on an error to see the corresponding message:";
365        ignore (dialog#treeview#connect#cursor_changed
366         (fun _ ->
367           let tree_path =
368            match fst (dialog#treeview#get_cursor ()) with
369               None -> assert false
370            | Some tp -> tp in
371           let idx1,idx2,idx3 = model#get_interp_no tree_path in
372           let loffset,lll = List.nth choices idx1 in
373           let _,envs_and_diffs,msg,significant =
374            match idx2 with
375               Some idx2 -> List.nth lll idx2
376             | None ->
377                 [],[],lazy "Multiple error messages. Please select one.",true
378           in
379           let _,env,diff =
380            match idx3 with
381               Some idx3 -> List.nth envs_and_diffs idx3
382             | None -> [],[],[] (* dymmy value, used *) in
383           let script = MatitaScript.current () in
384           let error_tag = script#error_tag in
385            source_buffer#remove_tag error_tag
386              ~start:source_buffer#start_iter
387              ~stop:source_buffer#end_iter;
388            notify_exn
389             (GrafiteDisambiguator.DisambiguationError
390               (offset,[[env,diff,loffset,msg,significant]]))
391            ));
392        let return _ =
393          dialog#disambiguationErrors#destroy ();
394          GMain.Main.quit ()
395        in
396        let fail _ = return () in
397        ignore(dialog#disambiguationErrors#event#connect#delete (fun _ -> true));
398        connect_button dialog#disambiguationErrorsOkButton
399         (fun _ ->
400           let tree_path =
401            match fst (dialog#treeview#get_cursor ()) with
402               None -> assert false
403            | Some tp -> tp in
404           let idx1,idx2,idx3 = model#get_interp_no tree_path in
405           let diff =
406            match idx2,idx3 with
407               Some idx2, Some idx3 ->
408                let _,lll = List.nth choices idx1 in
409                let _,envs_and_diffs,_,_ = List.nth lll idx2 in
410                let _,_,diff = List.nth envs_and_diffs idx3 in
411                 diff
412             | _,_ -> assert false
413           in
414            let newtxt =
415             String.concat "\n"
416              ("" ::
417                List.map
418                 (fun k,value ->
419                   DisambiguatePp.pp_environment
420                    (DisambiguateTypes.Environment.add k value
421                      DisambiguateTypes.Environment.empty))
422                 diff) ^ "\n"
423            in
424             source_buffer#insert
425              ~iter:
426                (source_buffer#get_iter_at_mark
427                 (`NAME "beginning_of_statement")) newtxt ;
428             return ()
429         );
430        connect_button dialog#disambiguationErrorsMoreErrors
431         (fun _ -> return () ;
432           interactive_error_interp ~all_passes:true source_buffer notify_exn offset
433            errorll);
434        connect_button dialog#disambiguationErrorsCancelButton fail;
435        dialog#disambiguationErrors#show ();
436        GtkThread.main ()
437
438
439 (** Selection handling
440  * Two clipboards are used: "clipboard" and "primary".
441  * "primary" is used by X, when you hit the middle button mouse is content is
442  *    pasted between applications. In Matita this selection always contain the
443  *    textual version of the selected term.
444  * "clipboard" is used inside Matita only and support ATM two different targets:
445  *    "TERM" and "PATTERN", in the future other targets like "MATHMLCONTENT" may
446  *    be added
447  *)
448
449 class gui () =
450     (* creation order _is_ relevant for windows placement *)
451   let main = new mainWin () in
452   let fileSel = new fileSelectionWin () in
453   let findRepl = new findReplWin () in
454   let develList = new develListWin () in
455   let newDevel = new newDevelWin () in
456   let keyBindingBoxes = (* event boxes which should receive global key events *)
457     [ main#mainWinEventBox ]
458   in
459   let console = new console ~buffer:main#logTextView#buffer () in
460   let (source_view: GSourceView.source_view) =
461     GSourceView.source_view
462       ~auto_indent:true
463       ~insert_spaces_instead_of_tabs:true ~tabs_width:2
464       ~margin:80 ~show_margin:true
465       ~smart_home_end:true
466       ~packing:main#scriptScrolledWin#add
467       ()
468   in
469   let default_font_size =
470     Helm_registry.get_opt_default Helm_registry.int
471       ~default:BuildTimeConf.default_font_size "matita.font_size"
472   in
473   let source_buffer = source_view#source_buffer in
474   object (self)
475     val mutable chosen_file = None
476     val mutable _ok_not_exists = false
477     val mutable _only_directory = false
478     val mutable script_fname = None
479     val mutable font_size = default_font_size
480     val mutable next_devel_must_contain = None
481     val mutable next_ligatures = []
482     val clipboard = GData.clipboard Gdk.Atom.clipboard
483     val primary = GData.clipboard Gdk.Atom.primary
484    
485     initializer
486         (* glade's check widgets *)
487       List.iter (fun w -> w#check_widgets ())
488         (let c w = (w :> <check_widgets: unit -> unit>) in
489         [ c fileSel; c main; c findRepl]);
490         (* key bindings *)
491       List.iter (* global key bindings *)
492         (fun (key, callback) -> self#addKeyBinding key callback)
493 (*
494         [ GdkKeysyms._F3,
495             toggle_win ~check:main#showProofMenuItem proof#proofWin;
496           GdkKeysyms._F4,
497             toggle_win ~check:main#showCheckMenuItem check#checkWin;
498 *)
499         [ ];
500         (* about win *)
501       let parse_txt_file file =
502        let ch = open_in (BuildTimeConf.runtime_base_dir ^ "/" ^ file) in
503        let l_rev = ref [] in
504        try
505         while true do
506          l_rev := input_line ch :: !l_rev;
507         done;
508         assert false
509        with
510         End_of_file ->
511          close_in ch;
512          List.rev !l_rev in 
513       let about_dialog =
514        GWindow.about_dialog
515         ~authors:(parse_txt_file "AUTHORS")
516         (*~comments:"comments"*)
517         ~copyright:"Copyright (C) 2005, the HELM team"
518         ~license:(String.concat "\n" (parse_txt_file "LICENSE"))
519         ~logo:(GdkPixbuf.from_file (MatitaMisc.image_path "/matita_medium.png"))
520         ~name:"Matita"
521         ~version:BuildTimeConf.version
522         ~website:"http://helm.cs.unibo.it"
523         ()
524       in
525       connect_menu_item main#contentsMenuItem (fun () ->
526         let cmd =
527           sprintf "gnome-help ghelp://%s/C/matita.xml &" BuildTimeConf.help_dir
528         in
529         ignore (Sys.command cmd));
530       connect_menu_item main#aboutMenuItem about_dialog#present;
531         (* findRepl win *)
532       let show_find_Repl () = 
533         findRepl#toplevel#misc#show ();
534         findRepl#toplevel#misc#grab_focus ()
535       in
536       let hide_find_Repl () = findRepl#toplevel#misc#hide () in
537       let find_forward _ = 
538           let highlight start end_ =
539             source_buffer#move_mark `INSERT ~where:start;
540             source_buffer#move_mark `SEL_BOUND ~where:end_;
541             source_view#scroll_mark_onscreen `INSERT
542           in
543           let text = findRepl#findEntry#text in
544           let iter = source_buffer#get_iter `SEL_BOUND in
545           match iter#forward_search text with
546           | None -> 
547               (match source_buffer#start_iter#forward_search text with
548               | None -> ()
549               | Some (start,end_) -> highlight start end_)
550           | Some (start,end_) -> highlight start end_ 
551       in
552       let replace _ =
553         let text = findRepl#replaceEntry#text in
554         let ins = source_buffer#get_iter `INSERT in
555         let sel = source_buffer#get_iter `SEL_BOUND in
556         if ins#compare sel < 0 then 
557           begin
558             ignore(source_buffer#delete_selection ());
559             source_buffer#insert text
560           end
561       in
562       connect_button findRepl#findButton find_forward;
563       connect_button findRepl#findReplButton replace;
564       connect_button findRepl#cancelButton (fun _ -> hide_find_Repl ());
565       ignore(findRepl#toplevel#event#connect#delete 
566         ~callback:(fun _ -> hide_find_Repl ();true));
567       let safe_undo =
568        fun () ->
569         (* phase 1: we save the actual status of the marks and we undo *)
570         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
571         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
572         let locked_iter_offset = locked_iter#offset in
573         let mark2 =
574          `MARK
575            (source_view#buffer#create_mark ~name:"lock_point"
576              ~left_gravity:true locked_iter) in
577         source_view#source_buffer#undo ();
578         (* phase 2: we save the cursor position and we redo, restoring
579            the previous status of all the marks *)
580         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
581         let mark =
582          `MARK
583            (source_view#buffer#create_mark ~name:"undo_point"
584              ~left_gravity:true cursor_iter)
585         in
586          source_view#source_buffer#redo ();
587          let mark_iter = source_view#buffer#get_iter_at_mark mark in
588          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
589          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
590           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
591           source_view#buffer#delete_mark mark;
592           source_view#buffer#delete_mark mark2;
593           (* phase 3: if after the undo the cursor was in the locked area,
594              then we move it there again and we perform a goto *)
595           if mark_iter#offset < locked_iter_offset then
596            begin
597             source_view#buffer#move_mark `INSERT ~where:mark_iter;
598             (MatitaScript.current ())#goto `Cursor ();
599            end;
600           (* phase 4: we perform again the undo. This time we are sure that
601              the text to undo is not locked *)
602           source_view#source_buffer#undo ();
603           source_view#misc#grab_focus () in
604       let safe_redo =
605        fun () ->
606         (* phase 1: we save the actual status of the marks, we redo and
607            we undo *)
608         let locked_mark = `MARK ((MatitaScript.current ())#locked_mark) in
609         let locked_iter = source_view#buffer#get_iter_at_mark locked_mark in
610         let locked_iter_offset = locked_iter#offset in
611         let mark2 =
612          `MARK
613            (source_view#buffer#create_mark ~name:"lock_point"
614              ~left_gravity:true locked_iter) in
615         source_view#source_buffer#redo ();
616         source_view#source_buffer#undo ();
617         (* phase 2: we save the cursor position and we restore
618            the previous status of all the marks *)
619         let cursor_iter = source_view#buffer#get_iter_at_mark `INSERT in
620         let mark =
621          `MARK
622            (source_view#buffer#create_mark ~name:"undo_point"
623              ~left_gravity:true cursor_iter)
624         in
625          let mark_iter = source_view#buffer#get_iter_at_mark mark in
626          let mark2_iter = source_view#buffer#get_iter_at_mark mark2 in
627          let mark2_iter = mark2_iter#set_offset locked_iter_offset in
628           source_view#buffer#move_mark locked_mark ~where:mark2_iter;
629           source_view#buffer#delete_mark mark;
630           source_view#buffer#delete_mark mark2;
631           (* phase 3: if after the undo the cursor is in the locked area,
632              then we move it there again and we perform a goto *)
633           if mark_iter#offset < locked_iter_offset then
634            begin
635             source_view#buffer#move_mark `INSERT ~where:mark_iter;
636             (MatitaScript.current ())#goto `Cursor ();
637            end;
638           (* phase 4: we perform again the redo. This time we are sure that
639              the text to redo is not locked *)
640           source_view#source_buffer#redo ();
641           source_view#misc#grab_focus ()
642       in
643       connect_menu_item main#undoMenuItem safe_undo;
644       ignore(source_view#source_buffer#connect#can_undo
645         ~callback:main#undoMenuItem#misc#set_sensitive);
646       connect_menu_item main#redoMenuItem safe_redo;
647       ignore(source_view#source_buffer#connect#can_redo
648         ~callback:main#redoMenuItem#misc#set_sensitive);
649       ignore(source_view#connect#after#populate_popup
650        ~callback:(fun pre_menu ->
651          let menu = new GMenu.menu pre_menu in
652          let menuItems = menu#children in
653          let undoMenuItem, redoMenuItem =
654           match menuItems with
655              [undo;redo;sep1;cut;copy;paste;delete;sep2;
656               selectall;sep3;inputmethod;insertunicodecharacter] ->
657                 List.iter menu#remove [ copy; cut; delete; paste ];
658                 undo,redo
659            | _ -> assert false in
660          let add_menu_item =
661            let i = ref 2 in (* last occupied position *)
662            fun ?label ?stock () ->
663              incr i;
664              GMenu.image_menu_item ?label ?stock ~packing:(menu#insert ~pos:!i)
665               ()
666          in
667          let copy = add_menu_item ~stock:`COPY () in
668          let cut = add_menu_item ~stock:`CUT () in
669          let delete = add_menu_item ~stock:`DELETE () in
670          let paste = add_menu_item ~stock:`PASTE () in
671          let paste_pattern = add_menu_item ~label:"Paste as pattern" () in
672          copy#misc#set_sensitive self#canCopy;
673          cut#misc#set_sensitive self#canCut;
674          delete#misc#set_sensitive self#canDelete;
675          paste#misc#set_sensitive self#canPaste;
676          paste_pattern#misc#set_sensitive self#canPastePattern;
677          connect_menu_item copy self#copy;
678          connect_menu_item cut self#cut;
679          connect_menu_item delete self#delete;
680          connect_menu_item paste self#paste;
681          connect_menu_item paste_pattern self#pastePattern;
682          let new_undoMenuItem =
683           GMenu.image_menu_item
684            ~image:(GMisc.image ~stock:`UNDO ())
685            ~use_mnemonic:true
686            ~label:"_Undo"
687            ~packing:(menu#insert ~pos:0) () in
688          new_undoMenuItem#misc#set_sensitive
689           (undoMenuItem#misc#get_flag `SENSITIVE);
690          menu#remove (undoMenuItem :> GMenu.menu_item);
691          connect_menu_item new_undoMenuItem safe_undo;
692          let new_redoMenuItem =
693           GMenu.image_menu_item
694            ~image:(GMisc.image ~stock:`REDO ())
695            ~use_mnemonic:true
696            ~label:"_Redo"
697            ~packing:(menu#insert ~pos:1) () in
698          new_redoMenuItem#misc#set_sensitive
699           (redoMenuItem#misc#get_flag `SENSITIVE);
700           menu#remove (redoMenuItem :> GMenu.menu_item);
701           connect_menu_item new_redoMenuItem safe_redo));
702
703       connect_menu_item main#editMenu (fun () ->
704         main#copyMenuItem#misc#set_sensitive self#canCopy;
705         main#cutMenuItem#misc#set_sensitive self#canCut;
706         main#deleteMenuItem#misc#set_sensitive self#canDelete;
707         main#pasteMenuItem#misc#set_sensitive self#canPaste;
708         main#pastePatternMenuItem#misc#set_sensitive self#canPastePattern);
709       connect_menu_item main#copyMenuItem self#copy;
710       connect_menu_item main#cutMenuItem self#cut;
711       connect_menu_item main#deleteMenuItem self#delete;
712       connect_menu_item main#pasteMenuItem self#paste;
713       connect_menu_item main#pastePatternMenuItem self#pastePattern;
714       connect_menu_item main#selectAllMenuItem (fun () ->
715         source_buffer#move_mark `INSERT source_buffer#start_iter;
716         source_buffer#move_mark `SEL_BOUND source_buffer#end_iter);
717       connect_menu_item main#findReplMenuItem show_find_Repl;
718       connect_menu_item main#externalEditorMenuItem self#externalEditor;
719       connect_menu_item main#ligatureButton self#nextLigature;
720       ignore (findRepl#findEntry#connect#activate find_forward);
721         (* interface lockers *)
722       let lock_world _ =
723         main#buttonsToolbar#misc#set_sensitive false;
724         develList#buttonsHbox#misc#set_sensitive false;
725         main#scriptMenu#misc#set_sensitive false;
726         source_view#set_editable false
727       in
728       let unlock_world _ =
729         main#buttonsToolbar#misc#set_sensitive true;
730         develList#buttonsHbox#misc#set_sensitive true;
731         main#scriptMenu#misc#set_sensitive true;
732         source_view#set_editable true;
733         (*The next line seems sufficient to avoid some unknown race condition *)
734         GtkThread.sync (fun () -> ()) ()
735       in
736       let worker_thread = ref None in
737       let notify_exn exn =
738        let floc, msg = MatitaExcPp.to_string exn in
739         begin
740          match floc with
741             None -> ()
742           | Some floc ->
743              let (x, y) = HExtlib.loc_of_floc floc in
744              let script = MatitaScript.current () in
745              let locked_mark = script#locked_mark in
746              let error_tag = script#error_tag in
747              let baseoffset =
748               (source_buffer#get_iter_at_mark (`MARK locked_mark))#offset in
749              let x' = baseoffset + x in
750              let y' = baseoffset + y in
751              let x_iter = source_buffer#get_iter (`OFFSET x') in
752              let y_iter = source_buffer#get_iter (`OFFSET y') in
753              source_buffer#apply_tag error_tag ~start:x_iter ~stop:y_iter;
754              let id = ref None in
755              id := Some (source_buffer#connect#changed ~callback:(fun () ->
756                source_buffer#remove_tag error_tag
757                  ~start:source_buffer#start_iter
758                  ~stop:source_buffer#end_iter;
759                match !id with
760                | None -> assert false (* a race condition occurred *)
761                | Some id ->
762                    (new GObj.gobject_ops source_buffer#as_buffer)#disconnect id));
763              source_buffer#place_cursor
764               (source_buffer#get_iter (`OFFSET x'));
765         end;
766         HLog.error msg in
767       let locker f () =
768        let thread_main =
769         fun () -> 
770           lock_world ();
771           try
772            f ();
773            unlock_world ()
774           with
775            | GrafiteDisambiguator.DisambiguationError (offset,errorll) ->
776               (try
777                 interactive_error_interp source_buffer notify_exn offset
778                  errorll
779                with
780                 exc -> notify_exn exc);
781               unlock_world ()
782            | exc ->
783               notify_exn exc;
784               unlock_world ()
785        in
786         worker_thread := Some (Thread.create thread_main ()) in
787       let kill_worker =
788        (* the following lines are from Xavier Leroy: http://alan.petitepomme.net/cwn/2005.11.08.html *)
789        let interrupt = ref None in
790        let old_callback = ref (function _ -> ()) in
791        let force_interrupt n =
792          (* This function is called just before the thread's timeslice ends *)
793          !old_callback n;
794          if Some(Thread.id(Thread.self())) = !interrupt then
795           (interrupt := None; raise Sys.Break) in
796        let _ =
797         match Sys.signal Sys.sigvtalrm (Sys.Signal_handle force_interrupt) with
798            Sys.Signal_handle f -> old_callback := f
799          | Sys.Signal_ignore
800          | Sys.Signal_default -> assert false
801        in
802         fun () ->
803          match !worker_thread with
804             None -> assert false
805           | Some t -> interrupt := Some (Thread.id t) in
806       let keep_focus f =
807         fun () ->
808          try
809           f (); source_view#misc#grab_focus ()
810          with
811           exc -> source_view#misc#grab_focus (); raise exc in
812         (* developments win *)
813       let model = 
814         new MatitaGtkMisc.multiStringListModel 
815           ~cols:2 develList#developmentsTreeview
816       in
817       let refresh_devels_win () =
818         model#list_store#clear ();
819         List.iter 
820           (fun (name, root) -> model#easy_mappend [name;root]) 
821           (MatitamakeLib.list_known_developments ())
822       in
823       let get_devel_selected () = 
824         match model#easy_mselection () with
825         | [[name;_]] -> MatitamakeLib.development_for_name name
826         | _ -> None
827       in
828       let refresh () = 
829         while Glib.Main.pending () do 
830           ignore(Glib.Main.iteration false); 
831         done
832       in
833       connect_button develList#newButton
834         (fun () -> 
835           next_devel_must_contain <- None;
836           newDevel#toplevel#misc#show());
837       connect_button develList#deleteButton
838         (locker (fun () -> 
839           (match get_devel_selected () with
840           | None -> ()
841           | Some d -> MatitamakeLib.destroy_development_in_bg refresh d);
842           refresh_devels_win ()));
843       connect_button develList#buildButton 
844         (locker (fun () -> 
845           match get_devel_selected () with
846           | None -> ()
847           | Some d -> 
848               let build = locker 
849                 (fun () -> MatitamakeLib.build_development_in_bg refresh d)
850               in
851               ignore(build ())));
852       connect_button develList#cleanButton 
853         (locker (fun () -> 
854           match get_devel_selected () with
855           | None -> ()
856           | Some d -> 
857               let clean = locker 
858                 (fun () -> MatitamakeLib.clean_development_in_bg refresh d)
859               in
860               ignore(clean ())));
861       connect_button develList#publishButton 
862         (locker (fun () -> 
863           match get_devel_selected () with
864           | None -> ()
865           | Some d -> 
866               let publish = locker (fun () ->
867                 MatitamakeLib.publish_development_in_bg refresh d) in
868               ignore(publish ())));
869       connect_button develList#graphButton (fun () -> 
870         match get_devel_selected () with
871         | None -> ()
872         | Some d ->
873             (match MatitamakeLib.dot_for_development d with
874             | None -> ()
875             | Some _ ->
876                 let browser = MatitaMathView.cicBrowser () in
877                 browser#load (`Development
878                   (MatitamakeLib.name_for_development d))));
879       connect_button develList#closeButton 
880         (fun () -> develList#toplevel#misc#hide());
881       ignore(develList#toplevel#event#connect#delete 
882         (fun _ -> develList#toplevel#misc#hide();true));
883       connect_menu_item main#developmentsMenuItem
884         (fun () -> refresh_devels_win ();develList#toplevel#misc#show ());
885       
886         (* add development win *)
887       let check_if_root_contains root =
888         match next_devel_must_contain with
889         | None -> true
890         | Some path -> 
891             let is_prefix_of d1 d2 =
892               let len1 = String.length d1 in
893               let len2 = String.length d2 in
894               if len2 < len1 then 
895                 false
896               else
897                 let pref = String.sub d2 0 len1 in
898                 pref = d1
899             in
900             is_prefix_of root path
901       in
902       connect_button newDevel#addButton 
903        (fun () -> 
904           let name = newDevel#nameEntry#text in
905           let root = newDevel#rootEntry#text in
906           if check_if_root_contains root then
907             begin
908               ignore (MatitamakeLib.initialize_development name root);
909               refresh_devels_win ();
910               newDevel#nameEntry#set_text "";
911               newDevel#rootEntry#set_text "";
912               newDevel#toplevel#misc#hide()
913             end
914           else
915             HLog.error ("The selected root does not contain " ^ 
916               match next_devel_must_contain with 
917               | Some x -> x 
918               | _ -> assert false));
919       connect_button newDevel#chooseRootButton 
920        (fun () ->
921          let path = self#chooseDir () in
922          match path with
923          | Some path -> newDevel#rootEntry#set_text path
924          | None -> ());
925       connect_button newDevel#cancelButton 
926        (fun () -> newDevel#toplevel#misc#hide ());
927       ignore(newDevel#toplevel#event#connect#delete 
928         (fun _ -> newDevel#toplevel#misc#hide();true));
929       
930         (* file selection win *)
931       ignore (fileSel#fileSelectionWin#event#connect#delete (fun _ -> true));
932       ignore (fileSel#fileSelectionWin#connect#response (fun event ->
933         let return r =
934           chosen_file <- r;
935           fileSel#fileSelectionWin#misc#hide ();
936           GMain.Main.quit ()
937         in
938         match event with
939         | `OK ->
940             let fname = fileSel#fileSelectionWin#filename in
941             if Sys.file_exists fname then
942               begin
943                 if HExtlib.is_regular fname && not (_only_directory) then 
944                   return (Some fname) 
945                 else if _only_directory && HExtlib.is_dir fname then 
946                   return (Some fname)
947               end
948             else
949               begin
950                 if _ok_not_exists then 
951                   return (Some fname)
952               end
953         | `CANCEL -> return None
954         | `HELP -> ()
955         | `DELETE_EVENT -> return None));
956         (* menus *)
957       List.iter (fun w -> w#misc#set_sensitive false) [ main#saveMenuItem ];
958         (* console *)
959       let adj = main#logScrolledWin#vadjustment in
960         ignore (adj#connect#changed
961                 (fun _ -> adj#set_value (adj#upper -. adj#page_size)));
962       console#message (sprintf "\tMatita version %s\n" BuildTimeConf.version);
963         (* toolbar *)
964       let module A = GrafiteAst in
965       let hole = CicNotationPt.UserInput in
966       let loc = HExtlib.dummy_floc in
967       let tac ast _ =
968         if (MatitaScript.current ())#onGoingProof () then
969           (MatitaScript.current ())#advance
970             ~statement:("\n"
971               ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
972                 ~lazy_term_pp:CicNotationPp.pp_term ast)
973             ()
974       in
975       let tac_w_term ast _ =
976         if (MatitaScript.current ())#onGoingProof () then
977           let buf = source_buffer in
978           buf#insert ~iter:(buf#get_iter_at_mark (`NAME "locked"))
979             ("\n"
980             ^ GrafiteAstPp.pp_tactic ~term_pp:CicNotationPp.pp_term
981               ~lazy_term_pp:CicNotationPp.pp_term ast)
982       in
983       let tbar = main in
984       connect_button tbar#introsButton (tac (A.Intros (loc, (None, []))));
985       connect_button tbar#applyButton (tac_w_term (A.Apply (loc, hole)));
986       connect_button tbar#exactButton (tac_w_term (A.Exact (loc, hole)));
987       connect_button tbar#elimButton (tac_w_term
988         (let pattern = None, [], Some CicNotationPt.UserInput in
989         A.Elim (loc, hole, None, pattern, (None, []))));
990       connect_button tbar#elimTypeButton (tac_w_term
991         (A.ElimType (loc, hole, None, (None, []))));
992       connect_button tbar#splitButton (tac (A.Split loc));
993       connect_button tbar#leftButton (tac (A.Left loc));
994       connect_button tbar#rightButton (tac (A.Right loc));
995       connect_button tbar#existsButton (tac (A.Exists loc));
996       connect_button tbar#reflexivityButton (tac (A.Reflexivity loc));
997       connect_button tbar#symmetryButton (tac (A.Symmetry loc));
998       connect_button tbar#transitivityButton
999         (tac_w_term (A.Transitivity (loc, hole)));
1000       connect_button tbar#assumptionButton (tac (A.Assumption loc));
1001       connect_button tbar#cutButton (tac_w_term (A.Cut (loc, None, hole)));
1002       connect_button tbar#autoButton (tac (A.AutoBatch (loc,[])));
1003       MatitaGtkMisc.toggle_widget_visibility
1004        ~widget:(main#tacticsButtonsHandlebox :> GObj.widget)
1005        ~check:main#tacticsBarMenuItem;
1006       let module Hr = Helm_registry in
1007       if
1008         not (Hr.get_opt_default Hr.bool ~default:false "matita.tactics_bar")
1009       then 
1010         main#tacticsBarMenuItem#set_active false;
1011       MatitaGtkMisc.toggle_callback ~check:main#fullscreenMenuItem
1012         ~callback:(function 
1013           | true -> main#toplevel#fullscreen () 
1014           | false -> main#toplevel#unfullscreen ());
1015       main#fullscreenMenuItem#set_active false;
1016       MatitaGtkMisc.toggle_callback ~check:main#ppNotationMenuItem
1017         ~callback:(function
1018           | true ->
1019               CicNotation.set_active_notations
1020                 (List.map fst (CicNotation.get_all_notations ()))
1021           | false ->
1022               CicNotation.set_active_notations []);
1023       MatitaGtkMisc.toggle_callback ~check:main#hideCoercionsMenuItem
1024         ~callback:(fun enabled -> Acic2content.hide_coercions := enabled);
1025       MatitaGtkMisc.toggle_callback ~check:main#unicodeAsTexMenuItem
1026         ~callback:(fun enabled ->
1027           Helm_registry.set_bool "matita.paste_unicode_as_tex" enabled);
1028       if not (Helm_registry.has "matita.paste_unicode_as_tex") then
1029         Helm_registry.set_bool "matita.paste_unicode_as_tex" true;
1030       main#unicodeAsTexMenuItem#set_active
1031         (Helm_registry.get_bool "matita.paste_unicode_as_tex");
1032         (* log *)
1033       HLog.set_log_callback self#console#log_callback;
1034       GtkSignal.user_handler :=
1035         (function 
1036         | MatitaScript.ActionCancelled s -> HLog.error s
1037         | exn ->
1038           if not (Helm_registry.get_bool "matita.debug") then
1039            notify_exn exn
1040           else raise exn);
1041         (* script *)
1042       ignore (source_buffer#connect#mark_set (fun _ _ -> next_ligatures <- []));
1043       let _ =
1044         match GSourceView.source_language_from_file BuildTimeConf.lang_file with
1045         | None ->
1046             HLog.warn (sprintf "can't load language file %s"
1047               BuildTimeConf.lang_file)
1048         | Some matita_lang ->
1049             source_buffer#set_language matita_lang;
1050             source_buffer#set_highlight true
1051       in
1052       let s () = MatitaScript.current () in
1053       let disableSave () =
1054         script_fname <- None;
1055         main#saveMenuItem#misc#set_sensitive false
1056       in
1057       let saveAsScript () =
1058         let script = s () in
1059         match self#chooseFile ~ok_not_exists:true () with
1060         | Some f -> 
1061               script#assignFileName f;
1062               script#saveToFile (); 
1063               console#message ("'"^f^"' saved.\n");
1064               self#_enableSaveTo f
1065         | None -> ()
1066       in
1067       let saveScript () =
1068         match script_fname with
1069         | None -> saveAsScript ()
1070         | Some f -> 
1071               (s ())#assignFileName f;
1072               (s ())#saveToFile ();
1073               console#message ("'"^f^"' saved.\n");
1074       in
1075       let abandon_script () =
1076         let lexicon_status = (s ())#lexicon_status in
1077         let grafite_status = (s ())#grafite_status in
1078         if source_view#buffer#modified then
1079           (match ask_unsaved main#toplevel with
1080           | `YES -> saveScript ()
1081           | `NO -> ()
1082           | `CANCEL -> raise MatitaTypes.Cancel);
1083         (match script_fname with
1084         | None -> ()
1085         | Some fname ->
1086            ask_and_save_moo_if_needed main#toplevel fname
1087             lexicon_status grafite_status);
1088       in
1089       let loadScript () =
1090         let script = s () in 
1091         try 
1092           match self#chooseFile () with
1093           | Some f -> 
1094               abandon_script ();
1095               script#reset (); 
1096               script#assignFileName f;
1097               source_view#source_buffer#begin_not_undoable_action ();
1098               script#loadFromFile f; 
1099               source_view#source_buffer#end_not_undoable_action ();
1100               console#message ("'"^f^"' loaded.\n");
1101               self#_enableSaveTo f
1102           | None -> ()
1103         with MatitaTypes.Cancel -> ()
1104       in
1105       let newScript () = 
1106         abandon_script ();
1107         source_view#source_buffer#begin_not_undoable_action ();
1108         (s ())#reset (); 
1109         (s ())#template (); 
1110         source_view#source_buffer#end_not_undoable_action ();
1111         disableSave ();
1112         script_fname <- None
1113       in
1114       let cursor () =
1115         source_buffer#place_cursor
1116           (source_buffer#get_iter_at_mark (`NAME "locked")) in
1117       let advance _ = (MatitaScript.current ())#advance (); cursor () in
1118       let retract _ = (MatitaScript.current ())#retract (); cursor () in
1119       let top _ = (MatitaScript.current ())#goto `Top (); cursor () in
1120       let bottom _ = (MatitaScript.current ())#goto `Bottom (); cursor () in
1121       let jump _ = (MatitaScript.current ())#goto `Cursor (); cursor () in
1122       let advance = locker (keep_focus advance) in
1123       let retract = locker (keep_focus retract) in
1124       let top = locker (keep_focus top) in
1125       let bottom = locker (keep_focus bottom) in
1126       let jump = locker (keep_focus jump) in
1127         (* quit *)
1128       self#setQuitCallback (fun () -> 
1129         let lexicon_status = (MatitaScript.current ())#lexicon_status in
1130         let grafite_status = (MatitaScript.current ())#grafite_status in
1131         if source_view#buffer#modified then
1132           begin
1133             let rc = ask_unsaved main#toplevel in 
1134             try
1135               match rc with
1136               | `YES -> saveScript ();
1137                         if not source_view#buffer#modified then
1138                           begin
1139                             (match script_fname with
1140                             | None -> ()
1141                             | Some fname -> 
1142                                ask_and_save_moo_if_needed main#toplevel
1143                                 fname lexicon_status grafite_status);
1144                           GMain.Main.quit ()
1145                           end
1146               | `NO -> GMain.Main.quit ()
1147               | `CANCEL -> raise MatitaTypes.Cancel
1148             with MatitaTypes.Cancel -> ()
1149           end 
1150         else 
1151           begin  
1152             (match script_fname with
1153             | None -> clean_current_baseuri grafite_status; GMain.Main.quit ()
1154             | Some fname ->
1155                 try
1156                   ask_and_save_moo_if_needed main#toplevel fname lexicon_status
1157                    grafite_status;
1158                   GMain.Main.quit ()
1159                 with MatitaTypes.Cancel -> ())
1160           end);
1161       connect_button main#scriptAdvanceButton advance;
1162       connect_button main#scriptRetractButton retract;
1163       connect_button main#scriptTopButton top;
1164       connect_button main#scriptBottomButton bottom;
1165       connect_button main#scriptJumpButton jump;
1166       connect_button main#scriptAbortButton kill_worker;
1167       connect_menu_item main#scriptAdvanceMenuItem advance;
1168       connect_menu_item main#scriptRetractMenuItem retract;
1169       connect_menu_item main#scriptTopMenuItem top;
1170       connect_menu_item main#scriptBottomMenuItem bottom;
1171       connect_menu_item main#scriptJumpMenuItem jump;
1172       connect_menu_item main#openMenuItem   loadScript;
1173       connect_menu_item main#saveMenuItem   saveScript;
1174       connect_menu_item main#saveAsMenuItem saveAsScript;
1175       connect_menu_item main#newMenuItem    newScript;
1176       connect_menu_item main#showCoercionsGraphMenuItem 
1177         (fun _ -> 
1178           let c = MatitaMathView.cicBrowser () in
1179           c#load (`About `Coercions));
1180       connect_menu_item main#showAutoGuiMenuItem 
1181         (fun _ -> MatitaAutoGui.auto_dialog Auto.get_auto_status);
1182          (* script monospace font stuff *)  
1183       self#updateFontSize ();
1184         (* debug menu *)
1185       main#debugMenu#misc#hide ();
1186         (* status bar *)
1187       main#hintLowImage#set_file (image_path "matita-bulb-low.png");
1188       main#hintMediumImage#set_file (image_path "matita-bulb-medium.png");
1189       main#hintHighImage#set_file (image_path "matita-bulb-high.png");
1190         (* focus *)
1191       self#sourceView#misc#grab_focus ();
1192         (* main win dimension *)
1193       let width = Gdk.Screen.width () in
1194       let height = Gdk.Screen.height () in
1195       let main_w = width * 90 / 100 in 
1196       let main_h = height * 80 / 100 in
1197       let script_w = main_w * 6 / 10 in
1198       main#toplevel#resize ~width:main_w ~height:main_h;
1199       main#hpaneScriptSequent#set_position script_w;
1200         (* source_view *)
1201       ignore(source_view#connect#after#paste_clipboard 
1202         ~callback:(fun () -> (MatitaScript.current ())#clean_dirty_lock));
1203       (* clean_locked is set to true only "during" a PRIMARY paste
1204          operation (i.e. by clicking with the second mouse button) *)
1205       let clean_locked = ref false in
1206       ignore(source_view#event#connect#button_press
1207         ~callback:
1208           (fun button ->
1209             if GdkEvent.Button.button button = 2 then
1210              clean_locked := true;
1211             false
1212           ));
1213       ignore(source_view#event#connect#button_release
1214         ~callback:(fun button -> clean_locked := false; false));
1215       ignore(source_view#buffer#connect#after#apply_tag
1216        ~callback:(
1217          fun tag ~start:_ ~stop:_ ->
1218           if !clean_locked &&
1219              tag#get_oid = (MatitaScript.current ())#locked_tag#get_oid
1220           then
1221            begin
1222             clean_locked := false;
1223             (MatitaScript.current ())#clean_dirty_lock;
1224             clean_locked := true
1225            end));
1226       (* math view handling *)
1227       connect_menu_item main#newCicBrowserMenuItem (fun () ->
1228         ignore (MatitaMathView.cicBrowser ()));
1229       connect_menu_item main#increaseFontSizeMenuItem (fun () ->
1230         self#increaseFontSize ();
1231         MatitaMathView.increase_font_size ();
1232         MatitaMathView.update_font_sizes ());
1233       connect_menu_item main#decreaseFontSizeMenuItem (fun () ->
1234         self#decreaseFontSize ();
1235         MatitaMathView.decrease_font_size ();
1236         MatitaMathView.update_font_sizes ());
1237       connect_menu_item main#normalFontSizeMenuItem (fun () ->
1238         self#resetFontSize ();
1239         MatitaMathView.reset_font_size ();
1240         MatitaMathView.update_font_sizes ());
1241       MatitaMathView.reset_font_size ();
1242
1243       (** selections / clipboards handling *)
1244
1245     method markupSelected = MatitaMathView.has_selection ()
1246     method private textSelected =
1247       (source_buffer#get_iter_at_mark `INSERT)#compare
1248         (source_buffer#get_iter_at_mark `SEL_BOUND) <> 0
1249     method private somethingSelected = self#markupSelected || self#textSelected
1250     method private markupStored = MatitaMathView.has_clipboard ()
1251     method private textStored = clipboard#text <> None
1252     method private somethingStored = self#markupStored || self#textStored
1253
1254     method canCopy = self#somethingSelected
1255     method canCut = self#textSelected
1256     method canDelete = self#textSelected
1257     method canPaste = self#somethingStored
1258     method canPastePattern = self#markupStored
1259
1260     method copy () =
1261       if self#textSelected
1262       then begin
1263         MatitaMathView.empty_clipboard ();
1264         source_view#buffer#copy_clipboard clipboard;
1265       end else
1266         MatitaMathView.copy_selection ()
1267     method cut () =
1268       source_view#buffer#cut_clipboard clipboard;
1269       MatitaMathView.empty_clipboard ()
1270     method delete () = ignore (source_view#buffer#delete_selection ())
1271     method paste () =
1272       if MatitaMathView.has_clipboard ()
1273       then source_view#buffer#insert (MatitaMathView.paste_clipboard `Term)
1274       else source_view#buffer#paste_clipboard clipboard;
1275       (MatitaScript.current ())#clean_dirty_lock
1276     method pastePattern () =
1277       source_view#buffer#insert (MatitaMathView.paste_clipboard `Pattern)
1278     
1279     method private nextLigature () =
1280       let iter = source_buffer#get_iter_at_mark `INSERT in
1281       let write_ligature len s =
1282         assert(Glib.Utf8.validate s);
1283         source_buffer#delete ~start:iter ~stop:(iter#copy#backward_chars len);
1284         source_buffer#insert ~iter:(source_buffer#get_iter_at_mark `INSERT) s
1285       in
1286       let get_ligature word =
1287         let len = String.length word in
1288         let aux_tex () =
1289           try
1290             for i = len - 1 downto 0 do
1291               if HExtlib.is_alpha word.[i] then ()
1292               else
1293                 (if word.[i] = '\\' then raise (Found i) else raise (Found ~-1))
1294             done;
1295             None
1296           with Found i ->
1297             if i = ~-1 then None else Some (String.sub word i (len - i))
1298         in
1299         let aux_ligature () =
1300           try
1301             for i = len - 1 downto 0 do
1302               if CicNotationLexer.is_ligature_char word.[i] then ()
1303               else raise (Found (i+1))
1304             done;
1305             raise (Found 0)
1306           with
1307           | Found i ->
1308               (try
1309                 Some (String.sub word i (len - i))
1310               with Invalid_argument _ -> None)
1311         in
1312         match aux_tex () with
1313         | Some macro -> macro
1314         | None -> (match aux_ligature () with Some l -> l | None -> word)
1315       in
1316       (match next_ligatures with
1317       | [] -> (* find ligatures and fill next_ligatures, then try again *)
1318           let last_word =
1319             iter#get_slice
1320               ~stop:(iter#copy#backward_find_char Glib.Unichar.isspace)
1321           in
1322           let ligature = get_ligature last_word in
1323           (match CicNotationLexer.lookup_ligatures ligature with
1324           | [] -> ()
1325           | hd :: tl ->
1326               write_ligature (MatitaGtkMisc.utf8_string_length ligature) hd;
1327               next_ligatures <- tl @ [ hd ])
1328       | hd :: tl ->
1329           write_ligature 1 hd;
1330           next_ligatures <- tl @ [ hd ])
1331
1332     method private externalEditor () =
1333       let cmd = Helm_registry.get "matita.external_editor" in
1334 (* ZACK uncomment to enable interactive ask of external editor command *)
1335 (*      let cmd =
1336          let msg =
1337           "External editor command:
1338 %f  will be substitute for the script name,
1339 %p  for the cursor position in bytes,
1340 %l  for the execution point in bytes."
1341         in
1342         ask_text ~gui:self ~title:"External editor" ~msg ~multiline:false
1343           ~default:(Helm_registry.get "matita.external_editor") ()
1344       in *)
1345       let fname = (MatitaScript.current ())#filename in
1346       let slice mark =
1347         source_buffer#start_iter#get_slice
1348           ~stop:(source_buffer#get_iter_at_mark mark)
1349       in
1350       let script = MatitaScript.current () in
1351       let locked = `MARK script#locked_mark in
1352       let string_pos mark = string_of_int (String.length (slice mark)) in
1353       let cursor_pos = string_pos `INSERT in
1354       let locked_pos = string_pos locked in
1355       let cmd =
1356         Pcre.replace ~pat:"%f" ~templ:fname
1357           (Pcre.replace ~pat:"%p" ~templ:cursor_pos
1358             (Pcre.replace ~pat:"%l" ~templ:locked_pos
1359               cmd))
1360       in
1361       let locked_before = slice locked in
1362       let locked_offset = (source_buffer#get_iter_at_mark locked)#offset in
1363       ignore (Unix.system cmd);
1364       source_buffer#set_text (HExtlib.input_file fname);
1365       let locked_iter = source_buffer#get_iter (`OFFSET locked_offset) in
1366       source_buffer#move_mark locked locked_iter;
1367       source_buffer#apply_tag script#locked_tag
1368         ~start:source_buffer#start_iter ~stop:locked_iter;
1369       let locked_after = slice locked in
1370       let line = ref 0 in
1371       let col = ref 0 in
1372       try
1373         for i = 0 to String.length locked_before - 1 do
1374           if locked_before.[i] <> locked_after.[i] then begin
1375             source_buffer#place_cursor
1376               ~where:(source_buffer#get_iter (`LINEBYTE (!line, !col)));
1377             script#goto `Cursor ();
1378             raise Exit
1379           end else if locked_before.[i] = '\n' then begin
1380             incr line;
1381             col := 0
1382           end
1383         done
1384       with
1385       | Exit -> ()
1386       | Invalid_argument _ -> script#goto `Bottom ()
1387
1388     method loadScript file =       
1389       let script = MatitaScript.current () in
1390       script#reset (); 
1391       if Pcre.pmatch ~pat:"\\.p$" file then
1392         begin
1393           let tptppath = 
1394             Helm_registry.get_opt_default Helm_registry.string ~default:"./"
1395               "matita.tptppath"
1396           in
1397           let data = Matitaprover.p_to_ma ~filename:file ~tptppath () in
1398           let filename = Pcre.replace ~pat:"\\.p$" ~templ:".ma" file in
1399           script#assignFileName filename;
1400           source_view#source_buffer#begin_not_undoable_action ();
1401           script#loadFromString data;
1402           source_view#source_buffer#end_not_undoable_action ();
1403           console#message ("'"^filename^"' loaded.");
1404           self#_enableSaveTo filename
1405         end
1406       else
1407         begin
1408           script#assignFileName file;
1409           let content =
1410            if Sys.file_exists file then file
1411            else BuildTimeConf.script_template
1412           in
1413            source_view#source_buffer#begin_not_undoable_action ();
1414            script#loadFromFile content;
1415            source_view#source_buffer#end_not_undoable_action ();
1416            console#message ("'"^file^"' loaded.");
1417            self#_enableSaveTo file
1418         end
1419       
1420     method setStar name b =
1421       let l = main#scriptLabel in
1422       if b then
1423         l#set_text (name ^  " *")
1424       else
1425         l#set_text (name)
1426         
1427     method private _enableSaveTo file =
1428       script_fname <- Some file;
1429       self#main#saveMenuItem#misc#set_sensitive true
1430         
1431     method console = console
1432     method sourceView: GSourceView.source_view =
1433       (source_view: GSourceView.source_view)
1434     method fileSel = fileSel
1435     method findRepl = findRepl
1436     method main = main
1437     method develList = develList
1438     method newDevel = newDevel
1439
1440     method newBrowserWin () =
1441       object (self)
1442         inherit browserWin ()
1443         val combo = GEdit.combo_box_entry ()
1444         initializer
1445           self#check_widgets ();
1446           let combo_widget = combo#coerce in
1447           uriHBox#pack ~from:`END ~fill:true ~expand:true combo_widget;
1448           combo#entry#misc#grab_focus ()
1449         method browserUri = combo
1450       end
1451
1452     method newUriDialog () =
1453       let dialog = new uriChoiceDialog () in
1454       dialog#check_widgets ();
1455       dialog
1456
1457     method newConfirmationDialog () =
1458       let dialog = new confirmationDialog () in
1459       dialog#check_widgets ();
1460       dialog
1461
1462     method newEmptyDialog () =
1463       let dialog = new emptyDialog () in
1464       dialog#check_widgets ();
1465       dialog
1466
1467     method private addKeyBinding key callback =
1468       List.iter (fun evbox -> add_key_binding key callback evbox)
1469         keyBindingBoxes
1470
1471     method setQuitCallback callback =
1472       connect_menu_item main#quitMenuItem callback;
1473       ignore (main#toplevel#event#connect#delete 
1474         (fun _ -> callback ();true));
1475       self#addKeyBinding GdkKeysyms._q callback
1476
1477     method chooseFile ?(ok_not_exists = false) () =
1478       _ok_not_exists <- ok_not_exists;
1479       _only_directory <- false;
1480       fileSel#fileSelectionWin#show ();
1481       GtkThread.main ();
1482       chosen_file
1483
1484     method private chooseDir ?(ok_not_exists = false) () =
1485       _ok_not_exists <- ok_not_exists;
1486       _only_directory <- true;
1487       fileSel#fileSelectionWin#show ();
1488       GtkThread.main ();
1489       (* we should check that this is a directory *)
1490       chosen_file
1491   
1492     method createDevelopment ~containing =
1493       next_devel_must_contain <- containing;
1494       newDevel#toplevel#misc#show()
1495
1496     method askText ?(title = "") ?(msg = "") () =
1497       let dialog = new textDialog () in
1498       dialog#textDialog#set_title title;
1499       dialog#textDialogLabel#set_label msg;
1500       let text = ref None in
1501       let return v =
1502         text := v;
1503         dialog#textDialog#destroy ();
1504         GMain.Main.quit ()
1505       in
1506       ignore (dialog#textDialog#event#connect#delete (fun _ -> true));
1507       connect_button dialog#textDialogCancelButton (fun _ -> return None);
1508       connect_button dialog#textDialogOkButton (fun _ ->
1509         let text = dialog#textDialogTextView#buffer#get_text () in
1510         return (Some text));
1511       dialog#textDialog#show ();
1512       GtkThread.main ();
1513       !text
1514
1515     method private updateFontSize () =
1516       self#sourceView#misc#modify_font_by_name
1517         (sprintf "%s %d" BuildTimeConf.script_font font_size)
1518
1519     method increaseFontSize () =
1520       font_size <- font_size + 1;
1521       self#updateFontSize ()
1522
1523     method decreaseFontSize () =
1524       font_size <- font_size - 1;
1525       self#updateFontSize ()
1526
1527     method resetFontSize () =
1528       font_size <- default_font_size;
1529       self#updateFontSize ()
1530
1531   end
1532
1533 let gui () = 
1534   let g = new gui () in
1535   gui_instance := Some g;
1536   MatitaMathView.set_gui g;
1537   g
1538   
1539 let instance = singleton gui
1540
1541 let non p x = not (p x)
1542
1543 (* this is a shit and should be changed :-{ *)
1544 let interactive_uri_choice
1545   ?(selection_mode:[`SINGLE|`MULTIPLE] = `MULTIPLE) ?(title = "")
1546   ?(msg = "") ?(nonvars_button = false) ?(hide_uri_entry=false) 
1547   ?(hide_try=false) ?(ok_label="_Auto") ?(ok_action:[`SELECT|`AUTO] = `AUTO) 
1548   ?copy_cb ()
1549   ~id uris
1550 =
1551   let gui = instance () in
1552   let nonvars_uris = lazy (List.filter (non UriManager.uri_is_var) uris) in
1553   if (selection_mode <> `SINGLE) &&
1554     (Helm_registry.get_opt_default Helm_registry.get_bool ~default:true "matita.auto_disambiguation")
1555   then
1556     Lazy.force nonvars_uris
1557   else begin
1558     let dialog = gui#newUriDialog () in
1559     if hide_uri_entry then
1560       dialog#uriEntryHBox#misc#hide ();
1561     if hide_try then
1562       begin
1563       dialog#uriChoiceSelectedButton#misc#hide ();
1564       dialog#uriChoiceConstantsButton#misc#hide ();
1565       end;
1566     dialog#okLabel#set_label ok_label;  
1567     dialog#uriChoiceTreeView#selection#set_mode
1568       (selection_mode :> Gtk.Tags.selection_mode);
1569     let model = new stringListModel dialog#uriChoiceTreeView in
1570     let choices = ref None in
1571     (match copy_cb with
1572     | None -> ()
1573     | Some cb ->
1574         dialog#copyButton#misc#show ();
1575         connect_button dialog#copyButton 
1576         (fun _ ->
1577           match model#easy_selection () with
1578           | [u] -> (cb u)
1579           | _ -> ()));
1580     dialog#uriChoiceDialog#set_title title;
1581     dialog#uriChoiceLabel#set_text msg;
1582     List.iter model#easy_append (List.map UriManager.string_of_uri uris);
1583     dialog#uriChoiceConstantsButton#misc#set_sensitive nonvars_button;
1584     let return v =
1585       choices := v;
1586       dialog#uriChoiceDialog#destroy ();
1587       GMain.Main.quit ()
1588     in
1589     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1590     connect_button dialog#uriChoiceConstantsButton (fun _ ->
1591       return (Some (Lazy.force nonvars_uris)));
1592     if ok_action = `AUTO then
1593       connect_button dialog#uriChoiceAutoButton (fun _ ->
1594         Helm_registry.set_bool "matita.auto_disambiguation" true;
1595         return (Some (Lazy.force nonvars_uris)))
1596     else
1597       connect_button dialog#uriChoiceAutoButton (fun _ ->
1598         match model#easy_selection () with
1599         | [] -> ()
1600         | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1601     connect_button dialog#uriChoiceSelectedButton (fun _ ->
1602       match model#easy_selection () with
1603       | [] -> ()
1604       | uris -> return (Some (List.map UriManager.uri_of_string uris)));
1605     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1606     dialog#uriChoiceDialog#show ();
1607     GtkThread.main ();
1608     (match !choices with 
1609     | None -> raise MatitaTypes.Cancel
1610     | Some uris -> uris)
1611   end
1612
1613 class interpModel =
1614   let cols = new GTree.column_list in
1615   let id_col = cols#add Gobject.Data.string in
1616   let dsc_col = cols#add Gobject.Data.string in
1617   let interp_no_col = cols#add Gobject.Data.int in
1618   let tree_store = GTree.tree_store cols in
1619   let id_renderer = GTree.cell_renderer_text [], ["text", id_col] in
1620   let dsc_renderer = GTree.cell_renderer_text [], ["text", dsc_col] in
1621   let id_view_col = GTree.view_column ~renderer:id_renderer () in
1622   let dsc_view_col = GTree.view_column ~renderer:dsc_renderer () in
1623   fun tree_view choices ->
1624     object
1625       initializer
1626         tree_view#set_model (Some (tree_store :> GTree.model));
1627         ignore (tree_view#append_column id_view_col);
1628         ignore (tree_view#append_column dsc_view_col);
1629         let name_of_interp =
1630           (* try to find a reasonable name for an interpretation *)
1631           let idx = ref 0 in
1632           fun interp ->
1633             try
1634               List.assoc "0" interp
1635             with Not_found ->
1636               incr idx; string_of_int !idx
1637         in
1638         tree_store#clear ();
1639         let idx = ref ~-1 in
1640         List.iter
1641           (fun interp ->
1642             incr idx;
1643             let interp_row = tree_store#append () in
1644             tree_store#set ~row:interp_row ~column:id_col
1645               (name_of_interp interp);
1646             tree_store#set ~row:interp_row ~column:interp_no_col !idx;
1647             List.iter
1648               (fun (id, dsc) ->
1649                 let row = tree_store#append ~parent:interp_row () in
1650                 tree_store#set ~row ~column:id_col id;
1651                 tree_store#set ~row ~column:dsc_col dsc;
1652                 tree_store#set ~row ~column:interp_no_col !idx)
1653               interp)
1654           choices
1655
1656       method get_interp_no tree_path =
1657         let iter = tree_store#get_iter tree_path in
1658         tree_store#get ~row:iter ~column:interp_no_col
1659     end
1660
1661 let interactive_string_choice 
1662   text prefix_len ?(title = "") ?(msg = "") () ~id locs uris 
1663 =
1664   let gui = instance () in
1665     let dialog = gui#newUriDialog () in
1666     dialog#uriEntryHBox#misc#hide ();
1667     dialog#uriChoiceSelectedButton#misc#hide ();
1668     dialog#uriChoiceAutoButton#misc#hide ();
1669     dialog#uriChoiceConstantsButton#misc#hide ();
1670     dialog#uriChoiceTreeView#selection#set_mode
1671       (`SINGLE :> Gtk.Tags.selection_mode);
1672     let model = new stringListModel dialog#uriChoiceTreeView in
1673     let choices = ref None in
1674     dialog#uriChoiceDialog#set_title title; 
1675     let hack_len = MatitaGtkMisc.utf8_string_length text in
1676     let rec colorize acc_len = function
1677       | [] -> 
1678           let floc = HExtlib.floc_of_loc (acc_len,hack_len) in
1679           fst(MatitaGtkMisc.utf8_parsed_text text floc)
1680       | he::tl -> 
1681           let start, stop =  HExtlib.loc_of_floc he in
1682           let floc1 = HExtlib.floc_of_loc (acc_len,start) in
1683           let str1,_=MatitaGtkMisc.utf8_parsed_text text floc1 in
1684           let str2,_ = MatitaGtkMisc.utf8_parsed_text text he in
1685           str1 ^ "<b>" ^ str2 ^ "</b>" ^ colorize stop tl
1686     in
1687 (*     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1688                 Printf.eprintf "(%d,%d)" start stop) locs; *)
1689     let locs = 
1690       List.sort 
1691         (fun loc1 loc2 -> 
1692           fst (HExtlib.loc_of_floc loc1) - fst (HExtlib.loc_of_floc loc2)) 
1693         locs 
1694     in
1695 (*     prerr_endline "XXXXXXXXXXXXXXXXXXXX";
1696     List.iter (fun l -> let start, stop = HExtlib.loc_of_floc l in
1697                 Printf.eprintf "(%d,%d)" start stop) locs;
1698     prerr_endline "XXXXXXXXXXXXXXXXXXXX2"; *)
1699     dialog#uriChoiceLabel#set_use_markup true;
1700     let txt = colorize 0 locs in
1701     let txt,_ = MatitaGtkMisc.utf8_parsed_text txt
1702       (HExtlib.floc_of_loc (prefix_len,MatitaGtkMisc.utf8_string_length txt))
1703     in
1704     dialog#uriChoiceLabel#set_label txt;
1705     List.iter model#easy_append uris;
1706     let return v =
1707       choices := v;
1708       dialog#uriChoiceDialog#destroy ();
1709       GMain.Main.quit ()
1710     in
1711     ignore (dialog#uriChoiceDialog#event#connect#delete (fun _ -> true));
1712     connect_button dialog#uriChoiceForwardButton (fun _ ->
1713       match model#easy_selection () with
1714       | [] -> ()
1715       | uris -> return (Some uris));
1716     connect_button dialog#uriChoiceAbortButton (fun _ -> return None);
1717     dialog#uriChoiceDialog#show ();
1718     GtkThread.main ();
1719     (match !choices with 
1720     | None -> raise MatitaTypes.Cancel
1721     | Some uris -> uris)
1722
1723 let interactive_interp_choice () text prefix_len choices =
1724 (*List.iter (fun l -> prerr_endline "==="; List.iter (fun (_,id,dsc) -> prerr_endline (id ^ " = " ^ dsc)) l) choices;*)
1725  let filter_choices filter =
1726   let rec is_compatible filter =
1727    function
1728       [] -> true
1729     | ([],_,_)::tl -> is_compatible filter tl
1730     | (loc::tlloc,id,dsc)::tl ->
1731        try
1732         if List.assoc (loc,id) filter = dsc then
1733          is_compatible filter ((tlloc,id,dsc)::tl)
1734         else
1735          false
1736        with
1737         Not_found -> true
1738   in
1739    List.filter (fun (_,interp) -> is_compatible filter interp)
1740  in
1741  let rec get_choices loc id =
1742   function
1743      [] -> []
1744    | (_,he)::tl ->
1745       let _,_,dsc =
1746        List.find (fun (locs,id',_) -> id = id' && List.mem loc locs) he
1747       in
1748        dsc :: (List.filter (fun dsc' -> dsc <> dsc') (get_choices loc id tl))
1749  in
1750  let example_interp =
1751   match choices with
1752      [] -> assert false
1753    | he::_ -> he in
1754  let ask_user id locs choices =
1755   interactive_string_choice
1756    text prefix_len
1757    ~title:"Ambiguous input"
1758    ~msg:("Choose an interpretation for " ^ id) () ~id locs choices
1759  in
1760  let rec classify ids filter partial_interpretations =
1761   match ids with
1762      [] -> List.map fst partial_interpretations
1763    | ([],_,_)::tl -> classify tl filter partial_interpretations
1764    | (loc::tlloc,id,dsc)::tl ->
1765       let choices = get_choices loc id partial_interpretations in
1766       let chosen_dsc =
1767        match choices with
1768           [] -> prerr_endline ("NO CHOICES FOR " ^ id); assert false
1769         | [dsc] -> dsc
1770         | _ ->
1771           match ask_user id [loc] choices with
1772              [x] -> x
1773            | _ -> assert false
1774       in
1775        let filter = ((loc,id),chosen_dsc)::filter in
1776        let compatible_interps = filter_choices filter partial_interpretations in
1777         classify ((tlloc,id,dsc)::tl) filter compatible_interps
1778  in
1779  let enumerated_choices =
1780   let idx = ref ~-1 in
1781   List.map (fun interp -> incr idx; !idx,interp) choices
1782  in
1783   classify example_interp [] enumerated_choices
1784
1785 let _ =
1786   (* disambiguator callbacks *)
1787   GrafiteDisambiguator.set_choose_uris_callback (interactive_uri_choice ());
1788   GrafiteDisambiguator.set_choose_interp_callback (interactive_interp_choice ());
1789   (* gtk initialization *)
1790   GtkMain.Rc.add_default_file BuildTimeConf.gtkrc_file; (* loads gtk rc *)
1791   GMathView.add_configuration_path BuildTimeConf.gtkmathview_conf;
1792   ignore (GMain.Main.init ())
1793