/***************************************************************************
                    TexGenerator.cpp  -  description
                             -------------------
    begin                : Mit Jul 24 2002
    copyright            : (C) 2002-2026 by Andre Simon
    email                : a.simon@mailbox.org
 ***************************************************************************/


/*
This file is part of Highlight.

Highlight is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Highlight is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Highlight.  If not, see <http://www.gnu.org/licenses/>.
*/


#include <sstream>

#include "charcodes.h"
#include "version.h"
#include "texgenerator.h"

using std::ostringstream;
using std::string;

namespace highlight
{

TexGenerator::TexGenerator()
    : CodeGenerator ( TEX )
{
    /*This makes TeX to use every par it encounters (the \\leavevmode has
    no effect when TeX is in horizontal mode and when TeX is in vertical
    mode, it switches it to horizontal mode).*/
    newLineTag="\\leavevmode\\par\n";

    spacer = initialSpacer = "\\ ";
    maskWs=true;
    excludeWs=true;
    maskWsBegin = "{\\hl"+STY_NAME_STD;
    maskWsEnd = "}";
    styleCommentOpen="%";
}

void TexGenerator::initOutputTags()
{
    openTags = {
         "{\\hl"+STY_NAME_STD+" ",
         "{\\hl"+STY_NAME_STR+" ",
         "{\\hl"+STY_NAME_NUM+" ",
         "{\\hl"+STY_NAME_SLC+" ",
         "{\\hl"+STY_NAME_COM+" ",
         "{\\hl"+STY_NAME_ESC+" ",
         "{\\hl"+STY_NAME_DIR+" ",
         "{\\hl"+STY_NAME_DST+" ",
         "{\\hl"+STY_NAME_LIN+" ",
         "{\\hl"+STY_NAME_SYM+" ",
         "{\\hl"+STY_NAME_IPL+" ",

         "{\\hl"+STY_NAME_ERR+" ",
         "{\\hl"+STY_NAME_ERM+" "
    };

    closeTags.assign ( NUMBER_BUILTIN_STATES, "}" );

    guideTagOpen = "{\\hl" + STY_NAME_GUI + " ";
    guideTagClose = "}";
}

string TexGenerator::getAttributes ( const string & elemName,const ElementStyle & elem )
{
    ostringstream s;

    s << "\\def\\hl"
      << elemName
      << "{";

    if (!elem.getCustomOverride()) {

        if ( elem.isBold() )  s << "\\bf";
        if ( elem.isItalic() )  s << "\\it";
        s   <<  "\\textColor{"
            << ( elem.getColour().getRed ( TEX ) ) <<" "
            << ( elem.getColour().getGreen ( TEX ) ) <<" "
            << ( elem.getColour().getBlue ( TEX ) ) <<" 0.0}";
    }

    if (string customStyle = elem.getCustomAttribute(); !customStyle.empty()) {
        s << customStyle;
    }

    s << "}\n";

    return  s.str();
}

string TexGenerator::getHeader()
{
    ostringstream os;
    os << styleCommentOpen
       << " Document title: " << docTitle << "\n\n";
    if ( currentSyntax->highlightingEnabled() ) {
        if ( includeStyleDef ) {
            os << getStyleDefinition();
            os << CodeGenerator::readUserStyleDef();
        } else {
            os << "\\input "
               << getStyleOutputPath()
               << "\n\n";
        }
    }

    return os.str();
}

void TexGenerator::printBody()
{
    *out << "{\n\\"<<getBaseFont() <<"\n";

    processRootState();

    *out << "}\n";
}

string TexGenerator::getFooter()
{
    ostringstream os;
    os << "\\bye\n";

    if (!omitVersionComment) {
        os  << "% TeX generated by Highlight "
            << highlight::Info::getVersion()
            << ", "
            << highlight::Info::getWebsite() << "\n";
    }
    return os.str();
}

string TexGenerator:: maskCharacter ( unsigned char c )
{
    switch ( c ) {
    case '{':
    case '}': {
        string m ( "$\\" );
        m += c;
        m += '$';
        return m;
    }
    case '^':
        return "{\\bf\\^{}}";
    case '_':
    case '&':
    case '$':
    case '#':
    case '%': {
        string m ( "\\" );
        m += c;
        m += "{}";
        return m;
    }
    case '\\':
        return "$\\backslash$";
    case ' ':
        return spacer;
    case '+':
    case '-':
    case '<':
    case '>':
    case '=': {
        string m ( "$\\mathord{" );
        m += c;
        m += "}$";
        return m;
    }
    case AUML_LC:
        return "\\\"a";
    case OUML_LC:
        return "\\\"o";
    case UUML_LC:
        return "\\\"u";
    case AUML_UC:
        return "\\\"A";
    case OUML_UC:
        return "\\\"O";
    case UUML_UC:
        return "\\\"U";
    case AACUTE_LC:
        return "\\'a";
    case EACUTE_LC:
        return "\\'e";
    case OACUTE_LC:
        return "\\'o";
    case UACUTE_LC:
        return "\\'u";
    case AGRAVE_LC:
        return "\\`a";
    case EGRAVE_LC:
        return "\\`e";
    case OGRAVE_LC:
        return "\\`o";
    case UGRAVE_LC:
        return "\\`u";
    case AACUTE_UC:
        return "\\'A";
    case EACUTE_UC:
        return "\\'E";
    case OACUTE_UC:
        return "\\'O";
    case UACUTE_UC:
        return "\\'U";
    case AGRAVE_UC:
        return "\\`A";
    case EGRAVE_UC:
        return "\\`E";
    case UGRAVE_UC:
        return "\\`O";
    case OGRAVE_UC:
        return "\\`U";
    case SZLIG:
        return "\\ss ";

    default :
        return string ( 1, c );
    }
}

string TexGenerator::getKeywordOpenTag ( unsigned int styleID )
{
    return "{\\hl"+currentSyntax->getKeywordClasses() [styleID]+" ";
}

string TexGenerator::getKeywordCloseTag ( unsigned int styleID )
{
    return "}";
}


string TexGenerator::getStyleDefinition()
{
    if ( disableStyleCache || styleDefinitionCache.empty() ) {
        ostringstream os;
        os << "% highlight theme: "<<docStyle.getDescription()<<"\n";
        os << getAttributes ( STY_NAME_STD, docStyle.getDefaultStyle() );
        os << getAttributes ( STY_NAME_NUM, docStyle.getNumberStyle() );
        os << getAttributes ( STY_NAME_ESC, docStyle.getEscapeCharStyle() );
        os << getAttributes ( STY_NAME_STR, docStyle.getStringStyle() );
        os << getAttributes ( STY_NAME_DST, docStyle.getPreProcStringStyle() );
        os << getAttributes ( STY_NAME_SLC, docStyle.getSingleLineCommentStyle() );
        os << getAttributes ( STY_NAME_COM, docStyle.getCommentStyle() );
        os << getAttributes ( STY_NAME_DIR, docStyle.getPreProcessorStyle() );
        os << getAttributes ( STY_NAME_LIN, docStyle.getLineStyle() );
        os << getAttributes ( STY_NAME_SYM, docStyle.getOperatorStyle() );
        os << getAttributes ( STY_NAME_IPL, docStyle.getInterpolationStyle() );

        os << getAttributes ( STY_NAME_ERR, docStyle.getErrorStyle() );
        os << getAttributes ( STY_NAME_ERM, docStyle.getErrorMessageStyle() );
        if ( showIndentGuides ) {
            os << getAttributes ( STY_NAME_GUI, docStyle.getIndentGuideStyle() );
        }

        for ( const auto &[first, second] : docStyle.getKeywordStyles() ) {
            os << getAttributes ( first, second );
        }

        os <<  "% The special option is not supported by all dvi drivers\n"
           << "\\special{background rgb "
           << docStyle.getBgColour().getRed ( LATEX ) << " "
           << docStyle.getBgColour().getGreen ( LATEX ) << " "
           << docStyle.getBgColour().getBlue ( LATEX ) << "}";
        os << "\n\\nopagenumbers\n"
           << "\\input colordvi\n";
        styleDefinitionCache=os.str();
    }
    return styleDefinitionCache;
}

}
