
/******************************************************************************
* MODULE     : totex.gen.cc
* DESCRIPTION: conversion of TeXmacs trees into TeX strings
* COPYRIGHT  : (C) 1999  Joris van der Hoeven
*******************************************************************************
* This software falls under the GNU general public license and comes WITHOUT
* ANY WARRANTY WHATSOEVER. See the file $TEXMACS_PATH/LICENSE for more details.
* If you don't have this file, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
******************************************************************************/

#module code_totex

bool eval_scheme_func_tree_string (string f, tree t, string& r);

static tree
substitute_bad_chars (tree t) {
  if (is_atomic (t)) {
    string s= t->label, r;
    int i, n= N(s);
    for (i=0; i<n; i++)
      switch ((int) s[i]) {
      case 0: r << "`"; break;
      case 1: r << "'"; break;
      case 2: r << "^"; break;
      case 3: r << "~"; break;
      case 4: r << "\""; break;
      default: r << s[i];
      }
    return r;
  }
  else {
    int i, n= N(t);
    tree r (t, n);
    for (i=0; i<n; i++)
      r[i]= substitute_bad_chars (t[i]);
    return r;
  }
}

static string
tree_to_tex_latex (
  tree t, tree style, string mode, string lan,
  bool latex_flag, bool document_flag)
{
  (void) latex_flag;
  if (is_atomic (style)) style= tree (TUPLE, style);
  t= substitute_bad_chars (t);
  if (mode == "math") t= tree (WITH, "mode", "math", t);
  if (document_flag) {
    t= tree (EXPAND, "!file", t);
    string tmpath= get_env ("TEXMACS_PATH");
    while ((N(tmpath)>0) && (tmpath [N(tmpath) - 1] == '/'))
      tmpath= tmpath (0, N(tmpath)-1);
    t << style << lan << tmpath;
  }

  string r;
  eval_scheme_func_tree_string ("tmtex-produce", t, r);
  return r;
}

string
tree_to_tex (tree t, string mode) {
  return tree_to_tex_latex (t, "article", mode, "english", FALSE, FALSE);
}

string
tree_to_tex_document (tree t, tree style, string lan) {
  return tree_to_tex_latex (t, style, "text", lan, FALSE, TRUE);
}

string
tree_to_latex (tree t, string mode) {
  return tree_to_tex_latex (t, "article", mode, "english", TRUE, FALSE);
}

string
tree_to_latex_document (tree t, tree style, string lan) {
  return tree_to_tex_latex (t, style, "text", lan, TRUE, TRUE);
}

#endmodule // code_totex
