]> matita.cs.unibo.it Git - helm.git/blobdiff - helm/gTopLevel/gTopLevel.ml
split into two major parts:
[helm.git] / helm / gTopLevel / gTopLevel.ml
index 9fd0b352b838bfb14b9b28887b58eb266a81c8e7..b62f4b6245dbc5b88b73df47bc8ab77633277f49 100644 (file)
@@ -1,4 +1,4 @@
-(* Copyright (C) 2000-2003, HELM Team.
+(* Copyright (C) 2000-2004, HELM Team.
  * 
  * This file is part of HELM, an Hypertextual, Electronic
  * Library of Mathematics, developed at the Computer Science
 (*                                                                            *)
 (******************************************************************************)
 
-open Printf;;
+let debug_level = ref 1
+let debug_print ?(level = 1) s = if !debug_level >= level then prerr_endline s
+
+open Printf
 
 (* DEBUGGING *)
 
@@ -45,24 +48,12 @@ module MQG  = MQueryGenerator
 
 (* GLOBAL CONSTANTS *)
 
-let mqi_flags = [MQIC.Postgres ; MQIC.Stat ; MQIC.Warn ; MQIC.Log] (* default MathQL interpreter options *)
-(*
-let mqi_flags = [] (* default MathQL interpreter options *)
-*)
-let mqi_handle = MQIC.init mqi_flags prerr_string
+let mqi_debug_fun s = debug_print ~level:2 s
+let mqi_flags = [MQIC.Postgres ; MQIC.Stat ; MQIC.Warn ; MQIC.Log]
+let mqi_handle = MQIC.init mqi_flags mqi_debug_fun
 
 let xlinkns = Gdome.domString "http://www.w3.org/1999/xlink";;
 
-let htmlheader =
- "<html>" ^
- " <body bgColor=\"white\">"
-;;
-
-let htmlfooter =
- " </body>" ^
- "</html>"
-;;
-
 let prooffile =
  try
   Sys.getenv "GTOPLEVEL_PROOFFILE"
@@ -87,9 +78,9 @@ let environmentfile =
 let restore_environment_on_boot = true ;;
 let notify_hbugs_on_goal_change = false ;;
 
-(* GLOBAL REFERENCES (USED BY CALLBACKS) *)
+let auto_disambiguation = ref true ;;
 
-let htmlheader_and_content = ref htmlheader;;
+(* GLOBAL REFERENCES (USED BY CALLBACKS) *)
 
 let check_term = ref (fun _ _ _ -> assert false);;
 
@@ -121,11 +112,11 @@ exception OutputHtmlNotInitialized;;
 
 let set_outputhtml,outputhtml =
  let outputhtml_ref = ref None in
-  (function rw -> outputhtml_ref := Some rw),
+  (function (rw: Ui_logger.html_logger) -> outputhtml_ref := Some rw),
   (function () ->
     match !outputhtml_ref with
-       None -> raise OutputHtmlNotInitialized
-     | Some outputhtml -> outputhtml
+     | None -> raise OutputHtmlNotInitialized
+     | Some outputhtml -> (outputhtml: Ui_logger.html_logger)
   )
 ;;
 
@@ -179,17 +170,14 @@ let string_of_cic_textual_parser_uri uri =
    String.sub uri' 4 (String.length uri' - 4)
 ;;
 
-let output_html outputhtml msg =
- htmlheader_and_content := !htmlheader_and_content ^ msg ;
- outputhtml#source (!htmlheader_and_content ^ htmlfooter) ;
- outputhtml#set_topline (-1)
-;;
+let output_html ?(append_NL = true) (outputhtml: Ui_logger.html_logger) =
+  outputhtml#log ~append_NL
 
 (* UTILITY FUNCTIONS TO DISAMBIGUATE AN URI *)
 
 (* Check window *)
 
-let check_window outputhtml uris =
+let check_window (outputhtml: Ui_logger.html_logger) uris =
  let window =
   GWindow.window
    ~width:800 ~modal:true ~title:"Check" ~border_width:2 () in
@@ -220,8 +208,7 @@ let check_window outputhtml uris =
           mmlwidget#load_sequent [] (111,[],expr)
          with
           e ->
-           output_html outputhtml
-            ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
+           output_html outputhtml (`Error (`T (Printexc.to_string e)))
        )
    ) uris
  in
@@ -237,110 +224,131 @@ let
  interactive_user_uri_choice ~(selection_mode:[`MULTIPLE|`SINGLE]) ?(ok="Ok")
   ?(enable_button_for_non_vars=false) ~title ~msg uris
 =
