
structure OutputTutorial =
struct

(* rebuilding the output function from ThyOutput in order to *)
(* enable the options [gray, linenos]                        *)

val gray = ref false
val linenos = ref false


fun output txt =
let
  val prts = map Pretty.str txt
in   
  prts
  |> (if ! ThyOutput.quotes then map Pretty.quote else I)
  |> (if ! ThyOutput.display then
    map (Output.output o Pretty.string_of o Pretty.indent (! ThyOutput.indent))
    #> space_implode "\\isasep\\isanewline%\n"
    #> (if ! linenos then (enclose "\\begin{linenos}%\n" "%\n\\end{linenos}") else I) 
    #> (if ! gray then (enclose "\\begin{graybox}%\n" "%\n\\end{graybox}") else I) 
    #> enclose "\\begin{isabelle}%\n" "%\n\\end{isabelle}"
  else
    map (Output.output o (if ! ThyOutput.break then Pretty.string_of else Pretty.str_of))
    #> space_implode "\\isasep\\isanewline%\n"
    #> enclose "\\isa{" "}")
end

datatype indstring =
  NoString
| Plain   of string
| Code    of string
| Struct  of string

fun translate_string f = Symbol.explode #> map f #> implode;

val clean_string = translate_string
  (fn "_" => "\\_"
    | "#" => "\\#"
    | "<" => "\\isacharless"
    | ">" => "\\isachargreater"
    | "{" => "\\{"
    | "|" => "\\isacharbar"
    | "}" => "\\}"
    | "$" => "\\isachardollar"
    | "!" => "\\isacharbang"
    | "\<dash>" => "-"
    | c => c)

fun get_word str =
let 
  fun only_letters [] = true
    | only_letters (x::xs) = 
        if (Symbol.is_ascii_blank x) then false else only_letters xs
in
  if only_letters (Symbol.explode str) 
  then clean_string str
  else error ("Only single word allowed! Error with " ^ quote str)
end  

fun get_indstring NoString = ""
  | get_indstring (Plain s) = get_word s
  | get_indstring (Code s) = let val w = get_word s in implode[w, "@{\\tt\\slshape{}", w, "}"] end
  | get_indstring (Struct s) =  implode ["in {\\tt\\slshape{}", get_word s, "}"]

fun get_index {main = m, minor = n} = 
 (if n = NoString
  then implode ["\\index{", get_indstring m, "}"]  
  else implode ["\\index{", get_indstring m, " (", get_indstring n, ")}"])  
    
fun output_indexed ind txt =
 txt |> output
     |> prefix (get_index ind)

fun boolean "" = true
  | boolean "true" = true
  | boolean "false" = false
  | boolean s = error ("Bad boolean value: " ^ quote s);

val _ = ThyOutput.add_options
 [("gray", Library.setmp gray o boolean),
  ("linenos", Library.setmp linenos o boolean)]

end