src/Pure/proof_general.ML
author aspinall
Wed Aug 18 16:25:27 2004 +0200 (2004-08-18)
changeset 15145 07360eef9f4f
parent 15134 d3fa5e1d6e4d
child 15146 eab7de0d0a31
permissions -rw-r--r--
Version for PGIP 2.X, with greatly improved parsing and XML handling.
wenzelm@12780
     1
(*  Title:      Pure/proof_general.ML
wenzelm@12778
     2
    ID:         $Id$
wenzelm@14675
     3
    Author:     David Aspinall and Markus Wenzel
wenzelm@12778
     4
aspinall@15134
     5
Isabelle configuration for Proof General (see http://proofgeneral.inf.ed.ac.uk)
aspinall@15134
     6
Includes support for PGIP control language for Isabelle/Isar.
aspinall@15134
     7
aspinall@15134
     8
===========================================================================
aspinall@15134
     9
NOTE: With this version you will lose support for the Isabelle
aspinall@15134
    10
preferences menu in the currently released version of Proof General (3.5).
aspinall@15134
    11
No other changes should be visible in the Emacs interface.
aspinall@15134
    12
aspinall@15134
    13
If the loss of preferences is a serious problem, please use a "sticky"
aspinall@15134
    14
check-out of the previous version of this file, version 1.27.
aspinall@15134
    15
aspinall@15145
    16
A version of Emacs Proof General which supports the new PGIP format for
aspinall@15134
    17
preferences will be available shortly.  
aspinall@15134
    18
===========================================================================
aspinall@15134
    19
aspinall@15145
    20
STATUS: this version is an experimental version that supports PGIP 2.X.
aspinall@15134
    21
wenzelm@12778
    22
*)
wenzelm@12778
    23
wenzelm@12778
    24
signature PROOF_GENERAL =
wenzelm@12778
    25
sig
wenzelm@12778
    26
  val setup: (theory -> theory) list
wenzelm@12778
    27
  val update_thy_only: string -> unit
wenzelm@12778
    28
  val try_update_thy_only: string -> unit
wenzelm@13391
    29
  val inform_file_retracted: string -> unit
wenzelm@12778
    30
  val inform_file_processed: string -> unit
aspinall@15134
    31
  val preferences: 
aspinall@15134
    32
      (string * 
aspinall@15134
    33
	(string * 
aspinall@15134
    34
	 (string * 
aspinall@15134
    35
	  (string * (string * (unit -> string)) * 
aspinall@15134
    36
	   (string -> unit)))) list) list ref
berghofe@13728
    37
  val process_pgip: string -> unit
wenzelm@12778
    38
  val thms_containing: string list -> unit
wenzelm@12778
    39
  val help: unit -> unit
wenzelm@12778
    40
  val show_context: unit -> theory
wenzelm@12778
    41
  val kill_goal: unit -> unit
wenzelm@12778
    42
  val repeat_undo: int -> unit
wenzelm@12778
    43
  val isa_restart: unit -> unit
wenzelm@12833
    44
  val full_proofs: bool -> unit
aspinall@15134
    45
  val isarcmd: string -> unit
wenzelm@12778
    46
  val init: bool -> unit
aspinall@15134
    47
  val init_pgip: bool -> unit
wenzelm@12778
    48
  val write_keywords: string -> unit
wenzelm@12778
    49
end;
wenzelm@12778
    50
aspinall@15134
    51
structure ProofGeneral : PROOF_GENERAL =
wenzelm@12778
    52
struct
wenzelm@12778
    53
aspinall@15145
    54
structure P = OuterParse
aspinall@15145
    55
aspinall@15134
    56
(* PGIP messaging mode (independent of PGML output) *)
aspinall@15134
    57
aspinall@15134
    58
val pgip_active = ref false;
aspinall@15134
    59
val pgip_emacs_compatibility_flag = ref false;
aspinall@15134
    60
aspinall@15134
    61
fun pgip () = (!pgip_active);
aspinall@15134
    62
fun pgip_emacs_compatibility () = (!pgip_emacs_compatibility_flag);
aspinall@15134
    63
aspinall@15134
    64
wenzelm@12778
    65
(* print modes *)
wenzelm@12778
    66
aspinall@15134
    67
val proof_generalN = "ProofGeneral"; (* token markup (colouring vars, etc.) *)
aspinall@15134
    68
val xsymbolsN = Symbol.xsymbolsN;    (* XSymbols symbols *)
aspinall@15134
    69
val pgmlN = "PGML";		     (* XML escapes and PGML symbol elements *)
aspinall@15134
    70
val pgmlatomsN = "PGMLatoms";	     (* variable kind decorations *)
aspinall@15134
    71
val thm_depsN = "thm_deps";	     (* meta-information about theorem deps *)
wenzelm@12778
    72
wenzelm@12778
    73
fun pgml () = pgmlN mem_string ! print_mode;
wenzelm@12778
    74
aspinall@15134
    75
(* text output: print modes for xsymbol and PGML *)
wenzelm@12778
    76
wenzelm@12778
    77
local
wenzelm@12778
    78
wenzelm@14827
    79
fun xsym_output "\\" = "\\\\"
wenzelm@14827
    80
  | xsym_output s = if Symbol.is_raw s then Symbol.decode_raw s else s;
wenzelm@14827
    81
wenzelm@12778
    82
fun xsymbols_output s =
aspinall@15134
    83
  if xsymbolsN mem_string ! print_mode andalso exists_string (equal "\\") s then
wenzelm@12778
    84
    let val syms = Symbol.explode s
wenzelm@14827
    85
    in (implode (map xsym_output syms), real (Symbol.length syms)) end
aspinall@15134
    86
  else Symbol.default_output s;
aspinall@15134
    87
aspinall@15134
    88
fun pgml_sym s =
aspinall@15134
    89
  (case Symbol.decode s of
aspinall@15134
    90
    Symbol.Char "\\" => "\\\\"
aspinall@15134
    91
  | Symbol.Char s => XML.text s
aspinall@15134
    92
  | Symbol.Sym s => XML.element "sym" [("name", s)] []
aspinall@15134
    93
  | Symbol.Ctrl s => XML.element "ctrl" [("name", s)] []
aspinall@15134
    94
  | Symbol.Raw s => s);
wenzelm@12778
    95
aspinall@15134
    96
fun pgml_output str =
aspinall@15134
    97
  let val syms = Symbol.explode str
aspinall@15134
    98
  in (implode (map pgml_sym syms), real (Symbol.length syms)) end;
aspinall@15134
    99
aspinall@15134
   100
in 
wenzelm@12778
   101
aspinall@15134
   102
fun setup_xsymbols_output () = 
aspinall@15134
   103
    Output.add_mode 
aspinall@15134
   104
	xsymbolsN 
aspinall@15134
   105
	(xsymbols_output, Symbol.default_indent, Symbol.encode_raw);
wenzelm@12778
   106
aspinall@15134
   107
fun setup_pgml_output () = 
aspinall@15134
   108
    Output.add_mode 
aspinall@15134
   109
	pgmlN
aspinall@15134
   110
	(pgml_output, Symbol.default_indent, Symbol.encode_raw);
wenzelm@12778
   111
wenzelm@12778
   112
end;
wenzelm@12778
   113
wenzelm@12778
   114
wenzelm@12778
   115
(* token translations *)
wenzelm@12778
   116
wenzelm@12778
   117
local
wenzelm@12778
   118
wenzelm@12778
   119
val end_tag = oct_char "350";
wenzelm@12778
   120
val class_tag = ("class", oct_char "351");
wenzelm@12778
   121
val tfree_tag = ("tfree", oct_char "352");
wenzelm@12778
   122
val tvar_tag = ("tvar", oct_char "353");
wenzelm@12778
   123
val free_tag = ("free", oct_char "354");
wenzelm@12778
   124
val bound_tag = ("bound", oct_char "355");
wenzelm@12778
   125
val var_tag = ("var", oct_char "356");
wenzelm@12778
   126
val skolem_tag = ("skolem", oct_char "357");
wenzelm@12778
   127
wenzelm@12778
   128
fun xml_atom kind x = XML.element "atom" [("kind", kind)] [XML.text x];
wenzelm@12778
   129
wenzelm@12778
   130
fun tagit (kind, bg_tag) x =
aspinall@15134
   131
    (if Output.has_mode pgmlatomsN then 
aspinall@15134
   132
	 xml_atom kind x
aspinall@15134
   133
     else bg_tag ^ x ^ end_tag, 
aspinall@15134
   134
     real (Symbol.length (Symbol.explode x)));
wenzelm@12778
   135
wenzelm@12778
   136
fun free_or_skolem x =
wenzelm@12778
   137
  (case try Syntax.dest_skolem x of
wenzelm@12778
   138
    None => tagit free_tag x
wenzelm@12778
   139
  | Some x' => tagit skolem_tag x');
wenzelm@12778
   140
wenzelm@12778
   141
fun var_or_skolem s =
wenzelm@12778
   142
  (case Syntax.read_var s of
wenzelm@12778
   143
    Var ((x, i), _) =>
wenzelm@12778
   144
      (case try Syntax.dest_skolem x of
wenzelm@12778
   145
        None => tagit var_tag s
wenzelm@12778
   146
      | Some x' => tagit skolem_tag (Syntax.string_of_vname (x', i)))
wenzelm@12778
   147
  | _ => tagit var_tag s);
wenzelm@12778
   148
wenzelm@12778
   149
val proof_general_trans =
wenzelm@12778
   150
 Syntax.tokentrans_mode proof_generalN
wenzelm@12778
   151
  [("class", tagit class_tag),
wenzelm@12778
   152
   ("tfree", tagit tfree_tag),
wenzelm@12778
   153
   ("tvar", tagit tvar_tag),
wenzelm@12778
   154
   ("free", free_or_skolem),
wenzelm@12778
   155
   ("bound", tagit bound_tag),
wenzelm@12778
   156
   ("var", var_or_skolem)];
wenzelm@12778
   157
wenzelm@12778
   158
in val setup = [Theory.add_tokentrfuns proof_general_trans] end;
wenzelm@12778
   159
wenzelm@12778
   160
aspinall@15134
   161
(* assembling PGIP packets *)
aspinall@15134
   162
aspinall@15134
   163
val pgip_refseq = ref None : string option ref
aspinall@15134
   164
val pgip_refid = ref None : string option ref
wenzelm@12778
   165
wenzelm@12778
   166
local
aspinall@15134
   167
    val myseq_no = ref 1;      (* PGIP packet counter *)
wenzelm@12778
   168
aspinall@15134
   169
    val pgip_class  = "pg"
aspinall@15134
   170
    val pgip_origin = "Isabelle/Isar"