- let choices = ref [] in
- let chosen = ref false in
- let use_only_constants = ref false in
- let window =
-  GWindow.dialog ~modal:true ~title ~width:600 () in
- let lMessage =
-  GMisc.label ~text:msg
-   ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
- let scrolled_window =
-  GBin.scrolled_window ~border_width:10
-   ~packing:(window#vbox#pack ~expand:true ~fill:true ~padding:5) () in
- let clist =
-  let expected_height = 18 * List.length uris in
-   let height = if expected_height > 400 then 400 else expected_height in
-    GList.clist ~columns:1 ~packing:scrolled_window#add
-     ~height ~selection_mode:(selection_mode :> Gtk.Tags.selection_mode) () in
- let _ = List.map (function x -> clist#append [x]) uris in
- let hbox2 =
-  GPack.hbox ~border_width:0
-   ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
- let explain_label =
-  GMisc.label ~text:"None of the above. Try this one:"
-   ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
- let manual_input =
-  GEdit.entry ~editable:true
-   ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
- let hbox =
-  GPack.hbox ~border_width:0 ~packing:window#action_area#add () in
- let okb =
-  GButton.button ~label:ok
-   ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
- let _ = okb#misc#set_sensitive false in
- let nonvarsb =
-  GButton.button
-   ~packing:
-    (function w ->
-      if enable_button_for_non_vars then
-       hbox#pack ~expand:false ~fill:false ~padding:5 w)
-   ~label:"Try constants only" () in
- let checkb =
-  GButton.button ~label:"Check"
-   ~packing:(hbox#pack ~padding:5) () in
- let _ = checkb#misc#set_sensitive false in
- let cancelb =
-  GButton.button ~label:"Abort"
-   ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
- (* actions *)
- let check_callback () =
-  assert (List.length !choices > 0) ;
-  check_window (outputhtml ()) !choices
+ let only_constant_choices =
+   lazy
+     (List.filter
+      (fun uri -> not (String.sub uri (String.length uri - 4) 4 = ".var"))
+      uris)
  in
-  ignore (window#connect#destroy GMain.Main.quit) ;
-  ignore (cancelb#connect#clicked window#destroy) ;
-  ignore
-   (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
-  ignore
-   (nonvarsb#connect#clicked
-     (function () ->
-       use_only_constants := true ;
-       chosen := true ;
-       window#destroy ()
-   )) ;
-  ignore (checkb#connect#clicked check_callback) ;
-  ignore
-   (clist#connect#select_row
-     (fun ~row ~column ~event ->
-       checkb#misc#set_sensitive true ;
-       okb#misc#set_sensitive true ;
-       choices := (List.nth uris row)::!choices)) ;
-  ignore
-   (clist#connect#unselect_row
-     (fun ~row ~column ~event ->
-       choices :=
-        List.filter (function uri -> uri != (List.nth uris row)) !choices)) ;
-  ignore
-   (manual_input#connect#changed
-     (fun _ ->
-       if manual_input#text = "" then
-        begin
-         choices := [] ;
-         checkb#misc#set_sensitive false ;
-         okb#misc#set_sensitive false ;
-         clist#misc#set_sensitive true
-        end
-       else
-        begin
-         choices := [manual_input#text] ;
-         clist#unselect_all () ;
+ if !auto_disambiguation then
+  Lazy.force only_constant_choices
+ else begin
+   let choices = ref [] in
+   let chosen = ref false in
+   let use_only_constants = ref false in
+   let window =
+    GWindow.dialog ~modal:true ~title ~width:600 () in
+   let lMessage =
+    GMisc.label ~text:msg
+     ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
+   let scrolled_window =
+    GBin.scrolled_window ~border_width:10
+     ~packing:(window#vbox#pack ~expand:true ~fill:true ~padding:5) () in
+   let clist =
+    let expected_height = 18 * List.length uris in
+     let height = if expected_height > 400 then 400 else expected_height in
+      GList.clist ~columns:1 ~packing:scrolled_window#add
+       ~height ~selection_mode:(selection_mode :> Gtk.Tags.selection_mode) () in
+   let _ = List.map (function x -> clist#append [x]) uris in
+   let hbox2 =
+    GPack.hbox ~border_width:0
+     ~packing:(window#vbox#pack ~expand:false ~fill:false ~padding:5) () in
+   let explain_label =
+    GMisc.label ~text:"None of the above. Try this one:"
+     ~packing:(hbox2#pack ~expand:false ~fill:false ~padding:5) () in
+   let manual_input =
+    GEdit.entry ~editable:true
+     ~packing:(hbox2#pack ~expand:true ~fill:true ~padding:5) () in
+   let hbox =
+    GPack.hbox ~border_width:0 ~packing:window#action_area#add () in
+   let okb =
+    GButton.button ~label:ok
+     ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
+   let _ = okb#misc#set_sensitive false in
+   let nonvarsb =
+    GButton.button
+     ~packing:
+      (function w ->
+        if enable_button_for_non_vars then
+         hbox#pack ~expand:false ~fill:false ~padding:5 w)
+     ~label:"Try constants only" () in
+   let autob =
+    GButton.button
+     ~packing:
+      (fun w ->
+        if enable_button_for_non_vars then
+         hbox#pack ~expand:false ~fill:false ~padding:5 w)
+     ~label:"Auto" () in
+   let checkb =
+    GButton.button ~label:"Check"
+     ~packing:(hbox#pack ~padding:5) () in
+   let _ = checkb#misc#set_sensitive false in
+   let cancelb =
+    GButton.button ~label:"Abort"
+     ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
+   (* actions *)
+   let check_callback () =
+    assert (List.length !choices > 0) ;
+    check_window (outputhtml ()) !choices
+   in
+    ignore (window#connect#destroy GMain.Main.quit) ;
+    ignore (cancelb#connect#clicked window#destroy) ;
+    ignore
+     (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
+    ignore
+     (nonvarsb#connect#clicked
+       (function () ->
+         use_only_constants := true ;
+         chosen := true ;
+         window#destroy ()
+     )) ;
+    ignore (autob#connect#clicked (fun () ->
+      auto_disambiguation := true;
+      (rendering_window ())#set_auto_disambiguation true;
+      use_only_constants := true ;
+      chosen := true;
+      window#destroy ()));
+    ignore (checkb#connect#clicked check_callback) ;
+    ignore
+     (clist#connect#select_row
+       (fun ~row ~column ~event ->
          checkb#misc#set_sensitive true ;
          okb#misc#set_sensitive true ;
-         clist#misc#set_sensitive false
-        end));
-  window#set_position `CENTER ;
-  window#show () ;
-  GtkThread.main ();
-  if !chosen then
-   if !use_only_constants then
-    List.filter
-     (function uri -> not (String.sub uri (String.length uri - 4) 4 = ".var"))
-     uris
-   else
-    if List.length !choices > 0 then !choices else raise NoChoice
-  else
-   raise NoChoice
+         choices := (List.nth uris row)::!choices)) ;
+    ignore
+     (clist#connect#unselect_row
+       (fun ~row ~column ~event ->
+         choices :=
+          List.filter (function uri -> uri != (List.nth uris row)) !choices)) ;
+    ignore
+     (manual_input#connect#changed
+       (fun _ ->
+         if manual_input#text = "" then
+          begin
+           choices := [] ;
+           checkb#misc#set_sensitive false ;
+           okb#misc#set_sensitive false ;
+           clist#misc#set_sensitive true
+          end
+         else
+          begin
+           choices := [manual_input#text] ;
+           clist#unselect_all () ;
+           checkb#misc#set_sensitive true ;
+           okb#misc#set_sensitive true ;
+           clist#misc#set_sensitive false
+          end));
+    window#set_position `CENTER ;
+    window#show () ;
+    GtkThread.main ();
+    if !chosen then
+     if !use_only_constants then
+       Lazy.force only_constant_choices
+     else
+      if List.length !choices > 0 then !choices else raise NoChoice
+    else
+     raise NoChoice
+ end
 ;;
 
 let interactive_interpretation_choice interpretations =
@@ -511,12 +519,10 @@ let save_unfinished_proof () =
  let (xml, bodyxml) = ProofEngine.get_current_status_as_xml () in
  Xml.pp ~quiet:true xml (Some prooffiletype) ;
  output_html outputhtml
-  ("<h1 color=\"Green\">Current proof type saved to " ^
-   prooffiletype ^ "</h1>") ;
+  (`Msg (`T ("Current proof type saved to " ^ prooffiletype))) ;
  Xml.pp ~quiet:true bodyxml (Some prooffile) ;
  output_html outputhtml
-  ("<h1 color=\"Green\">Current proof body saved to " ^
-   prooffile ^ "</h1>")
+  (`Msg (`T ("Current proof body saved to " ^ prooffile)))
 ;;
 
 (* Used to typecheck the loaded proofs *)
@@ -550,9 +556,9 @@ let decompose_uris_choice_callback uris =
     ) 
 ;;
 
-let mk_fresh_name_callback context name ~typ =
+let mk_fresh_name_callback metasenv context name ~typ =
  let fresh_name =
-  match ProofEngineHelpers.mk_fresh_name context name ~typ with
+  match FreshNamesGenerator.mk_fresh_name metasenv context name ~typ with
      Cic.Name fresh_name -> fresh_name
    | Cic.Anonymous -> assert false
  in
@@ -576,10 +582,10 @@ let refresh_proof (output : TermViewer.proof_viewer) =
        if List.length metasenv = 0 then
         begin
          !qed_set_sensitive true ;
-         (*Hbugs.clear*) ()
+         Hbugs.clear ()
         end
        else
-        (*Hbugs.notify*) () ;
+        Hbugs.notify () ;
        (*CSC: Wrong: [] is just plainly wrong *)
        uri,
         (Cic.CurrentProof (UriManager.name_of_uri uri, metasenv, bo, ty, []))
@@ -590,8 +596,8 @@ let refresh_proof (output : TermViewer.proof_viewer) =
  match ProofEngine.get_proof () with
     None -> assert false
   | Some (uri,metasenv,bo,ty) ->
-prerr_endline ("Offending proof: " ^ CicPp.ppobj (Cic.CurrentProof ("questa",metasenv,bo,ty,[]))) ; flush stderr ;
-   raise (InvokeTactics.RefreshProofException e)
+      debug_print ("Offending proof: " ^ CicPp.ppobj (Cic.CurrentProof ("questa",metasenv,bo,ty,[])));
+      raise (InvokeTactics.RefreshProofException e)
 
 let set_proof_engine_goal g =
  ProofEngine.goal := g
@@ -651,10 +657,13 @@ let metasenv =
   | Some (_,metasenv,_,_) -> metasenv
 in
 try
-let currentsequent = List.find (function (m,_,_) -> m=metano) metasenv in
-   prerr_endline ("Offending sequent: " ^ SequentPp.TextualPp.print_sequent currentsequent) ; flush stderr ;
-      raise (InvokeTactics.RefreshSequentException e)
-with Not_found -> prerr_endline ("Offending sequent " ^ string_of_int metano ^ " unknown."); raise (InvokeTactics.RefreshSequentException e)
+  let currentsequent = List.find (function (m,_,_) -> m=metano) metasenv in
+  debug_print
+    ("Offending sequent: " ^ SequentPp.TextualPp.print_sequent currentsequent);
+  raise (InvokeTactics.RefreshSequentException e)
+with Not_found ->
+  debug_print ("Offending sequent " ^ string_of_int metano ^ " unknown.");
+  raise (InvokeTactics.RefreshSequentException e)
 
 module InvokeTacticsCallbacks =
  struct
@@ -676,9 +685,8 @@ module InvokeTacticsCallbacks =
  end
 ;;
 module InvokeTactics' = InvokeTactics.Make (InvokeTacticsCallbacks);;
-
-(* Just to initialize the Hbugs module *)
 (*
+(* Just to initialize the Hbugs module *)
 module Ignore = Hbugs.Initialize (InvokeTactics');;
 Hbugs.set_describe_hint_callback (fun hint ->
   match hint with
@@ -688,7 +696,6 @@ Hbugs.set_describe_hint_callback (fun hint ->
   | _ -> ())
 ;;
 *)
-
 let dummy_uri = "/dummy.con"
 
   (** load an unfinished proof from filesystem *)
@@ -716,31 +723,38 @@ let load_unfinished_proof () =
              ) ;
             refresh_goals notebook ;
              output_html outputhtml
-              ("<h1 color=\"Green\">Current proof type loaded from " ^
-                prooffiletype ^ "</h1>") ;
+              (`Msg (`T ("Current proof type loaded from " ^
+                prooffiletype))) ;
              output_html outputhtml
-              ("<h1 color=\"Green\">Current proof body loaded from " ^
-                prooffile ^ "</h1>") ;
+              (`Msg (`T ("Current proof body loaded from " ^
+                prooffile))) ;
             !save_set_sensitive true;
          | _ -> assert false
   with
      InvokeTactics.RefreshSequentException e ->
       output_html outputhtml
-       ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-        "sequent: " ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T ("Exception raised during the refresh of the " ^
+        "sequent: " ^ Printexc.to_string e)))
    | InvokeTactics.RefreshProofException e ->
       output_html outputhtml
-       ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-        "proof: " ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T ("Exception raised during the refresh of the " ^
+        "proof: " ^ Printexc.to_string e)))
    | e ->
       output_html outputhtml
-       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+       (`Error (`T (Printexc.to_string e)))
+;;
+
+let clear_aliases () =
+  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
+  inputt#environment :=
+    DisambiguatingParser.EnvironmentP3.of_string
+      DisambiguatingParser.EnvironmentP3.empty
 ;;
 
 let edit_aliases () =
  let inputt = ((rendering_window ())#inputt : TermEditor.term_editor) in
- let id_to_uris = inputt#id_to_uris in
- let chosen = ref false in
+ let disambiguation_env = inputt#environment in
+ let chosen_aliases = ref None in
  let window =
   GWindow.window
    ~width:400 ~modal:true ~title:"Edit Aliases..." ~border_width:2 () in
@@ -757,72 +771,37 @@ let edit_aliases () =
  let okb =
   GButton.button ~label:"Ok"
    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
+ let clearb =
+  GButton.button ~label:"Clear"
+   ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
  let cancelb =
   GButton.button ~label:"Cancel"
    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
  ignore (window#connect#destroy GMain.Main.quit) ;
  ignore (cancelb#connect#clicked window#destroy) ;
- ignore
-  (okb#connect#clicked (function () -> chosen := true ; window#destroy ())) ;
- let dom,resolve_id = !id_to_uris in
+ ignore (clearb#connect#clicked (fun () ->
+  input#buffer#set_text DisambiguatingParser.EnvironmentP3.empty)) ;
+ ignore (okb#connect#clicked (fun () ->
+    chosen_aliases := Some (input#buffer#get_text ());
+    window#destroy ()));
   ignore
    (input#buffer#insert ~iter:(input#buffer#get_iter_at_char 0)
-    (String.concat "\n"
-      (List.map
-        (function v ->
-          let uri =
-           match resolve_id v with
-              None -> assert false
-            | Some (CicTextualParser0.Uri uri) -> uri
-            | Some (CicTextualParser0.Term _)
-            | Some CicTextualParser0.Implicit -> assert false
-          in
-           "alias " ^
-            (match v with
-                CicTextualParser0.Id id -> id
-              | CicTextualParser0.Symbol (descr,_) ->
-                 (* CSC: To be implemented *)
-                 assert false
-            )^ " " ^ (string_of_cic_textual_parser_uri uri)
-        ) dom))) ;
+     (DisambiguatingParser.EnvironmentP3.to_string !disambiguation_env ^ "\n"));
   window#show () ;
   GtkThread.main ();
-  if !chosen then
-   let dom,resolve_id =
-    let inputtext = input#buffer#get_text () in
-    let regexpr =
-     let alfa = "[a-zA-Z_-]" in
-     let digit = "[0-9]" in
-     let ident = alfa ^ "\(" ^ alfa ^ "\|" ^ digit ^ "\)*" in
-     let blanks = "\( \|\t\|\n\)+" in
-     let nonblanks = "[^ \t\n]+" in
-     let uri = "/\(" ^ ident ^ "/\)*" ^ nonblanks in (* not very strict check *)
-      Str.regexp
-       ("alias" ^ blanks ^ "\(" ^ ident ^ "\)" ^ blanks ^ "\(" ^ uri ^ "\)")
-    in
-     let rec aux n =
-      try
-       let n' = Str.search_forward regexpr inputtext n in
-        let id = CicTextualParser0.Id (Str.matched_group 2 inputtext) in
-        let uri =
-         MQueryMisc.cic_textual_parser_uri_of_string
-          ("cic:" ^ (Str.matched_group 5 inputtext))
-        in
-         let dom,resolve_id = aux (n' + 1) in
-          if List.mem id dom then
-           dom,resolve_id
-          else
-           id::dom,
-            (function id' ->
-              if id = id' then
-               Some (CicTextualParser0.Uri uri)
-              else resolve_id id')
-      with
-       Not_found -> TermEditor.empty_id_to_uris
-     in
-      aux 0
-   in
-    id_to_uris := (dom,resolve_id)
+  match !chosen_aliases with
+  | None -> ()
+  | Some raw_aliases ->
+      let new_disambiguation_env =
+        (try
+          DisambiguatingParser.EnvironmentP3.of_string raw_aliases
+        with e ->
+          output_html (outputhtml ())
+            (`Error (`T
+              ("Error while parsing aliases: " ^ Printexc.to_string e)));
+          !disambiguation_env)
+      in
+      disambiguation_env := new_disambiguation_env
 ;;
 
 let proveit () =
@@ -830,7 +809,7 @@ let proveit () =
  let module G = Gdome in
  let notebook = (rendering_window ())#notebook in
  let output = (rendering_window ())#output in
- let outputhtml = ((rendering_window ())#outputhtml (*: GHtml.xmhtml*)) in
+ let outputhtml = (rendering_window ())#outputhtml in
   try
    output#make_sequent_of_selected_term ;
    refresh_proof output ;
@@ -838,15 +817,15 @@ let proveit () =
   with
      InvokeTactics.RefreshSequentException e ->
       output_html outputhtml
-       ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-        "sequent: " ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T ("Exception raised during the refresh of the " ^
+        "sequent: " ^ Printexc.to_string e)))
    | InvokeTactics.RefreshProofException e ->
       output_html outputhtml
-       ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-        "proof: " ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T ("Exception raised during the refresh of the " ^
+        "proof: " ^ Printexc.to_string e)))
    | e ->
       output_html outputhtml
-       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T (Printexc.to_string e)))
 ;;
 
 let focus () =
@@ -861,15 +840,15 @@ let focus () =
   with
      InvokeTactics.RefreshSequentException e ->
       output_html outputhtml
-       ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-        "sequent: " ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T ("Exception raised during the refresh of the " ^
+        "sequent: " ^ Printexc.to_string e)))
    | InvokeTactics.RefreshProofException e ->
       output_html outputhtml
-       ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-        "proof: " ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T ("Exception raised during the refresh of the " ^
+        "proof: " ^ Printexc.to_string e)))
    | e ->
       output_html outputhtml
-       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T (Printexc.to_string e)))
 ;;
 
 exception NoPrevGoal;;
@@ -879,7 +858,8 @@ let setgoal metano =
  let module L = LogicalOperations in
  let module G = Gdome in
  let notebook = (rendering_window ())#notebook in
- let outputhtml = ((rendering_window ())#outputhtml(* : GHtml.xmhtml*)) in
+ let output = (rendering_window ())#output in
+ let outputhtml = (rendering_window ())#outputhtml in
   let metasenv =
    match ProofEngine.get_proof () with
       None -> assert false
@@ -890,11 +870,11 @@ let setgoal metano =
    with
       InvokeTactics.RefreshSequentException e ->
        output_html outputhtml
-        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-         "sequent: " ^ Printexc.to_string e ^ "</h1>")
+        (`Error (`T ("Exception raised during the refresh of the " ^
+         "sequent: " ^ Printexc.to_string e)))
     | e ->
        output_html outputhtml
-        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
+        (`Error (`T (Printexc.to_string e)))
 ;;
 
 let
@@ -920,7 +900,7 @@ let
       Cic2acic.acic_object_of_cic_object obj
      in
       let mml =
-       ApplyStylesheets.mml_of_cic_object
+       ChosenTransformer.mml_of_cic_object
         ~explode_all:false uri acic ids_to_inner_sorts ids_to_inner_types
       in
        window#set_title (UriManager.string_of_uri uri) ;
@@ -929,7 +909,7 @@ let
     with
      e ->
       output_html outputhtml
-       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+       (`Error (`T (Printexc.to_string e)))
   in
   let show_in_show_window_uri uri =
    let obj = CicEnvironment.get_obj uri in
@@ -981,10 +961,10 @@ let locate_callback id =
    (function uri,_ ->
      MQueryMisc.wrong_xpointer_format_from_wrong_xpointer_format' uri)
    result in
-  out "<h1>Locate Query: </h1><pre>";
-  MQueryUtil.text_of_query out "" query; 
-  out "<h1>Result:</h1>";
-  MQueryUtil.text_of_result out "<br>" result;
+  out (`Msg (`T "Locate Query:")) ;
+  MQueryUtil.text_of_query (fun m -> out (`Msg (`T m))) "" query; 
+  out (`Msg (`T "Result:")) ;
+  MQueryUtil.text_of_result (fun m -> out (`Msg (`T m))) "" result;
   user_uri_choice ~title:"Ambiguous input."
    ~msg:
      ("Ambiguous input \"" ^ id ^
@@ -1040,21 +1020,21 @@ let input_or_locate_uri ~title =
    let uri = "cic:" ^ manual_input#text in
     try
       ignore (Getter.resolve (UriManager.uri_of_string uri)) ;
-      output_html outputhtml "<h1 color=\"Green\">OK</h1>" ;
+      output_html outputhtml (`Msg (`T "OK")) ;
       true
     with
        Getter.Unresolved ->
         output_html outputhtml
-         ("<h1 color=\"Red\">URI " ^ uri ^
-          " does not correspond to any object.</h1>") ;
+         (`Error (`T ("URI " ^ uri ^
+          " does not correspond to any object."))) ;
         false
      | UriManager.IllFormedUri _ ->
         output_html outputhtml
-         ("<h1 color=\"Red\">URI " ^ uri ^ " is not well-formed.</h1>") ;
+         (`Error (`T ("URI " ^ uri ^ " is not well-formed."))) ;
         false
      | e ->
         output_html outputhtml
-         ("<h1 color=\"Red\">" ^ Printexc.to_string e ^ "</h1>") ;
+         (`Error (`T (Printexc.to_string e))) ;
         false
   in
   ignore
@@ -1101,29 +1081,19 @@ exception AmbiguousInput;;
 
 (* A WIDGET TO ENTER CIC TERMS *)
 
-module ChosenTermEditor  = TexTermEditor;;
-module ChosenTextualParser0 = TexCicTextualParser0;;
-(*
-module ChosenTermEditor = TermEditor;;
-module ChosenTextualParser0 = CicTextualParser0;;
-*)
-
-module Callbacks =
+module DisambiguateCallbacks =
  struct
-  let get_metasenv () = !ChosenTextualParser0.metasenv
-  let set_metasenv metasenv = ChosenTextualParser0.metasenv := metasenv
-
-  let output_html msg = output_html (outputhtml ()) msg;;
+  let output_html ?append_NL = output_html ?append_NL (outputhtml ())
   let interactive_user_uri_choice =
    fun ~selection_mode ?ok ?enable_button_for_non_vars ~title ~msg ~id ->
     interactive_user_uri_choice ~selection_mode ?ok
-     ?enable_button_for_non_vars ~title ~msg;;
-  let interactive_interpretation_choice = interactive_interpretation_choice;;
-  let input_or_locate_uri = input_or_locate_uri;;
+     ?enable_button_for_non_vars ~title ~msg
+  let interactive_interpretation_choice = interactive_interpretation_choice
+  let input_or_locate_uri = input_or_locate_uri
  end
 ;;
 
-module TexTermEditor' = ChosenTermEditor.Make(Callbacks);;
+module TermEditor' = ChosenTermEditor.Make (DisambiguateCallbacks);;
 
 (* OTHER FUNCTIONS *)
 
@@ -1141,7 +1111,7 @@ let locate () =
    with
     e ->
      output_html outputhtml
-      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
+      (`Error (`T (Printexc.to_string e)))
 ;;
 
 
@@ -1250,7 +1220,7 @@ let new_inductive () =
        with
         e ->
          output_html outputhtml
-          ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+          (`Error (`T (Printexc.to_string e)))
      ))
  (* Second phase *)
  and phase2 () =
@@ -1269,10 +1239,10 @@ let new_inductive () =
        GBin.scrolled_window ~border_width:5
         ~packing:(vbox#pack ~expand:true ~padding:0) () in
       let newinputt =
-       TexTermEditor'.term_editor
+       TermEditor'.term_editor
         mqi_handle
         ~width:400 ~height:20 ~packing:scrolled_window#add 
-        ~share_id_to_uris_with:inputt ()
+        ~share_environment_with:inputt ()
         ~isnotempty_callback:
          (function b ->
            (*non_empty_type := b ;*)
@@ -1357,7 +1327,7 @@ let new_inductive () =
         with
          e ->
           output_html outputhtml
-           ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+           (`Error (`T (Printexc.to_string e)))
       ))
  (* Third phase *)
  and phase3 name cons =
@@ -1381,10 +1351,10 @@ let new_inductive () =
        GBin.scrolled_window ~border_width:5
         ~packing:(vbox#pack ~expand:true ~padding:0) () in
       let newinputt =
-       TexTermEditor'.term_editor
+       TermEditor'.term_editor
         mqi_handle
         ~width:400 ~height:20 ~packing:scrolled_window#add
-        ~share_id_to_uris_with:inputt ()
+        ~share_environment_with:inputt ()
         ~isnotempty_callback:
          (function b ->
            (* (*non_empty_type := b ;*)
@@ -1431,7 +1401,7 @@ let new_inductive () =
        with
         e ->
          output_html outputhtml
-          ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+          (`Error (`T (Printexc.to_string e)))
      )) ;
   window2#show () ;
   GtkThread.main ();