aspinall@15134
   171
    val pgip_id = (getenv "HOSTNAME") ^ "/" ^ (getenv "USER") ^ "/" ^ 
aspinall@15134
   172
		   (Time.toString(Time.now()))
aspinall@15134
   173
	          (* FIXME: PPID is empty for me: any way to get process ID? *)
wenzelm@12778
   174
aspinall@15134
   175
    fun assemble_pgips pgips = 
aspinall@15134
   176
	XML.element 
aspinall@15134
   177
	     "pgip" 
aspinall@15134
   178
	     ([("class",  pgip_class),
aspinall@15134
   179
	       ("origin", pgip_origin),
aspinall@15134
   180
	       ("id",     pgip_id)] @
aspinall@15134
   181
	      (if_none (apsome (single o (pair "refseq")) (!pgip_refseq)) []) @
aspinall@15134
   182
	      (if_none (apsome (single o (pair "refid")) (!pgip_refid)) []) @
aspinall@15134
   183
	      [("seq",  string_of_int (Library.inc myseq_no))])
aspinall@15134
   184
	     pgips
wenzelm@13526
   185
in
wenzelm@12778
   186
aspinall@15134
   187
 fun decorated_output bg en prfx = 
aspinall@15134
   188
    writeln_default o enclose bg en o prefix_lines prfx;
aspinall@15134
   189
aspinall@15134
   190
 (* FIXME: see Rev 1.48 [PG CVS] for cleaner version of this which can be used
aspinall@15134
   191
    for PG 4.0 which processes PGIP without needing special chars. *)
aspinall@15134
   192
 fun issue_pgips ps = 
aspinall@15134
   193
     if pgip_emacs_compatibility() then
aspinall@15134
   194
	 decorated_output (* add urgent message annotation *)
aspinall@15134
   195
	     (oct_char "360") (oct_char "361") "" 
aspinall@15134
   196
	     (assemble_pgips ps)
aspinall@15134
   197
     else 
aspinall@15134
   198
	 writeln_default (assemble_pgips ps)
aspinall@15134
   199
aspinall@15134
   200
 fun assemble_pgip resp attrs s = assemble_pgips [XML.element resp attrs [s]]
aspinall@15134
   201
				  
aspinall@15134
   202
 fun assemble_pgipe resp attrs = assemble_pgips [XML.element resp attrs []]
aspinall@15134
   203
aspinall@15145
   204
 (* FIXME: need to add stuff to gather PGIPs here *)
aspinall@15134
   205
 fun issue_pgip resp attrs = writeln_default o (assemble_pgip resp attrs)
aspinall@15134
   206
aspinall@15134
   207
(*  FIXME: temporarily to support PG 3.4.  *)
aspinall@15134
   208
 fun issue_pgip_maybe_decorated bg en resp attrs s = 
aspinall@15134
   209
     if pgip_emacs_compatibility() then
aspinall@15134
   210
      (*  in PGIP mode, but using escape characters as well.  *)
aspinall@15134
   211
	writeln_default (enclose bg en (assemble_pgip resp attrs s))
aspinall@15134
   212
     else 
aspinall@15134
   213
	issue_pgip resp attrs s
aspinall@15134
   214
	
aspinall@15134
   215
 fun issue_pgipe resp attrs = writeln_default (assemble_pgipe resp attrs)
aspinall@15134
   216
aspinall@15134
   217
end
aspinall@15134
   218
aspinall@15134
   219
(* messages and notification *)
aspinall@15134
   220
aspinall@15134
   221
fun message resp attrs bg en prfx s =
aspinall@15134
   222
  if pgip() then 
aspinall@15134
   223
      issue_pgip_maybe_decorated bg en resp attrs (prefix_lines prfx s)
aspinall@15134
   224
  else 
aspinall@15134
   225
      decorated_output bg en prfx s;
aspinall@15134
   226
aspinall@15134
   227
aspinall@15134
   228
local
aspinall@15134
   229
    val display_area = ("area", "display")
aspinall@15134
   230
    val message_area = ("area", "message")
aspinall@15134
   231
    val tracing_category = ("category", "tracing")
aspinall@15134
   232
    val urgent_indication = ("urgent", "y")
aspinall@15134
   233
    val nonfatal = ("fatality", "nonfatal")
aspinall@15134
   234
    val fatal = ("fatality", "fatal")
aspinall@15134
   235
    val panic = ("fatality", "panic")
aspinall@15134
   236
aspinall@15134
   237
    val thyname_attr = pair "thyname"
aspinall@15134
   238
    val url_attr = pair "url"
aspinall@15134
   239
    fun localfile_url_attr path = url_attr ("file:///" ^ path)
aspinall@15134
   240
in			   
wenzelm@12778
   241
wenzelm@12778
   242
fun setup_messages () =
aspinall@15134
   243
 (writeln_fn  := message "normalresponse" [message_area] "" "" "";
aspinall@15134
   244
aspinall@15134
   245
  priority_fn := message "normalresponse" [message_area, urgent_indication]
aspinall@15134
   246
			 (oct_char "360") (oct_char "361") "";
aspinall@15134
   247
aspinall@15134
   248
  tracing_fn := message "normalresponse"  [message_area, tracing_category]
aspinall@15134
   249
			(oct_char "360" ^ oct_char "375") (oct_char "361") "";
aspinall@15134
   250
aspinall@15134
   251
  warning_fn := message "errorresponse"    [nonfatal]
aspinall@15134
   252
			(oct_char "362") (oct_char "363") "### ";
aspinall@15134
   253
aspinall@15134
   254
  error_fn := message "errorresponse" [fatal]
aspinall@15134
   255
		      (oct_char "364") (oct_char "365") "*** ";
aspinall@15134
   256
aspinall@15134
   257
  panic_fn := message "errorresponse" [panic]
aspinall@15134
   258
		      (oct_char "364") (oct_char "365") "!!! ")
aspinall@15134
   259
aspinall@15134
   260
aspinall@15134
   261
(* accumulate printed output in a single PGIP response *)
aspinall@15134
   262
aspinall@15134
   263
fun with_displaywrap (elt,attrs) dispfn =
aspinall@15134
   264
    let 
aspinall@15134
   265
	val lines = ref ([] : string list);
aspinall@15134
   266
	fun wlgrablines s = (lines:= (s :: (!lines)))
aspinall@15134
   267
    in 
aspinall@15134
   268
	(setmp writeln_fn wlgrablines dispfn ();
aspinall@15134
   269
	 (* FIXME: cat_lines here inefficient, should use stream output *)
aspinall@15134
   270
         issue_pgip elt attrs (cat_lines (!lines)))
aspinall@15134
   271
    end
wenzelm@12778
   272
aspinall@15134
   273
val emacs_notify = decorated_output (oct_char "360") (oct_char "361") "";
aspinall@15134
   274
    
aspinall@15134
   275
fun tell_clear_goals () = 
aspinall@15134
   276
    if pgip() then
aspinall@15134
   277
	issue_pgipe "cleardisplay" [display_area]
aspinall@15134
   278
    else 
aspinall@15134
   279
	emacs_notify "Proof General, please clear the goals buffer.";
aspinall@15134
   280
aspinall@15134
   281
fun tell_clear_response () = 
aspinall@15134
   282
    if pgip() then
aspinall@15134
   283
	issue_pgipe "cleardisplay" [message_area]
aspinall@15134
   284
    else 
aspinall@15134
   285
	emacs_notify "Proof General, please clear the response buffer.";
wenzelm@12778
   286
aspinall@15134
   287
fun tell_file_loaded path = 
aspinall@15134
   288
    if pgip() then
aspinall@15134
   289
	issue_pgipe "informtheoryloaded"  (* FIXME: get thy name from info here? *)
aspinall@15134
   290
		    [thyname_attr        (XML.text (File.sysify_path path)),
aspinall@15134
   291
		     localfile_url_attr  (XML.text (File.sysify_path path))]
aspinall@15134
   292
    else 
aspinall@15134
   293
	emacs_notify ("Proof General, this file is loaded: " 
aspinall@15134
   294
		      ^ quote (File.sysify_path path));
aspinall@15134
   295
aspinall@15134
   296
fun tell_file_retracted path = 
aspinall@15134
   297
    if pgip() then
aspinall@15134
   298
	issue_pgipe "informtheoryretracted"  (* FIXME: get thy name from info here? *)
aspinall@15134
   299
		    [thyname_attr        (XML.text (File.sysify_path path)),
aspinall@15134
   300
		     localfile_url_attr  (XML.text (File.sysify_path path))]
aspinall@15134
   301
    else 
aspinall@15134
   302
	emacs_notify ("Proof General, you can unlock the file " 
aspinall@15134
   303
		      ^ quote (File.sysify_path path));
wenzelm@12778
   304
wenzelm@12778
   305
wenzelm@12778
   306
(* theory / proof state output *)
wenzelm@12778
   307
wenzelm@12778
   308
local
wenzelm@12778
   309
aspinall@15134
   310
    fun tmp_markers f =	setmp Display.current_goals_markers 
aspinall@15134
   311
			      (oct_char "366", oct_char "367", "") f ()
wenzelm@12778
   312
aspinall@15134
   313
    fun statedisplay prts =
aspinall@15134
   314
	issue_pgip "proofstate" []
aspinall@15134
   315
		   (XML.element "pgml" []
aspinall@15134
   316
				[XML.element "statedisplay" 
aspinall@15134
   317
					     [] 
aspinall@15134
   318
					     [Output.output (* FIXME: needed? *)
aspinall@15134
   319
						  (Pretty.output
aspinall@15134
   320
						       (Pretty.chunks prts))]])
wenzelm@13545
   321
aspinall@15134
   322
    fun print_current_goals n m st =
aspinall@15134
   323
	if pgml () then statedisplay (Display.pretty_current_goals n m st)
aspinall@15134
   324
	else tmp_markers (fn () => Display.print_current_goals_default n m st)
aspinall@15134
   325
	     
aspinall@15134
   326
    fun print_state b st =
aspinall@15134
   327
	if pgml () then statedisplay (Toplevel.pretty_state b st)
aspinall@15134
   328
	else tmp_markers (fn () => Toplevel.print_state_default b st)
wenzelm@13526
   329
in
wenzelm@13526
   330
aspinall@15134
   331
 fun setup_state () =