@@ -1459,13 +1429,13 @@ let new_inductive () =
      let obj = Cic.InductiveDefinition(tys,params,!paramsno) in
       begin
        try
-        prerr_endline (CicPp.ppobj obj) ;
+        debug_print (CicPp.ppobj obj);
         CicTypeChecker.typecheck_mutual_inductive_defs uri
          (tys,params,!paramsno) ;
         with
          e ->
-          prerr_endline "Offending mutual (co)inductive type declaration:" ;
-          prerr_endline (CicPp.ppobj obj) ;
+          debug_print "Offending mutual (co)inductive type declaration:" ;
+          debug_print (CicPp.ppobj obj) ;
       end ;
       (* We already know that obj is well-typed. We need to add it to the  *)
       (* environment in order to compute the inner-types without having to *)
@@ -1477,7 +1447,7 @@ let new_inductive () =
    with
     e ->
      output_html outputhtml
-      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+      (`Error (`T (Printexc.to_string e)))
 ;;
 
 let new_proof () =
@@ -1528,22 +1498,17 @@ let new_proof () =
    ~packing:(hbox#pack ~expand:false ~fill:false ~padding:5) () in
  (* moved here to have visibility of the ok button *)
  let newinputt =
-  TexTermEditor'.term_editor
+  TermEditor'.term_editor
    mqi_handle
    ~width:400 ~height:100 ~packing:scrolled_window#add
-   ~share_id_to_uris_with:inputt ()
+   ~share_environment_with:inputt ()
    ~isnotempty_callback:
     (function b ->
       non_empty_type := b ;
       okb#misc#set_sensitive (b && uri_entry#text <> ""))
  in
  let _ =
-let xxx = inputt#get_as_string in
-prerr_endline ("######################## " ^ xxx) ;
-  newinputt#set_term xxx ;
-(*
-  newinputt#set_term inputt#get_as_string ;
-*)
+  newinputt#set_term inputt#get_as_string  ;
   inputt#reset in
  let _ =
   uri_entry#connect#changed
@@ -1576,7 +1541,7 @@ prerr_endline ("######################## " ^ xxx) ;
       with
        e ->
         output_html outputhtml
-         ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+         (`Error (`T (Printexc.to_string e)))
   )) ;
  window#show () ;
  GtkThread.main ();
@@ -1597,15 +1562,15 @@ prerr_endline ("######################## " ^ xxx) ;
   with
      InvokeTactics.RefreshSequentException e ->
       output_html outputhtml
-       ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-        "sequent: " ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T ("Exception raised during the refresh of the " ^
+        "sequent: " ^ Printexc.to_string e)))
    | InvokeTactics.RefreshProofException e ->
       output_html outputhtml
-       ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-        "proof: " ^ Printexc.to_string e ^ "</h1>")
+       (`Error (`T ("Exception raised during the refresh of the " ^
+        "proof: " ^ Printexc.to_string e)))
    | e ->
       output_html outputhtml
-       ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+       (`Error (`T (Printexc.to_string e)))
 ;;
 
 let check_term_in_scratch scratch_window metasenv context expr = 
@@ -1646,7 +1611,7 @@ let check scratch_window () =
    with
     e ->
      output_html outputhtml
-      ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+      (`Error (`T (Printexc.to_string e)))
 ;;
 
 let show () =
@@ -1656,7 +1621,7 @@ let show () =
   with
    e ->
     output_html outputhtml
-     ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+     (`Error (`T (Printexc.to_string e)))
 ;;
 
 exception NotADefinition;;
@@ -1684,15 +1649,15 @@ let open_ () =
    with
       InvokeTactics.RefreshSequentException e ->
        output_html outputhtml