aspinall@15134
   332
     (Display.print_current_goals_fn := print_current_goals;
aspinall@15134
   333
      Toplevel.print_state_fn := print_state;
aspinall@15134
   334
      (* FIXME: check next octal char won't appear in pgip? *)
aspinall@15134
   335
      Toplevel.prompt_state_fn := (suffix (oct_char "372") o  
aspinall@15134
   336
				   Toplevel.prompt_state_default));
aspinall@15134
   337
end
berghofe@13728
   338
aspinall@15134
   339
end
berghofe@13728
   340
wenzelm@12778
   341
(* misc commands for ProofGeneral/isa *)
wenzelm@12778
   342
wenzelm@12778
   343
fun thms_containing ss =
wenzelm@13284
   344
  ProofContext.print_thms_containing (ProofContext.init (the_context ())) None ss;
wenzelm@12778
   345
wenzelm@12778
   346
val welcome = priority o Session.welcome;
wenzelm@12778
   347
val help = welcome;
wenzelm@12778
   348
val show_context = Context.the_context;
wenzelm@12778
   349
wenzelm@12778
   350
fun kill_goal () = (Goals.reset_goals (); tell_clear_goals ());
wenzelm@12778
   351
wenzelm@12778
   352
fun no_print_goals f = setmp Display.print_current_goals_fn (fn _ => fn _ => fn _ => ()) f;
wenzelm@12778
   353
wenzelm@12778
   354
fun repeat_undo 0 = ()
wenzelm@12778
   355
  | repeat_undo 1 = undo ()
wenzelm@12778
   356
  | repeat_undo n = (no_print_goals undo (); repeat_undo (n - 1));
wenzelm@12778
   357
wenzelm@12778
   358
aspinall@15134
   359
(* theory loader actions *)
aspinall@15134
   360
aspinall@15134
   361
local
aspinall@15134
   362
aspinall@15134
   363
fun add_master_files name files =
aspinall@15134
   364
  let val masters = [ThyLoad.thy_path name, ThyLoad.ml_path name]
aspinall@15134
   365
  in masters @ gen_rems (op = o pairself Path.base) (files, masters) end;
aspinall@15134
   366
aspinall@15134
   367
fun trace_action action name =
aspinall@15134
   368
  if action = ThyInfo.Update then
aspinall@15134
   369
    seq tell_file_loaded (ThyInfo.loaded_files name)
aspinall@15134
   370
  else if action = ThyInfo.Outdate orelse action = ThyInfo.Remove then
aspinall@15134
   371
    seq tell_file_retracted (add_master_files name (ThyInfo.loaded_files name))
aspinall@15134
   372
  else ();
aspinall@15134
   373
aspinall@15134
   374
in
aspinall@15134
   375
  fun setup_thy_loader () = ThyInfo.add_hook trace_action;
aspinall@15134
   376
  fun sync_thy_loader () = seq (trace_action ThyInfo.Update) (ThyInfo.names ());
aspinall@15134
   377
end;
aspinall@15134
   378
aspinall@15134
   379
aspinall@15134
   380
(* prepare theory context *)
aspinall@15134
   381
aspinall@15134
   382
val thy_name = Path.pack o #1 o Path.split_ext o Path.base o Path.unpack;
aspinall@15134
   383
val update_thy_only = setmp MetaSimplifier.trace_simp 
aspinall@15134
   384
			    false ThyInfo.update_thy_only;
aspinall@15134
   385
aspinall@15134
   386
fun which_context () =
aspinall@15134
   387
  (case Context.get_context () of
aspinall@15134
   388
    Some thy => "  Using current (dynamic!) one: " ^
aspinall@15134
   389
      (case try PureThy.get_name thy of Some name => quote name | None => "<unnamed>")
aspinall@15134
   390
  | None => "");
aspinall@15134
   391
aspinall@15134
   392
fun try_update_thy_only file =
aspinall@15134
   393
  ThyLoad.cond_add_path (Path.dir (Path.unpack file)) (fn () =>
aspinall@15134
   394
    let val name = thy_name file in
aspinall@15134
   395
      if is_some (ThyLoad.check_file (ThyLoad.thy_path name)) 
aspinall@15134
   396
      then update_thy_only name
aspinall@15134
   397
      else warning ("Unkown theory context of ML file." ^ which_context ())
aspinall@15134
   398
    end) ();
aspinall@15134
   399
aspinall@15134
   400
aspinall@15134
   401
(* get informed about files *)
aspinall@15134
   402
aspinall@15134
   403
val inform_file_retracted = 
aspinall@15134
   404
    ThyInfo.if_known_thy ThyInfo.remove_thy o thy_name;
aspinall@15134
   405
val inform_file_processed = 
aspinall@15134
   406
    ThyInfo.if_known_thy ThyInfo.touch_child_thys o thy_name;
aspinall@15134
   407
aspinall@15134
   408
fun proper_inform_file_processed file state =
aspinall@15134
   409
  let val name = thy_name file in
aspinall@15134
   410
    if Toplevel.is_toplevel state andalso ThyInfo.known_thy name then
aspinall@15134
   411
     (ThyInfo.touch_child_thys name;
aspinall@15134
   412
      transform_error ThyInfo.pretend_use_thy_only name handle ERROR_MESSAGE msg =>
aspinall@15134
   413
       (warning msg; warning ("Failed to register theory: " ^ quote name);
aspinall@15134
   414
        tell_file_retracted (Path.base (Path.unpack file))))
aspinall@15134
   415
    else raise Toplevel.UNDEF
aspinall@15134
   416
  end;
aspinall@15134
   417
aspinall@15134
   418
fun vacuous_inform_file_processed file state =
aspinall@15134
   419
 (warning ("No theory " ^ quote (thy_name file));
aspinall@15134
   420
  tell_file_retracted (Path.base (Path.unpack file)));
aspinall@15134
   421
aspinall@15134
   422
wenzelm@12778
   423
(* restart top-level loop (keeps most state information) *)
wenzelm@12778
   424
wenzelm@12778
   425
local
wenzelm@12778
   426
wenzelm@12778
   427
fun restart isar =
wenzelm@12778
   428
 (if isar then tell_clear_goals () else kill_goal ();
wenzelm@12778
   429
  tell_clear_response ();
wenzelm@12778
   430
  welcome ());
wenzelm@12778
   431
wenzelm@12778
   432
in
wenzelm@12778
   433
wenzelm@12778
   434
fun isa_restart () = restart false;
wenzelm@12778
   435
fun isar_restart () = (sync_thy_loader (); restart true; raise Toplevel.RESTART);
wenzelm@12778
   436
wenzelm@12778
   437
end;
wenzelm@12778
   438
wenzelm@12833
   439
fun full_proofs true = proofs := 2
wenzelm@12833
   440
  | full_proofs false = proofs := 1;
wenzelm@12833
   441
wenzelm@12833
   442
aspinall@15134
   443
(* theorem dependency output *)
aspinall@15134
   444
aspinall@15134
   445
local
aspinall@15134
   446
aspinall@15134
   447
val spaces_quote = space_implode " " o map quote;
aspinall@15134
   448
aspinall@15134
   449
fun thm_deps_message (thms, deps) = 
aspinall@15134
   450
    if pgip() then
aspinall@15134
   451
	issue_pgips 
aspinall@15134
   452
	    [XML.element
aspinall@15134
   453
		 "metainforesponse"  (* FIXME: get thy name from info here? *)
aspinall@15134
   454
		 [("infotype", "isabelle_theorem_dependencies")]
aspinall@15134
   455
		 [XML.element "value" [("name", "thms")] [XML.text thms],
aspinall@15134
   456
		  XML.element "value" [("name", "deps")] [XML.text deps]]]
aspinall@15134
   457
    else emacs_notify 
aspinall@15134
   458
	     ("Proof General, theorem dependencies of " 
aspinall@15134
   459
	      ^ thms ^ " are " ^ deps)
aspinall@15134
   460
aspinall@15134
   461
aspinall@15134
   462
fun tell_thm_deps ths =
aspinall@15134
   463
  conditional (thm_depsN mem_string ! print_mode) (fn () =>
aspinall@15134
   464
    let
aspinall@15134
   465
      val names = map Thm.name_of_thm ths \ "";
aspinall@15134
   466
      val deps = Symtab.keys (foldl (uncurry Proofterm.thms_of_proof)
aspinall@15134
   467
				    (Symtab.empty, map Thm.proof_of ths)) \ "";
aspinall@15134
   468
    in
aspinall@15134
   469
      if null names orelse null deps then ()
aspinall@15134
   470
      else thm_deps_message (spaces_quote names, spaces_quote deps)
aspinall@15134
   471
    end);
aspinall@15134
   472
aspinall@15134
   473
in
aspinall@15134
   474
aspinall@15134
   475
fun setup_present_hook () =
aspinall@15134
   476
  Present.add_hook (fn _ => fn res => tell_thm_deps (flat (map #2 res)));
aspinall@15134
   477
aspinall@15134
   478
end;
aspinall@15134
   479
aspinall@15134
   480
aspinall@15134
   481
(*** Preferences ***)
aspinall@15134
   482
aspinall@15134
   483
local
aspinall@15134
   484
val pgipnat        = XML.element "pgipint" [("min", "0")] [] 
aspinall@15134
   485
fun pgipnatmax max = XML.element "pgipint" [("min", "0"), 
aspinall@15134
   486
					    ("max", string_of_int max)] []
aspinall@15134
   487
val pgipbool       = XML.element "pgipbool" [] []
aspinall@15134
   488
aspinall@15134
   489
fun withdefault f = (f(), f)
aspinall@15134
   490
in
aspinall@15134
   491
aspinall@15134
   492
fun nat_option r = (pgipnat,
aspinall@15134
   493
  withdefault (fn () => string_of_int (!r)),
aspinall@15134
   494
  (fn s => (case Syntax.read_nat s of
aspinall@15134
   495
       None => error "nat_option: illegal value"
aspinall@15134
   496
     | Some i => r := i)));
aspinall@15134
   497
aspinall@15134
   498
fun bool_option r = (pgipbool,
aspinall@15134
   499
  withdefault (fn () => Bool.toString (!r)),
aspinall@15134
   500
  (fn "false" => r := false | "true" => r := true
aspinall@15134
   501
    | _ => error "bool_option: illegal value"));
aspinall@15134
   502
aspinall@15134
   503
val proof_option = (pgipbool,
aspinall@15134
   504
  withdefault (fn () => Bool.toString (!proofs >= 2)),
aspinall@15134
   505
  (fn "false" => proofs := 1 | "true" => proofs := 2
aspinall@15134
   506
    | _ => error "proof_option: illegal value"));
aspinall@15134
   507
aspinall@15134
   508
val thm_deps_option = (pgipbool,
aspinall@15134
   509
  withdefault (fn () => Bool.toString (Output.has_mode "thm_deps")),
aspinall@15134
   510
  (fn "false" => print_mode := ((!print_mode) \ "thm_deps")
aspinall@15134
   511
    | "true" => print_mode := ("thm_deps" ins (!print_mode))
aspinall@15134
   512
    | _ => error "thm_deps_option: illegal value"));
aspinall@15134
   513
aspinall@15134
   514
local 
aspinall@15134
   515
    val pg_print_depth_val = ref 10
aspinall@15134
   516
    fun pg_print_depth n = (print_depth n; pg_print_depth_val := n)
aspinall@15134
   517
in
aspinall@15134
   518
val print_depth_option = (pgipnat,
aspinall@15134
   519
  withdefault (fn () => string_of_int (!pg_print_depth_val)),
aspinall@15134
   520
  (fn s => (case Syntax.read_nat s of
aspinall@15134
   521
       None => error "print_depth_option: illegal value"
aspinall@15134
   522
     | Some i => pg_print_depth i)))
aspinall@15134
   523
end
aspinall@15134
   524
aspinall@15134
   525
val preferences = ref 
aspinall@15134
   526
  [("Display",
aspinall@15134
   527
    [("show-types", 
aspinall@15134
   528
      ("Include types in display of Isabelle terms", 
aspinall@15134
   529
       bool_option show_types)),
aspinall@15134
   530
     ("show-sorts", 
aspinall@15134
   531
      ("Include sorts in display of Isabelle terms", 
aspinall@15134
   532
       bool_option show_sorts)),
aspinall@15134
   533
     ("show-consts", 
aspinall@15134
   534
      ("Show types of consts in Isabelle goal display",
aspinall@15134
   535
       bool_option show_consts)),
aspinall@15134
   536
     ("long-names", 
aspinall@15134
   537
      ("Show fully qualified names in Isabelle terms", bool_option long_names)),
aspinall@15134
   538
     ("show-brackets", 
aspinall@15134
   539
      ("Show full bracketing in Isabelle terms",
aspinall@15134
   540
       bool_option show_brackets)),
aspinall@15134
   541
     ("show-main-goal", 
aspinall@15134
   542
      ("Show main goal in proof state display", bool_option Proof.show_main_goal)),
aspinall@15134
   543
     ("eta-contract", 
aspinall@15134
   544
      ("Print terms eta-contracted",
aspinall@15134
   545
       bool_option Syntax.eta_contract))]),
aspinall@15134
   546
   ("Advanced Display",
aspinall@15134
   547
    [("goals-limit", 
aspinall@15134
   548
      ("Setting for maximum number of goals printed",
aspinall@15134
   549
       nat_option goals_limit)),
aspinall@15134
   550
     ("prems-limit", 
aspinall@15134
   551
      ("Setting for maximum number of premises printed",
aspinall@15134
   552
       nat_option ProofContext.prems_limit)),
aspinall@15134
   553
     ("print-depth", 
aspinall@15134
   554
      ("Setting for the ML print depth",
aspinall@15134
   555
       print_depth_option))]),
aspinall@15134
   556
   ("Tracing",
aspinall@15134
   557
    [("trace-simplifier", 
aspinall@15134
   558
      ("Trace simplification rules.",
aspinall@15134
   559
       bool_option trace_simp)),
aspinall@15134
   560
     ("trace-rules", ("Trace application of the standard rules",
aspinall@15134
   561
		      bool_option trace_rules)),
aspinall@15134
   562
     ("trace-unification", 
aspinall@15134
   563
      ("Output error diagnostics during unification",
aspinall@15134
   564
       bool_option Pattern.trace_unify_fail)),
aspinall@15134
   565
     ("global-timing", 
aspinall@15134
   566
      ("Whether to enable timing in Isabelle.",
aspinall@15134
   567
       bool_option Output.timing))]),
aspinall@15134
   568
   ("Proof", 
aspinall@15134
   569
    [("quick-and-dirty", 
aspinall@15134
   570
      ("Take a few (interactive-only) short cuts",
aspinall@15134
   571
       bool_option quick_and_dirty)),
aspinall@15134
   572
     ("full-proofs", 
aspinall@15134
   573
      ("Record full proof objects internally",
aspinall@15134
   574
       proof_option)),
aspinall@15134
   575
     ("theorem-dependencies", 
aspinall@15134
   576
       ("Track theorem dependencies within Proof General",
aspinall@15134
   577
	thm_deps_option))])
aspinall@15134
   578
   ];
aspinall@15134
   579
end
aspinall@15134
   580
aspinall@15134
   581
(* Configuration: GUI config, proverinfo messages *)
aspinall@15134
   582
aspinall@15134
   583
local
aspinall@15134
   584
    val config_file = "~~/lib/ProofGeneral/pgip_isar.xml"
aspinall@15134
   585
    val name_attr = pair "name"
aspinall@15134
   586
    val version_attr = pair "version"
aspinall@15134
   587
    val isabelle_www = "http://isabelle.in.tum.de/"
aspinall@15134
   588
in
aspinall@15134
   589
fun send_pgip_config () =
aspinall@15134
   590
    let 
aspinall@15134
   591
	val path = Path.unpack config_file
aspinall@15134
   592
	val exists = File.exists path
aspinall@15134
   593
	val proverinfo = 
aspinall@15134
   594
	    XML.element "proverinfo"
aspinall@15134
   595
              [("name",Session.name()), ("version", version),
aspinall@15134
   596
	       ("url", isabelle_www)]
aspinall@15134
   597
	    [XML.element "welcomemsg" [] [XML.text (Session.welcome())],
aspinall@15134
   598
	     XML.element "helpdoc" 
aspinall@15134
   599
         (* NB: would be nice to generate/display docs from isatool
aspinall@15134
   600
          doc, but that program may not be running on same machine;
aspinall@15134
   601
          front end should be responsible for launching viewer, etc. *)
aspinall@15134
   602
		      [("name", "Isabelle/HOL Tutorial"),
aspinall@15134
   603
		       ("descr", "A Gentle Introduction to Isabelle/HOL"), 
aspinall@15134
   604
		       ("url",  "http://isabelle.in.tum.de/dist/Isabelle2003/doc/tutorial.pdf")]
aspinall@15134
   605
	      []]
aspinall@15134
   606
    in
aspinall@15134
   607
	if exists then
aspinall@15134
   608
	    (issue_pgips [proverinfo]; issue_pgips [File.read path])
aspinall@15134
   609
	else panic ("PGIP configuration file " ^ config_file ^ " not found")
aspinall@15134
   610
    end;
aspinall@15134
   611
end
aspinall@15134
   612
aspinall@15134
   613
aspinall@15134
   614
(* PGIP identifier tables (prover objects). [incomplete] *)
aspinall@15134
   615
aspinall@15134
   616
local
aspinall@15134
   617
    val objtype_thy  = "theory"
aspinall@15134
   618
    val objtype_thm  = "theorem"
aspinall@15134
   619
    val objtype_term = "term"
aspinall@15134
   620
    val objtype_type = "type"
aspinall@15134
   621
		       
aspinall@15134
   622
    fun xml_idtable ty ctx ids = 
aspinall@15134
   623
	let
aspinall@15134
   624
            fun ctx_attr (Some c)= [("context", c)]
aspinall@15134
   625
              | ctx_attr None    = []
aspinall@15134
   626
	    fun xmlid x = XML.element "identifier" [] [XML.text x];
aspinall@15134
   627
	in 
aspinall@15134
   628
	    XML.element "idtable" (("objtype", ty)::ctx_attr ctx)
aspinall@15134
   629
	                          (map xmlid ids)
aspinall@15134
   630
	end
aspinall@15134
   631
in
aspinall@15134
   632
aspinall@15134
   633
fun setids t = issue_pgip "setids" [] t
aspinall@15134
   634
fun addids t = issue_pgip "addids" [] t
aspinall@15134
   635
fun delids t = issue_pgip "delids" [] t
aspinall@15134
   636
aspinall@15134
   637
fun delallids ty = setids (xml_idtable ty None [])
aspinall@15134
   638
aspinall@15134
   639
fun send_thy_idtable ctx thys = setids (xml_idtable objtype_thy ctx thys)
aspinall@15134
   640
fun clear_thy_idtable () = delallids objtype_thy
aspinall@15134
   641
aspinall@15134
   642
fun send_thm_idtable ctx thy = 
aspinall@15134
   643
    addids (xml_idtable objtype_thm ctx (map fst (PureThy.thms_of thy)));
aspinall@15134
   644
aspinall@15134
   645
fun clear_thm_idtable () = delallids objtype_thm
aspinall@15134
   646
aspinall@15134
   647
(* fun send_type_idtable thy = TODO, it's a bit low-level messy
aspinall@15134
   648
   & maybe not so useful anyway *)
aspinall@15134
   649
	
aspinall@15134
   650
end
aspinall@15134
   651
aspinall@15134
   652
(* Response to interface queries about known objects *)
aspinall@15134
   653
aspinall@15134
   654
local
aspinall@15134
   655
 val topthy = Toplevel.theory_of o Toplevel.get_state
aspinall@15134
   656
 val pthm = print_thm oo get_thm
aspinall@15134
   657
aspinall@15134
   658
 fun idvalue tp nm = ("idvalue",[("objtype",tp),("name",nm)])
aspinall@15134
   659
in
aspinall@15134
   660
fun askids (None, Some "theory")  = send_thy_idtable None (ThyInfo.names())
aspinall@15134
   661
  | askids (None, None) =  send_thy_idtable None (ThyInfo.names())
aspinall@15134
   662
                           (* only theories known in top context *)
aspinall@15134
   663
  | askids (Some thy, Some "theory") = send_thy_idtable (Some thy) (ThyInfo.get_preds thy)
aspinall@15134
   664
  | askids (Some thy, Some "theorem") = send_thm_idtable (Some thy) (ThyInfo.get_theory thy)
aspinall@15134
   665
  | askids (Some thy, None) = (send_thy_idtable (Some thy) (ThyInfo.get_preds thy);
aspinall@15134
   666
                               send_thm_idtable (Some thy) (ThyInfo.get_theory thy)) 
aspinall@15134
   667
  | askids (_, Some ot) = error ("No objects of type "^(quote ot)^" are available here.")
aspinall@15134
   668
aspinall@15134
   669
fun showid (_,        "theory", n) = 
aspinall@15134
   670
    with_displaywrap (idvalue "theory" n) (fn ()=>(print_theory (ThyInfo.get_theory n)))
aspinall@15134
   671
  | showid (Some thy, "theorem", t) = 
aspinall@15134
   672
    with_displaywrap (idvalue "theorem" t) (fn ()=>(pthm (ThyInfo.get_theory thy) t))
aspinall@15134
   673
  | showid (None,     "theorem", t) = 
aspinall@15134
   674
    with_displaywrap (idvalue "theorem" t) (fn ()=>pthm (topthy()) t)
aspinall@15134
   675
  | showid (_, ot, _) = error ("Cannot show objects of type "^ot)
aspinall@15134
   676
aspinall@15134
   677
end
aspinall@15134
   678
	 
aspinall@15134
   679
(** Parsing proof scripts without execution **)
aspinall@15134
   680
aspinall@15134
   681
local
aspinall@15145
   682
    fun markup_text str elt = [XML.element elt [] [XML.text str]]
aspinall@15145
   683
    fun markup_text_attrs str elt attrs = [XML.element elt attrs [XML.text str]]
aspinall@15145
   684
    fun empty elt = [XML.element elt [] []]
aspinall@15145
   685
aspinall@15145
   686
    fun named_item_elt toks str elt nameP objtyp = 
aspinall@15145
   687
	let 
aspinall@15145
   688
	    val name = (fst (nameP toks))
aspinall@15145
   689
			handle _ => (error ("Error occurred in name parser for " ^ elt);
aspinall@15145
   690
				     "")
aspinall@15145
   691
				     
aspinall@15145
   692
	in 
aspinall@15145
   693
	    [XML.element elt 
aspinall@15145
   694
			 ((if name="" then [] else [("name", name)])@
aspinall@15145
   695
			  (if objtyp="" then [] else [("objtype", objtyp)]))
aspinall@15145
   696
			 ([XML.text str])]
aspinall@15145
   697
	end
aspinall@15145
   698
aspinall@15145
   699
    fun parse_warning msg = warning ("script->PGIP markup parser: " ^ msg)
aspinall@15145
   700
aspinall@15145
   701
    (* FIXME: allow dynamic extensions to language here: we need a hook in
aspinall@15145
   702
       outer_syntax.ML to reset this table. *)
aspinall@15145
   703
aspinall@15145
   704
    val keywords_classification_table = ref (None:(string Symtab.table) option)
aspinall@15145
   705
aspinall@15145
   706
    fun get_keywords_classification_table () = 
aspinall@15145
   707
	case (!keywords_classification_table) of
aspinall@15145
   708
	    Some t => t
aspinall@15145
   709
	  | None => (let
aspinall@15145
   710
			 val tab = foldl (fn (tab,(c,_,k,_))=>Symtab.update((c,k),tab)) 
aspinall@15145
   711
					 (Symtab.empty,OuterSyntax.dest_parsers())
aspinall@15145
   712
		     in (keywords_classification_table := Some tab; tab) end)
aspinall@15145
   713
aspinall@15145
   714
aspinall@15145
   715
		    
aspinall@15145
   716
    fun xmls_of_thy_begin (name,toks,str) = (* see isar_syn.ML/theoryP *)
aspinall@15145
   717
	let 
aspinall@15145
   718
	    val ((thyname,imports,files),_) = ThyHeader.args toks
aspinall@15145
   719
	in 
aspinall@15145
   720
	    markup_text_attrs str "opentheory" [("thyname",thyname)]
aspinall@15145
   721
	end 
aspinall@15145
   722
aspinall@15145
   723
    fun xmls_of_thy_decl (name,toks,str) = (* see isar_syn.ML/thy_decl cases  *)
aspinall@15145
   724
	let 
aspinall@15145
   725
	    (* NB: PGIP only deals with single name bindings at the moment;
aspinall@15145
   726
	       potentially we could markup grouped definitions several times but
aspinall@15145
   727
	       that might suggest the wrong structure to the editor?
aspinall@15145
   728
	       Better alternative would be to put naming closer around text,
aspinall@15145
   729
	       but to do that we'd be much better off modifying the real parser
aspinall@15145
   730
	       instead of reconstructing it here. *)
aspinall@15134
   731
aspinall@15145
   732
	    val plain_items = (* no names, unimportant names, or too difficult *)
aspinall@15145
   733
		["defaultsort","arities","judgement","finalconsts",
aspinall@15145
   734
		 "syntax", "nonterminals", "translations",
aspinall@15145
   735
		 "global", "local", "hide",
aspinall@15145
   736
		 "ML_setup", "setup", "method_setup",
aspinall@15145
   737
		 "parse_ast_translation", "parse_translation", "print_translation",
aspinall@15145
   738
		 "typed_print_translation", "print_ast_translation", "token_translation",
aspinall@15145
   739
		 "oracle",
aspinall@15145
   740
		 "declare"]
aspinall@15145
   741
aspinall@15145
   742
	    val plain_item   = markup_text str "theoryitem"
aspinall@15145
   743
	    val comment_item = markup_text str "litcomment"
aspinall@15145
   744
	    val named_item   = named_item_elt toks str "theoryitem"
aspinall@15145
   745
aspinall@15145
   746
	    val opt_overloaded = P.opt_keyword "overloaded";
aspinall@15145
   747
aspinall@15145
   748
	    val thmnameP = (* see isar_syn.ML/theoremsP *)
aspinall@15145
   749
		let 
aspinall@15145
   750
		    val name_facts = P.and_list1 ((P.opt_thm_name "=" --| P.xthms1) >> #1)
aspinall@15145
   751
		    val theoremsP = P.locale_target |-- name_facts >> (fn [] => "" | x::_ => x)
aspinall@15145
   752
		in 
aspinall@15145
   753
		    theoremsP
aspinall@15145
   754
		end
aspinall@15134
   755
	in 
aspinall@15145
   756
	    if (name mem plain_items) then plain_item
aspinall@15145
   757
	    else case name of
aspinall@15145
   758
		     "text"      => comment_item
aspinall@15145
   759
		   | "text_raw"  => comment_item
aspinall@15145
   760
		   | "typedecl"  => named_item (P.type_args |-- P.name) "type"
aspinall@15145
   761
		   | "types"     => named_item (P.type_args |-- P.name) "type"
aspinall@15145
   762
		   | "classes"   => named_item P.name "class"
aspinall@15145
   763
		   | "classrel"  => named_item P.name "class"
aspinall@15145
   764
		   | "consts"    => named_item (P.const >> #1) "term"
aspinall@15145
   765
		   | "axioms"    => named_item (P.spec_name >> (#1 o #1)) "theorem"
aspinall@15145
   766
		   | "defs"	 => named_item (opt_overloaded |-- P.spec_name >> (#1 o #1)) "theorem"
aspinall@15145
   767
		   | "constdefs" => named_item P.name (* FIXME: heavily simplified/wrong *) "term"
aspinall@15145
   768
		   | "theorems"  => named_item thmnameP "thmset"
aspinall@15145
   769
		   | "lemmas"    => named_item thmnameP "thmset"
aspinall@15145
   770
		   | "oracle"    => named_item P.name "oracle"
aspinall@15145
   771
		   | "locale"	 => named_item ((P.opt_keyword "open" >> not) |-- P.name) "locale"
aspinall@15145
   772
		   | _ => (parse_warning ("Unrecognized thy-decl command: " ^ name); plain_item)
aspinall@15145
   773
	end
aspinall@15145
   774
aspinall@15145
   775
    fun xmls_of_thy_goal (name,toks,str) = 
aspinall@15145
   776
	let 
aspinall@15145
   777
	    val nameP = P.locale_target |-- ((P.opt_thm_name ":") >> #1)
aspinall@15145
   778
	    (* TODO: add preference values for attributes 
aspinall@15145
   779
	       val prefval = XML.element "prefval" [("name","thm-kind"),("value",name)]
aspinall@15145
   780
	    *)
aspinall@15145
   781
	in 
aspinall@15145
   782
	    named_item_elt toks str "opengoal" nameP ""
aspinall@15134
   783
	end
aspinall@15134
   784
aspinall@15145
   785
    fun xmls_of_qed (name,markup) = case name of
aspinall@15145
   786
      "sorry"         => markup "giveupgoal"
aspinall@15145
   787
    | "oops"          => markup "postponegoal"
aspinall@15145
   788
    | "done"          => markup "closegoal" 
aspinall@15145
   789
    | "by"            => markup "closegoal"  (* nested or toplevel *)
aspinall@15145
   790
    | "qed"           => markup "closegoal"  (* nested or toplevel *)
aspinall@15145
   791
    | "."	      => markup "closegoal"  (* nested or toplevel *)
aspinall@15145
   792
    | ".."	      => markup "closegoal"  (* nested or toplevel *)
aspinall@15145
   793
    | other => (* default to closegoal: may be wrong for extns *)
aspinall@15145
   794
      (parse_warning ("Unrecognized qed command: " ^ quote other); markup "closegoal")
aspinall@15145
   795
aspinall@15145
   796
    fun xmls_of_kind kind (name,toks,str) = 
aspinall@15145
   797
    let val markup = markup_text str in 
aspinall@15145
   798
    case kind of
aspinall@15145
   799
      "control"        => markup "badcmd"
aspinall@15145
   800
    | "diag"           => markup "spuriouscmd"
aspinall@15145
   801
    (* theory/files *)
aspinall@15145
   802
    | "theory-begin"   => xmls_of_thy_begin (name,toks,str)
aspinall@15145
   803
    | "theory-decl"    => xmls_of_thy_decl (name,toks,str)
aspinall@15145
   804
    | "theory-heading" => markup "litcomment"
aspinall@15145
   805
    | "theory-script"  => markup "theorystep"
aspinall@15145
   806
    (* proof control *)
aspinall@15145
   807
    | "theory-goal"    => xmls_of_thy_goal (name,toks,str)
aspinall@15145
   808
    | "proof-heading"  => markup "litcomment"
aspinall@15145
   809
    | "proof-goal"     => markup "opengoal"  (* nested proof: have, show, ... *)
aspinall@15145
   810
    | "proof-block"    => markup "proofstep" (* context-shift: proof, next; really "newgoal" *)
aspinall@15145
   811
    | "proof-open"     => (empty "openblock") @ (markup "proofstep")
aspinall@15145
   812
    | "proof-close"    => (markup "proofstep") @ (empty "closeblock")
aspinall@15145
   813
    | "proof-script"   => markup "proofstep"
aspinall@15145
   814
    | "proof-chain"    => markup "proofstep"
aspinall@15145
   815
    | "proof-decl"     => markup "proofstep"
aspinall@15145
   816
    | "proof-asm"      => markup "proofstep"
aspinall@15145
   817
    | "proof-asm-goal" => markup "proofstep"
aspinall@15145
   818
    | "qed"            => xmls_of_qed (name,markup)
aspinall@15145
   819
    | "qed-block"      => xmls_of_qed (name,markup)
aspinall@15145
   820
    | "qed-global"     => xmls_of_qed (name,markup)
aspinall@15145
   821
    | other => (* default for anything else is "spuriouscmd", ignored for undo. *)
aspinall@15145
   822
      (parse_warning ("Internal inconsistency, unrecognized keyword kind: " ^ quote other);
aspinall@15145
   823
       markup "spuriouscmd")
aspinall@15145
   824
    end 
aspinall@15134
   825
in
aspinall@15145
   826
aspinall@15145
   827
fun xmls_of_transition (name,str,toks) = 
aspinall@15134
   828
   let 
aspinall@15145
   829
       val classification = Symtab.lookup (get_keywords_classification_table(),name)
aspinall@15145
   830
   in case classification of
aspinall@15145
   831
	  Some k => (xmls_of_kind k (name,toks,str))
aspinall@15145
   832
	| None => (* an uncategorized keyword ignored for undo (maybe wrong) *)
aspinall@15145
   833
	  (parse_warning ("Uncategorized command found: " ^ name ^ " -- using spuriouscmd");
aspinall@15145
   834
	   markup_text str "spuriouscmd")
aspinall@15145
   835
   end 
aspinall@15145
   836
aspinall@15145
   837
fun xmls_of_impropers [] = []
aspinall@15145
   838
  | xmls_of_impropers toks = 
aspinall@15145
   839
    let 
aspinall@15145
   840
	val (whs,rest) = take_prefix (not o OuterLex.is_proper) toks
aspinall@15145
   841
	fun markup [] _ = []
aspinall@15145
   842
	  | markup toks x = markup_text (implode (map OuterLex.unparse toks)) x
aspinall@15145
   843
    in
aspinall@15145
   844
	(markup whs "comment") @ (markup rest "unparseable")
aspinall@15145
   845
    end
aspinall@15145
   846
    
aspinall@15145
   847
end
aspinall@15145
   848
aspinall@15145
   849
aspinall@15145
   850
local
aspinall@15145
   851
    (* we have to weave together the whitespace/comments with proper tokens 
aspinall@15145
   852
       to reconstruct the input. *)
aspinall@15134
   853
aspinall@15145
   854
    fun match_tokens ([],us,vs) = (rev vs,us)  (* used, unused *)
aspinall@15145
   855
      | match_tokens (t::ts,w::ws,vs) = 
aspinall@15145
   856
	if (t = w) then match_tokens (ts,ws,w::vs)
aspinall@15145
   857
	else match_tokens (t::ts,ws,w::vs)
aspinall@15145
   858
      | match_tokens _ = error ("match_tokens: mismatched input parse")
aspinall@15145
   859
in
aspinall@15145
   860
    fun xmls_of_str str =
aspinall@15145
   861
    let 
aspinall@15145
   862
       val toks = OuterSyntax.scan str
aspinall@15134
   863
aspinall@15145
   864
       (* parsing:   See outer_syntax.ML/toplevel_source *)
aspinall@15145
   865
    
aspinall@15145
   866
       fun parse_loop ([],[],xmls) = xmls
aspinall@15145
   867
	 | parse_loop ([],itoks,xmls) = xmls @ (xmls_of_impropers itoks)
aspinall@15145
   868
	 | parse_loop ((nm,toks,_)::trs,itoks,xmls) =
aspinall@15145
   869
	   let 
aspinall@15145
   870
	       (* first proper token is command, except FIXME for -- *)
aspinall@15145
   871
	       val (prewhs,cmditoks') = take_prefix (not o OuterLex.is_proper) itoks
aspinall@15145
   872
	       val (cmdtok,itoks') = case cmditoks' of x::xs => (x,xs)
aspinall@15145
   873
						  | _ => error("proof_general/parse_loop impossible") 
aspinall@15145
   874
	       val (utoks,itoks'') = match_tokens (toks,itoks',[])
aspinall@15145
   875
               (* FIXME: should take trailing [w/s+] semicolon too in utoks *)
aspinall@15145
   876
aspinall@15145
   877
	       val str = implode (map OuterLex.unparse (cmdtok::utoks))
aspinall@15145
   878
aspinall@15145
   879
	       val xmls_whs = xmls_of_impropers prewhs 
aspinall@15145
   880
	       val xmls_tr  = xmls_of_transition (nm,str,toks)
aspinall@15145
   881
	   in
aspinall@15145
   882
	       parse_loop(trs,itoks'',xmls @ xmls_whs @ xmls_tr)
aspinall@15145
   883
	   end
aspinall@15134
   884
    in
aspinall@15145
   885
	(* FIXME: put errors/warnings inside the parse result *)
aspinall@15145
   886
	parse_loop (OuterSyntax.read toks, toks, [])
aspinall@15134
   887
    end
aspinall@15134
   888
aspinall@15134
   889
aspinall@15134
   890
fun parsescript str = 
aspinall@15134
   891
    issue_pgips [XML.element "parseresult" [] (xmls_of_str str)]
aspinall@15134
   892
aspinall@15134
   893
end
aspinall@15134
   894
aspinall@15134
   895
aspinall@15134
   896
aspinall@15134
   897
(**** PGIP:  Isabelle -> Interface ****)
aspinall@15134
   898
aspinall@15134
   899
val isabelle_pgml_version_supported = "1.0"; 
aspinall@15145
   900
val isabelle_pgip_version_supported = "2.0"
aspinall@15134
   901
aspinall@15134
   902
fun usespgip () = 
aspinall@15134
   903
    issue_pgipe "usespgip" [("version", isabelle_pgip_version_supported)];
aspinall@15134
   904
aspinall@15134
   905
fun usespgml () = 
aspinall@15134
   906
    issue_pgipe "usespgml" [("version", isabelle_pgml_version_supported)];
aspinall@15134
   907
aspinall@15134
   908
fun hasprefs () = 
aspinall@15134
   909
    seq (fn (prefcat, prefs) =>
aspinall@15134
   910
	    issue_pgips [XML.element "hasprefs" [("prefcategory",prefcat)]
aspinall@15134
   911
		 (map (fn (name, (descr, (ty, (default,_),_))) => 
aspinall@15134
   912
		       XML.element "haspref" [("name", name), 
aspinall@15134
   913
					      ("descr", descr), 
aspinall@15134
   914
					      ("default", default)]
aspinall@15134
   915
		       [ty]) prefs)]) (!preferences);
aspinall@15134
   916
aspinall@15134
   917
fun allprefs () = foldl (op @) ([], map snd (!preferences))
aspinall@15134
   918
	
aspinall@15134
   919
fun setpref name value = 
aspinall@15134
   920
    (case assoc (allprefs(), name) of
aspinall@15134
   921
	 None => warning ("Unknown pref: " ^ quote name)
aspinall@15134
   922
       | Some (_, (_, _, set)) => set value);
aspinall@15134
   923
aspinall@15134
   924
fun getpref name = 
aspinall@15134
   925
    (case assoc (allprefs(), name) of
aspinall@15134
   926
	 None => warning ("Unknown pref: " ^ quote name)
aspinall@15134
   927
       | Some (_, (_, (_,get), _)) => 
aspinall@15134
   928
	   issue_pgip "prefval" [("name", name)] (get ()));
aspinall@15134
   929
aspinall@15134
   930
aspinall@15134
   931
aspinall@15134
   932
aspinall@15134
   933
aspinall@15134
   934
(**** PGIP:  Interface -> Isabelle/Isar ****)
aspinall@15134
   935
aspinall@15134
   936
exception PGIP of string;
aspinall@15134
   937
exception PGIP_QUIT;
aspinall@15134
   938
aspinall@15134
   939
(* Sending commands to Isar *)
aspinall@15134
   940
aspinall@15145
   941
fun isarcmd s = 
aspinall@15145
   942
    s |> OuterSyntax.scan |> OuterSyntax.read 
aspinall@15145
   943
      |> map (Toplevel.position (Position.name "PGIP message") o #3) |> Toplevel.>>>;
aspinall@15134
   944
aspinall@15145
   945
fun xmltext ((XML.Text text)::ts) = text ^ (xmltext ts)
aspinall@15145
   946
  | xmltext [] = ""
aspinall@15145
   947
  | xmltext _ = raise PGIP "Expected text (PCDATA/CDATA)"
aspinall@15145
   948
			
aspinall@15145
   949
fun isarscript xmls = isarcmd (xmltext xmls)   (* send a script command *)
aspinall@15134
   950
aspinall@15134
   951
aspinall@15134
   952
(* load an arbitrary (.thy or .ML) file *)
aspinall@15134
   953
aspinall@15134
   954
fun use_thy_or_ml_file file = 
aspinall@15134
   955
    let
aspinall@15134
   956
	val (path,extn) = Path.split_ext (Path.unpack file)
aspinall@15134
   957
    in
aspinall@15134
   958
	case extn of
aspinall@15134
   959
	    "" => isarcmd ("use_thy " ^ (quote (Path.pack path)))
aspinall@15134
   960
	  | "thy" => isarcmd ("use_thy " ^ (quote (Path.pack path)))
aspinall@15134
   961
	  | "ML" => isarcmd ("use " ^ quote file)
aspinall@15134
   962
	  (* instead of error we could guess theory? *)
aspinall@15134
   963
	  | other => error ("Don't know how to read a file with extension " ^ other)
aspinall@15134
   964
    end  
aspinall@15134
   965
aspinall@15134
   966
aspinall@15134
   967
local
aspinall@15134
   968
  (* Proof control commands *)
aspinall@15134
   969
aspinall@15134
   970
  fun xmlattro attrs attr = assoc(attrs,attr)
aspinall@15134
   971
aspinall@15134
   972
  fun xmlattr attrs attr = 
aspinall@15134
   973
      (case xmlattro attrs attr of 
aspinall@15134
   974
	   Some value => value 
aspinall@15134
   975
	 | None => raise PGIP ("Missing attribute: " ^ attr))
aspinall@15134
   976
aspinall@15134
   977
  val thyname_attr = "thyname"
aspinall@15134
   978
  val objtype_attr = "objtype"
aspinall@15134
   979
  val name_attr = "name"
aspinall@15134
   980
  val dirname_attr = "dir"
aspinall@15134
   981
  fun comment x = "(* " ^ x ^ " *)"
aspinall@15134
   982
aspinall@15134
   983
  (* parse URLs like "file://host/name.thy" *)
aspinall@15134
   984
  (* FIXME: instead of this, extend code in General/url.ML & use that. *)
aspinall@15134
   985
  fun decode_url url = 
aspinall@15134
   986
      (let 
aspinall@15134
   987
	  val sep = find_index_eq ":" (explode url)
aspinall@15134
   988
 	  val proto = String.substring(url,0,sep)
aspinall@15134
   989
	  val hostsep = find_index_eq "/" (drop (sep+3,explode url))
aspinall@15134
   990
	  val host = String.substring(url,sep+3,hostsep-sep+4)
aspinall@15134
   991
	  val doc = if (size url >= sep+hostsep+3) then
aspinall@15134
   992
			String.substring(url,sep+hostsep+4,size url-hostsep-sep-4) 
aspinall@15134
   993
		    else ""
aspinall@15134
   994
      in 
aspinall@15134
   995
	  (proto,host,doc)
aspinall@15134
   996
      end) handle Subscript => error ("Badly formed URL " ^ url)
aspinall@15134
   997
 
aspinall@15134
   998
  fun localfile_of_url url =
aspinall@15134
   999
      let
aspinall@15134
  1000
	  val (proto,host,name) = decode_url url
aspinall@15134
  1001
      in
aspinall@15134
  1002
	  if (proto = "file" andalso 
aspinall@15134
  1003
	      (host = "" orelse 
aspinall@15134
  1004
	       host = "localhost" orelse 
aspinall@15134
  1005
	       host = (getenv "HOSTNAME")))
aspinall@15134
  1006
	     then name
aspinall@15134
  1007
	  else error ("Cannot access non-local URL " ^ url)
aspinall@15134
  1008
      end
aspinall@15134
  1009
aspinall@15134
  1010
  fun fileurl_of attrs = localfile_of_url (xmlattr attrs "url")
aspinall@15134
  1011
aspinall@15134
  1012
  val topthy = Toplevel.theory_of o Toplevel.get_state
aspinall@15134
  1013
  val topthy_name = PureThy.get_name o topthy
aspinall@15134
  1014
aspinall@15134
  1015
  val currently_open_file = ref (None : string option)
aspinall@15145
  1016
aspinall@15134
  1017
in
aspinall@15134
  1018
aspinall@15145
  1019
fun process_pgip_element pgipxml = (case pgipxml of 
aspinall@15145
  1020
  (XML.Text t) => warning ("Ignored text in PGIP packet: \n" ^ t)
aspinall@15145
  1021
| (XML.Elem (xml as (elem, attrs, data))) => 
aspinall@15145
  1022
  (case elem of
aspinall@15145
  1023
       (* protocol config *)
aspinall@15145
  1024
       "askpgip"  	=> (usespgip (); send_pgip_config ())
aspinall@15145
  1025
     | "askpgml"  	=> usespgml ()
aspinall@15145
  1026
     (* proverconfig *)
aspinall@15145
  1027
     | "askprefs" 	=> hasprefs ()
aspinall@15145
  1028
     | "getpref"  	=> getpref (xmlattr attrs name_attr)
aspinall@15145
  1029
     | "setpref"  	=> setpref (xmlattr attrs name_attr) (xmltext data)
aspinall@15145
  1030
     (* provercontrol *)
aspinall@15145
  1031
     | "proverinit" 	=> isar_restart ()
aspinall@15145
  1032
     | "proverexit" 	=> isarcmd "quit"
aspinall@15145
  1033
     | "startquiet" 	=> isarcmd "disable_pr"
aspinall@15145
  1034
     | "stopquiet"  	=> isarcmd "enable_pr"
aspinall@15145
  1035
     | "pgmlsymbolson"   => (print_mode := (["xsymbols", "symbols"] @ ! print_mode))
aspinall@15145
  1036
     | "pgmlsymbolsoff"  => (print_mode := (Library.gen_rems 
aspinall@15145
  1037
						(op =) 
aspinall@15145
  1038
						(! print_mode, ["xsymbols", "symbols"])))
aspinall@15145
  1039
     (* properproofcmd: proper commands which belong in script *)
aspinall@15145
  1040
     | "opengoal"       => isarscript data
aspinall@15145
  1041
     | "proofstep"      => isarscript data
aspinall@15145
  1042
     | "closegoal"      => isarscript data
aspinall@15145
  1043
     | "giveupgoal"     => isarscript data
aspinall@15145
  1044
     | "postponegoal"   => isarscript data
aspinall@15145
  1045
     | "comment"	=> isarscript data
aspinall@15145
  1046
     | "litcomment"     => isarscript data
aspinall@15145
  1047
     | "spuriouscmd"    => isarscript data
aspinall@15145
  1048
     | "badcmd"		=> isarscript data
aspinall@15145
  1049
     (* improperproofcmd: improper commands which *do not* belong in script *)
aspinall@15145
  1050
     | "undostep"       => isarcmd "ProofGeneral.undo"
aspinall@15145
  1051
     | "abortgoal"      => isarcmd "ProofGeneral.kill_proof"  
aspinall@15145
  1052
     | "forget"         => error "Not implemented" 
aspinall@15145
  1053
     | "restoregoal"    => error "Not implemented"  (* could just treat as forget? *)
aspinall@15145
  1054
     (* proofctxt: improper commands *)
aspinall@15145
  1055
     | "askids"         => askids (xmlattro attrs thyname_attr, 
aspinall@15145
  1056
				   xmlattro attrs objtype_attr)
aspinall@15145
  1057
     | "showid"	        => showid (xmlattro attrs thyname_attr, 
aspinall@15145
  1058
				   xmlattr attrs objtype_attr,
aspinall@15145
  1059
		     		   xmlattr attrs name_attr)
aspinall@15145
  1060
     | "parsescript"    => parsescript (xmltext data)
aspinall@15145
  1061
     | "showproofstate" => isarcmd "pr"
aspinall@15145
  1062
     | "showctxt"       => isarcmd "print_theory"   (* more useful than print_context *)
aspinall@15145
  1063
     | "searchtheorems" => isarcmd ("thms_containing " ^ (xmltext data))
aspinall@15145
  1064
     | "setlinewidth"   => isarcmd ("pretty_setmargin " ^ (xmltext data))
aspinall@15145
  1065
     | "viewdoc"	=> isarcmd ("print_" ^ (xmltext data)) (* FIXME: isatool doc? *)
aspinall@15145
  1066
     (* properfilecmd: proper theory-level script commands *)
aspinall@15145
  1067
     | "opentheory"     => isarscript data
aspinall@15145
  1068
     | "theoryitem"     => isarscript data
aspinall@15145
  1069
     | "closetheory"    => (isarscript data;
aspinall@15145
  1070
			    writeln ("Theory "^(topthy_name())^" completed."))
aspinall@15145
  1071
     (* improperfilecmd: theory-level commands not in script *)
aspinall@15145
  1072
     | "aborttheory"    => isarcmd ("init_toplevel")
aspinall@15145
  1073
     | "retracttheory"  => isarcmd ("kill_thy " ^
aspinall@15145
  1074
				    (quote (xmlattr attrs thyname_attr)))
aspinall@15145
  1075
     | "loadfile"       => use_thy_or_ml_file    (fileurl_of attrs)
aspinall@15145
  1076
     | "openfile"       => (inform_file_retracted (fileurl_of attrs);
aspinall@15145
  1077
			    currently_open_file := Some (fileurl_of attrs))
aspinall@15145
  1078
     | "closefile"      => (case !currently_open_file of 
aspinall@15145
  1079
				Some f => (inform_file_processed f;
aspinall@15145
  1080
					   currently_open_file := None)
aspinall@15145
  1081
			      | None => raise PGIP ("closefile when no file is open!"))
aspinall@15145
  1082
     | "abortfile"      => (currently_open_file := None) (* perhaps error for no file open *)
aspinall@15145
  1083
     | "changecwd"      => ThyLoad.add_path (xmlattr attrs dirname_attr)
aspinall@15145
  1084
     (* unofficial command for debugging *)
aspinall@15145
  1085
     | "quitpgip" => raise PGIP_QUIT  
aspinall@15145
  1086
     | _ => raise PGIP ("Unrecognized PGIP element: " ^ elem)))
aspinall@15134
  1087
aspinall@15134
  1088
fun process_pgip_tree s = 
aspinall@15134
  1089
    (pgip_refseq := None; 
aspinall@15134
  1090
     pgip_refid := None;
aspinall@15134
  1091
     (case s of
aspinall@15134
  1092
	  XML.Elem ("pgip", attrs, pgips) => 
aspinall@15134
  1093
	  (let 
aspinall@15134
  1094
	       val class = xmlattr attrs "class"
aspinall@15134
  1095
	       val _ = (pgip_refseq := xmlattro attrs "seq";
aspinall@15134
  1096
			pgip_refid :=  xmlattro attrs "id")
aspinall@15134
  1097
	   in  
aspinall@15134
  1098
	       if (class = "pa") then
aspinall@15134
  1099
		   seq process_pgip_element pgips
aspinall@15134
  1100
	       else 
aspinall@15134
  1101
		   raise PGIP "PGIP packet for me should have class=\"pa\""
aspinall@15134
  1102
	   end)
aspinall@15134
  1103
	| _ => raise PGIP "Invalid PGIP packet received") 
aspinall@15134
  1104
     handle (PGIP msg) => 
aspinall@15134
  1105
	    (error (msg ^ "\nPGIP error occured in XML text below:\n" ^ 
aspinall@15134
  1106
		    (XML.string_of_tree s))))
aspinall@15134
  1107
aspinall@15134
  1108
(* for export to Emacs *)
aspinall@15134
  1109
(* val process_pgip = process_pgip_tree o XML.tree_of_string; *)
aspinall@15134
  1110
(* FIXME: for temporary compatibility with PG 3.4, we engage special characters
aspinall@15134
  1111
   during output *)
aspinall@15134
  1112
fun process_pgip s = 
aspinall@15134
  1113
    (pgip_emacs_compatibility_flag := true;
aspinall@15134
  1114
     process_pgip_tree (XML.tree_of_string s);
aspinall@15134
  1115
     pgip_emacs_compatibility_flag := false)
aspinall@15134
  1116
end
aspinall@15134
  1117
aspinall@15134
  1118
aspinall@15134
  1119
aspinall@15134
  1120
aspinall@15134
  1121
(* PGIP loop: process PGIP input only *)
aspinall@15134
  1122
aspinall@15134
  1123
local  
aspinall@15134
  1124
aspinall@15145
  1125
exception XML_PARSE
aspinall@15134
  1126
aspinall@15145
  1127
fun loop src : unit =
aspinall@15134
  1128
    let 
aspinall@15134
  1129
	val _ = issue_pgipe "ready" []
aspinall@15145
  1130
	val pgipo = (Source.get_single src) 
aspinall@15145
  1131
			handle e => raise XML_PARSE
aspinall@15134
  1132
    in
aspinall@15145
  1133
	case pgipo of  
aspinall@15134
  1134
	     None  => ()
aspinall@15145
  1135
	   | Some (pgip,src') =>  
aspinall@15145
  1136
	     ((process_pgip_tree pgip); loop src') handle e => handler (e,Some src')
aspinall@15145
  1137
    end handle e => handler (e,Some src)  (* i.e. error in ready/XML parse *)
aspinall@15134
  1138
aspinall@15145
  1139
and handler (e,srco) = 
aspinall@15145
  1140
    case (e,srco) of
aspinall@15145
  1141
        (XML_PARSE,Some src) => 
aspinall@15145
  1142
	(* (!error_fn "Invalid XML input, aborting"; ()) NB: loop OK for tty, but want exit on EOF *)
aspinall@15145
  1143
         panic "Invalid XML input, aborting"
aspinall@15145
  1144
      | (PGIP_QUIT,_) => ()
aspinall@15145
  1145
      | (ERROR,Some src) => loop src (* message already given *)
aspinall@15145
  1146
      | (Interrupt,Some src) => (!error_fn "Interrupt during PGIP processing"; loop src)
aspinall@15145
  1147
      | (Toplevel.UNDEF,Some src) => (error "No working context defined"; loop src) (* usually *)
aspinall@15145
  1148
      | (e,Some src) => (error (Toplevel.exn_message e); loop src)
aspinall@15145
  1149
      | (_,None) => ()
aspinall@15134
  1150
in
aspinall@15145
  1151
  (* NB: simple tty for now; later might read from other tty-style sources (e.g. sockets). *)
aspinall@15145
  1152
aspinall@15145
  1153
  val xmlP = XML.scan_comment_whspc |-- XML.parse_elem >> single
aspinall@15145
  1154
aspinall@15145
  1155
  val tty_src = Source.set_prompt "" (Source.source Symbol.stopper xmlP None Source.tty)
aspinall@15145
  1156
aspinall@15145
  1157
  val pgip_toplevel =  loop 
aspinall@15134
  1158
end
aspinall@15134
  1159
aspinall@15134
  1160
aspinall@15134
  1161
(* additional outer syntax for Isar *)
wenzelm@12778
  1162
wenzelm@12778
  1163
local structure P = OuterParse and K = OuterSyntax.Keyword in
wenzelm@12778
  1164
aspinall@15134
  1165
val undoP = (* undo without output *)
wenzelm@12778
  1166
  OuterSyntax.improper_command "ProofGeneral.undo" "(internal)" K.control
wenzelm@12778
  1167
    (Scan.succeed (Toplevel.no_timing o IsarCmd.undo));
wenzelm@12778
  1168
wenzelm@12778
  1169
val context_thy_onlyP =
wenzelm@12778
  1170
  OuterSyntax.improper_command "ProofGeneral.context_thy_only" "(internal)" K.control
wenzelm@12778
  1171
    (P.name >> (Toplevel.no_timing oo IsarThy.init_context update_thy_only));
wenzelm@12778
  1172
wenzelm@12778
  1173
val try_context_thy_onlyP =
wenzelm@12778
  1174
  OuterSyntax.improper_command "ProofGeneral.try_context_thy_only" "(internal)" K.control
wenzelm@12778
  1175
    (P.name >> (Toplevel.no_timing oo
wenzelm@12778
  1176
      (Toplevel.imperative (K ()) oo IsarThy.init_context try_update_thy_only)));
wenzelm@12778
  1177
wenzelm@12778
  1178
val restartP =
wenzelm@12778
  1179
  OuterSyntax.improper_command "ProofGeneral.restart" "(internal)" K.control
wenzelm@12778
  1180
    (P.opt_unit >> (Toplevel.no_timing oo K (Toplevel.imperative isar_restart)));
wenzelm@12778
  1181
wenzelm@12778
  1182
val kill_proofP =
wenzelm@12778
  1183
  OuterSyntax.improper_command "ProofGeneral.kill_proof" "(internal)" K.control
wenzelm@12778
  1184
    (Scan.succeed (Toplevel.no_timing o IsarCmd.kill_proof_notify tell_clear_goals));
wenzelm@12778
  1185
wenzelm@12778
  1186
val inform_file_processedP =
wenzelm@12778
  1187
  OuterSyntax.improper_command "ProofGeneral.inform_file_processed" "(internal)" K.control
wenzelm@14902
  1188
    (P.name >> (fn file => Toplevel.no_timing o
wenzelm@14902
  1189
      Toplevel.keep (vacuous_inform_file_processed file) o
wenzelm@14902
  1190
      Toplevel.kill o
wenzelm@14902
  1191
      Toplevel.keep (proper_inform_file_processed file)));
wenzelm@12778
  1192
wenzelm@12778
  1193
val inform_file_retractedP =
wenzelm@12778
  1194
  OuterSyntax.improper_command "ProofGeneral.inform_file_retracted" "(internal)" K.control
wenzelm@12778
  1195
    (P.name >> (Toplevel.no_timing oo
wenzelm@14902
  1196
      (fn file => Toplevel.imperative (fn () => inform_file_retracted file))));
wenzelm@12778
  1197
wenzelm@14725
  1198
val process_pgipP =
wenzelm@14725
  1199
  OuterSyntax.improper_command "ProofGeneral.process_pgip" "(internal)" K.control
wenzelm@14725
  1200
    (P.text >> (Toplevel.no_timing oo
wenzelm@14725
  1201
      (fn txt => Toplevel.imperative (fn () => process_pgip txt))));
wenzelm@14725
  1202
wenzelm@12778
  1203
fun init_outer_syntax () = OuterSyntax.add_parsers
wenzelm@14675
  1204
 [undoP, restartP, kill_proofP, context_thy_onlyP, try_context_thy_onlyP,
wenzelm@14725
  1205
  inform_file_processedP, inform_file_retractedP, process_pgipP];
wenzelm@12778
  1206
wenzelm@12778
  1207
end;
wenzelm@12778
  1208
wenzelm@12778
  1209
wenzelm@12778
  1210
(* init *)
wenzelm@12778
  1211
wenzelm@12778
  1212
val initialized = ref false;
wenzelm@12778
  1213
aspinall@15134
  1214
fun set_prompts true _ = ml_prompts "ML> " "ML# " 
aspinall@15134
  1215
  | set_prompts false true = ml_prompts "PGIP-ML>" "PGIP-ML# "
aspinall@15134
  1216
  | set_prompts false false = 
aspinall@15134
  1217
    ml_prompts ("> " ^ oct_char "372") ("- " ^ oct_char "373");
aspinall@15134
  1218
aspinall@15134
  1219
fun init_setup isar pgip =
wenzelm@12778
  1220
 (conditional (not (! initialized)) (fn () =>
wenzelm@12778
  1221
   (if isar then setmp warning_fn (K ()) init_outer_syntax () else ();
wenzelm@12778
  1222
    setup_xsymbols_output ();
aspinall@15134
  1223
    setup_pgml_output ();
wenzelm@12778
  1224
    setup_messages ();
wenzelm@12778
  1225
    setup_state ();
wenzelm@12778
  1226
    setup_thy_loader ();
wenzelm@13526
  1227
    setup_present_hook ();
wenzelm@12778
  1228
    set initialized; ()));
wenzelm@12778
  1229
  sync_thy_loader ();
wenzelm@12778
  1230
  print_mode := proof_generalN :: (! print_mode \ proof_generalN);
aspinall@15134
  1231
  if pgip then 
aspinall@15134
  1232
      print_mode := pgmlN :: (pgmlatomsN :: (! print_mode \ pgmlN \ pgmlatomsN)) 
aspinall@15134
  1233
    else ();
wenzelm@12778
  1234
  set quick_and_dirty;
wenzelm@12778
  1235
  ThmDeps.enable ();
aspinall@15134
  1236
  set_prompts isar pgip;
aspinall@15134
  1237
  pgip_active := pgip)
aspinall@15134
  1238
aspinall@15134
  1239
fun init isar = 
aspinall@15134
  1240
    (init_setup isar false;
aspinall@15134
  1241
     if isar then ((* da: this welcome is problematic: clashes with welcome
aspinall@15134
  1242
		      issued for PG anyway. 
aspinall@15134
  1243
		      welcome (); *)
aspinall@15134
  1244
		    Isar.sync_main ()) else isa_restart ());
aspinall@15134
  1245
aspinall@15134
  1246
fun init_pgip false = panic "Sorry, PGIP not supported for Isabelle/classic mode."
aspinall@15145
  1247
  | init_pgip true = (init_setup true true; pgip_toplevel tty_src);
wenzelm@12778
  1248
wenzelm@12778
  1249
wenzelm@12778
  1250
aspinall@15134
  1251
(** generate keyword classification elisp file **)
wenzelm@12778
  1252
wenzelm@12778
  1253
local
wenzelm@12778
  1254
wenzelm@12778
  1255
val regexp_meta = explode ".*+?[]^$";
aspinall@15134
  1256
val regexp_quote = 
aspinall@15134
  1257
    implode o map  (fn c => if c mem regexp_meta then "\\\\" ^ c else c)
aspinall@15134
  1258
    o explode;
wenzelm@12778
  1259
wenzelm@12778
  1260
fun defconst name strs =
wenzelm@12778
  1261
  "\n(defconst isar-keywords-" ^ name ^
wenzelm@12778
  1262
  "\n  '(" ^ space_implode "\n    " (map (quote o regexp_quote) strs) ^ "))\n";
wenzelm@12778
  1263
wenzelm@12778
  1264
fun make_elisp_commands commands kind =
aspinall@15134
  1265
  defconst kind (mapfilter 
aspinall@15134
  1266
		     (fn (c, _, k, _) => if k = kind then Some c else None) 
aspinall@15134
  1267
		     commands);
wenzelm@12778
  1268
wenzelm@12778
  1269
fun make_elisp_syntax (keywords, commands) =
wenzelm@12778
  1270
  ";;\n\
wenzelm@12778
  1271
  \;; Keyword classification tables for Isabelle/Isar.\n\
wenzelm@12778
  1272
  \;; This file was generated by " ^ Session.name () ^ " -- DO NOT EDIT!\n\
wenzelm@12778
  1273
  \;;\n\
wenzelm@12778
  1274
  \;; $" ^ "Id$\n\
wenzelm@12778
  1275
  \;;\n" ^
wenzelm@12778
  1276
  defconst "major" (map #1 commands) ^
aspinall@15134
  1277
  defconst "minor" (filter Syntax.is_identifier keywords) ^
wenzelm@12778
  1278
  implode (map (make_elisp_commands commands) OuterSyntax.Keyword.kinds) ^
wenzelm@12778
  1279
  "\n(provide 'isar-keywords)\n";
wenzelm@12778
  1280
wenzelm@12778
  1281
in
wenzelm@12778
  1282
wenzelm@12778
  1283
fun write_keywords s =
wenzelm@12778
  1284
  (init_outer_syntax ();
wenzelm@12778
  1285
    File.write (Path.unpack ("isar-keywords" ^ (if s = "" then "" else "-" ^ s) ^".el"))
aspinall@15134
  1286
      (make_elisp_syntax (OuterSyntax.dest_keywords (), 
aspinall@15134
  1287
			  OuterSyntax.dest_parsers ())));
wenzelm@12778
  1288
wenzelm@12778
  1289
end;
wenzelm@12778
  1290
aspinall@15134
  1291
end