-        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-         "sequent: " ^ Printexc.to_string e ^ "</h1>")
+        (`Error (`T ("Exception raised during the refresh of the " ^
+         "sequent: " ^ Printexc.to_string e)))
     | InvokeTactics.RefreshProofException e ->
        output_html outputhtml
-        ("<h1 color=\"red\">Exception raised during the refresh of the " ^
-         "proof: " ^ Printexc.to_string e ^ "</h1>")
+        (`Error (`T ("Exception raised during the refresh of the " ^
+         "proof: " ^ Printexc.to_string e)))
     | e ->
        output_html outputhtml
-        ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+        (`Error (`T (Printexc.to_string e)))
 ;;
 
 let show_query_results results =
@@ -1946,7 +1911,7 @@ let completeSearchPattern () =
   with
    e ->
     output_html outputhtml
-     ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+     (`Error (`T (Printexc.to_string e)))
 ;;
 
 let insertQuery () =
@@ -2014,7 +1979,7 @@ let insertQuery () =
   with
    e ->
     output_html outputhtml
-     ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>") ;
+     (`Error (`T (Printexc.to_string e)))
 ;;
 
 let choose_must list_of_must only =
@@ -2157,8 +2122,8 @@ let searchPattern () =
          let uris' =
            TacticChaser.matchConclusion
            mqi_handle
-            ~output_html:(output_html outputhtml) ~choose_must ()
-            ~status:(proof, metano)
+            ~output_html:(fun m -> output_html outputhtml (`Msg (`T m)))
+            ~choose_must () ~status:(proof, metano)
          in
          let uri' =
           user_uri_choice ~title:"Ambiguous input."
@@ -2170,12 +2135,11 @@ let searchPattern () =
   with
    e -> 
     output_html outputhtml 
-     ("<h1 color=\"red\">" ^ Printexc.to_string e ^ "</h1>")
+     (`Error (`T (Printexc.to_string e)))
 ;;
       
 let choose_selection mmlwidget (element : Gdome.element option) =
  let module G = Gdome in
- prerr_endline "Il bandolo" ;
   let rec aux element =
    if element#hasAttributeNS
        ~namespaceURI:Misc.helmns
@@ -2192,7 +2156,7 @@ let choose_selection mmlwidget (element : Gdome.element option) =
        | Some p -> aux (new Gdome.element_of_node p)
     with
        GdomeInit.DOMCastException _ ->
-        prerr_endline
+        debug_print
          "******* trying to select above the document root ********"
   in
    match element with
@@ -2669,7 +2633,7 @@ object(self)
           Lazy.force (page#compute) ;
           Lazy.force setgoal;
           if notify_hbugs_on_goal_change then
-            (*Hbugs.notify *) ()
+            Hbugs.notify ()
         with _ -> ()
     ))
 end
@@ -2678,42 +2642,30 @@ end
 let dump_environment () =
   try
     let oc = open_out environmentfile in
-    output_html (outputhtml ()) "<b>Dumping environment ... </b><br />";
+    output_html (outputhtml ()) (`Msg (`T "Dumping environment ..."));
     CicEnvironment.dump_to_channel
-      ~callback:(fun uri -> output_html (outputhtml ()) (uri ^ "<br />"))
+      ~callback:(fun uri -> output_html (outputhtml ()) (`Msg (`T uri)))
       oc;
-    output_html (outputhtml ()) "<b>... done!</b><br />";
+    output_html (outputhtml ()) (`Msg (`T "... done!")) ;
     close_out oc
   with exc ->
     output_html (outputhtml ())
-      (Printf.sprintf
-        "<h1 color=\"red\">Dump failure, uncaught exception:%s</h1>"
-        (Printexc.to_string exc))
+      (`Error (`T (Printf.sprintf "Dump failure, uncaught exception:%s"
+        (Printexc.to_string exc))))
 ;;
 let restore_environment () =
   try
     let ic = open_in environmentfile in
-    output_html (outputhtml ()) "<b>Restoring environment ... </b><br />";
+    output_html (outputhtml ()) (`Msg (`T "Restoring environment ... "));
     CicEnvironment.restore_from_channel
-      ~callback:(fun uri -> output_html (outputhtml ()) (uri ^ "<br />"))
+      ~callback:(fun uri -> output_html (outputhtml ()) (`Msg (`T uri)))
       ic;
-    output_html (outputhtml ()) "<b>... done!</b><br />";
+    output_html (outputhtml ()) (`Msg (`T "... done!"));
     close_in ic
   with exc ->
     output_html (outputhtml ())
-      (Printf.sprintf
-        "<h1 color=\"red\">Restore failure, uncaught exception:%s</h1>"
-        (Printexc.to_string exc))
-;;
-
-(* HTML simulator (first in its kind) *)
-
-class fake_xmhtml ~source ~width ~height ~border_width ~packing ~show () =
- let tv = GText.view ~width ~height ~border_width ~packing ~show () in
-  object
-   method set_topline (_:int) = ()
-   method source s = tv#buffer#insert s
-  end
+      (`Error (`T (Printf.sprintf "Restore failure, uncaught exception:%s"
+        (Printexc.to_string exc))))
 ;;
 
 (* Main window *)
@@ -2827,18 +2779,18 @@ class rendering_window output (notebook : notebook) =
  let factory6 = new GMenu.factory hbugs_menu ~accel_group in
  let _ =
   factory6#add_check_item
-    ~active:false ~key:GdkKeysyms._F5 ~callback:(*Hbugs.toggle*)(fun _ -> ()) "HBugs enabled"
+    ~active:false ~key:GdkKeysyms._F5 ~callback:Hbugs.toggle "HBugs enabled"
  in
  let _ =
-  factory6#add_item ~key:GdkKeysyms._Return ~callback:(*Hbugs.notify*)(fun _ -> ())
+  factory6#add_item ~key:GdkKeysyms._Return ~callback:Hbugs.notify
    "(Re)Submit status!"
  in
  let _ = factory6#add_separator () in
  let _ =
-  factory6#add_item ~callback:(*Hbugs.start_web_services*)(fun _ -> ()) "Start Web Services"
+  factory6#add_item ~callback:Hbugs.start_web_services "Start Web Services"
  in
  let _ =
-  factory6#add_item ~callback:(*Hbugs.stop_web_services*)(fun _ -> ()) "Stop Web Services"
+  factory6#add_item ~callback:Hbugs.stop_web_services "Stop Web Services"
  in
  (* settings menu *)
  let settings_menu = factory0#add_submenu "Settings" in
@@ -2846,6 +2798,12 @@ class rendering_window output (notebook : notebook) =
  let _ =
   factory3#add_item "Edit Aliases..." ~key:GdkKeysyms._A
    ~callback:edit_aliases in
+ let _ =
+  factory3#add_item "Clear Aliases" ~key:GdkKeysyms._K
+   ~callback:clear_aliases in
+ let autoitem =
+  factory3#add_check_item "Auto disambiguation"
+   ~callback:(fun checked -> auto_disambiguation := checked) in
  let _ = factory3#add_separator () in
  let _ =
   factory3#add_item "MathML Widget Preferences..." ~key:GdkKeysyms._P
@@ -2855,7 +2813,7 @@ class rendering_window output (notebook : notebook) =
   factory3#add_item "Reload Stylesheets"
    ~callback:
      (function _ ->
-       ApplyStylesheets.reload_stylesheets () ;
+       ChosenTransformer.reload_stylesheets () ;
        if ProofEngine.get_proof () <> None then
         try
          refresh_goals notebook ;
@@ -2863,13 +2821,13 @@ class rendering_window output (notebook : notebook) =
         with
            InvokeTactics.RefreshSequentException e ->
             output_html (outputhtml ())
-             ("<h1 color=\"red\">An error occurred while refreshing the " ^
-               "sequent: " ^ Printexc.to_string e ^ "</h1>") ;
+             (`Error (`T ("An error occurred while refreshing the " ^
+               "sequent: " ^ Printexc.to_string e))) ;
            (*notebook#remove_all_pages ~skip_switch_page_event:false ;*)
            notebook#set_empty_page
          | InvokeTactics.RefreshProofException e ->
             output_html (outputhtml ())
-             ("<h1 color=\"red\">An error occurred while refreshing the proof: "               ^ Printexc.to_string e ^ "</h1>") ;
+             (`Error (`T ("An error occurred while refreshing the proof: "               ^ Printexc.to_string e))) ;
             output#unload
      ) in
  (* accel group *)
@@ -2891,7 +2849,7 @@ class rendering_window output (notebook : notebook) =
   GBin.scrolled_window ~border_width:5
    ~packing:frame#add () in
  let inputt =
-  TexTermEditor'.term_editor
+  TermEditor'.term_editor
    mqi_handle
    ~width:400 ~height:100 ~packing:scrolled_window1#add ()
    ~isnotempty_callback:
@@ -2906,15 +2864,9 @@ class rendering_window output (notebook : notebook) =
   GBin.frame ~shadow_type:`IN ~packing:(vboxl#pack ~expand:true ~padding:5) ()
  in
  let outputhtml =
-  new fake_xmhtml
-  (*
-  GHtml.xmhtml
-  *)
-   ~source:"<html><body bgColor=\"white\"></body></html>"
-   ~width:400 ~height: 100
-   ~border_width:20
-   ~packing:frame#add
-   ~show:true () in
+   new Ui_logger.html_logger
+    ~width:400 ~height: 100 ~show:true ~packing:frame#add ()
+ in
 object
  method outputhtml = outputhtml
  method inputt = inputt
@@ -2922,6 +2874,7 @@ object
  method scratch_window = scratch_window
  method notebook = notebook
  method show = window#show
+ method set_auto_disambiguation set = autoitem#set_active set
  initializer
   notebook#set_empty_page ;
   (*export_to_postscript_menu_item#misc#set_sensitive false ;*)
@@ -2939,9 +2892,8 @@ object
   set_settings_window settings_window ;
   set_outputhtml outputhtml ;
   ignore(window#event#connect#delete (fun _ -> GMain.Main.quit () ; true )) ;
-  Logger.log_callback :=
-   (Logger.log_to_html ~print_and_flush:(output_html outputhtml))
-end;;
+  CicLogger.log_callback := (outputhtml#log_cic_msg ~append_NL:true)
+end
 
 (* MAIN *)
 
@@ -2950,10 +2902,10 @@ let initialize_everything () =
   let output = TermViewer.proof_viewer ~width:350 ~height:280 () in
   let notebook = new notebook in
    let rendering_window' = new rendering_window output notebook in
+    rendering_window'#set_auto_disambiguation !auto_disambiguation;
     set_rendering_window rendering_window' ;
     let print_error_as_html prefix msg =
-     output_html (outputhtml ())
-      ("<h1 color=\"red\">" ^ prefix ^ msg ^ "</h1>")
+     output_html (outputhtml ()) (`Error (`T (prefix ^ msg)))
     in
      Gdome_xslt.setErrorCallback (Some (print_error_as_html "XSLT Error: "));
      Gdome_xslt.setDebugCallback
@@ -2967,8 +2919,8 @@ let initialize_everything () =
 let main () =
  ignore (GtkMain.Main.init ()) ;
  initialize_everything () ;
- MQIC.close mqi_handle(*;
- Hbugs.quit ()*)
+ MQIC.close mqi_handle;
+ Hbugs.quit ()
 ;;
 
 try