/*
   ktigcc - TIGCC IDE for KDE

   Copyright (C) 2004-2007 Kevin Kofler
   Copyright (C) 2006 Joey Adams
   Copyright (C) 2007 Konrad Meyer

   This program 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 2, or (at your option)
   any later version.

   This program 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 this program; if not, write to the Free Software Foundation,
   Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
*/

#include <cstdio>
#include <cstdlib>
#include <unistd.h>
#include <kapplication.h>
#include <kcmdlineargs.h>
#include <kaboutdata.h>
#include <kglobal.h>
#include <kstandarddirs.h>
#include <QTextCodec>
#include <QColor>
#include <QFont>
#include <QDomDocument>
#include <QDomElement>
#include <QDomNode>
#include <QDomAttr>
#include <QDomText>
#include <QDir>
#include <QPair>
#include <QLinkedList>
#include <kconfig.h>
#include <kconfiggroup.h>
#include "ktigcc.h"
#include "preferences.h"
#include "preferencesdlg.h"
#include "tpr.h"

// versions of the syntax highlighting description file:
// 1.00 = KTIGCC 20060807 Beta
// 1.01 = KTIGCC 20060814 Beta - 1.07 
// 1.02 = current KTIGCC 1 (since 1.08)
// 1.80 = KTIGCC 2 up to 1.80-20070702
// 1.81 = current KTIGCC 2 (since 1.80-20070702)
#define CURRENT_SYNFILE_VERSION "1.81"

TIGCCPrefs preferences;

static void writeSyntaxXML(const Syn_SettingsForDoc &synprefs,
                           const QString &name, const QString &internalName)
{
  // Create XML document.
  QDomDocument doc("language");
  QDomElement root=doc.createElement("language");
  doc.appendChild(root);

  // Work around bad interfaces...
  #define ADD_ATTR(node,aname,aval) do { \
    QDomAttr newattr=doc.createAttribute((aname)); \
    newattr.setValue((aval)); \
    (node).setAttributeNode(newattr); \
  } while(0)
  #define ADD_TEXT(node,text) do { \
    QDomText newtext=doc.createTextNode((text)); \
    (node).appendChild(newtext); \
  } while(0)
  #define CHILD_NODE(child,node,chname) \
    QDomElement child=doc.createElement((chname));\
    (node).appendChild(child)

  bool allWordListsCaseInsensitive=TRUE;
  foreach (const Syn_WordList &wordList, synprefs.wordLists)
    if (wordList.caseSensitive) allWordListsCaseInsensitive=FALSE;

  ADD_ATTR(root,"name","TIGCC "+name);
  ADD_ATTR(root,"section","KTIGCC");
  ADD_ATTR(root,"extensions","");
  ADD_ATTR(root,"version",CURRENT_SYNFILE_VERSION);
  ADD_ATTR(root,"kateversion","2.5");
  ADD_ATTR(root,"author","KTIGCC (autogenerated)");
  ADD_ATTR(root,"license","GPL");

  CHILD_NODE(highlighting,root,"highlighting");
  CHILD_NODE(general,root,"general");

  foreach (const Syn_WordList &wordList, synprefs.wordLists) {
    CHILD_NODE(list,highlighting,"list");
    ADD_ATTR(list,"name",wordList.name);
    QStringList stringList=wordList.list;
    foreach (QString keyword, stringList) {
      CHILD_NODE(item,list,"item");
      ADD_TEXT(item,keyword);
    }
  }

  CHILD_NODE(contexts,highlighting,"contexts");
  CHILD_NODE(defaultContext,contexts,"context");
  ADD_ATTR(defaultContext,"name","Default");
  ADD_ATTR(defaultContext,"attribute","Normal");
  ADD_ATTR(defaultContext,"lineEndContext","#stay");
  foreach (const Syn_CustomStyle &customStyle, synprefs.customStyles) {
    switch (customStyle.beginning.length()) {
      case 0: // Ignore these ones altogether.
        break;
      case 1:
        {
          CHILD_NODE(detectCustomStyle,defaultContext,"DetectChar");
          ADD_ATTR(detectCustomStyle,"attribute",customStyle.name);
          ADD_ATTR(detectCustomStyle,"context",customStyle.name);
          if (customStyle.lineStartOnly)
            ADD_ATTR(detectCustomStyle,"firstNonSpace","true");
          ADD_ATTR(detectCustomStyle,"char",customStyle.beginning.left(1));
        }
        break;
      case 2:
        {
          CHILD_NODE(detectCustomStyle,defaultContext,"Detect2Chars");
          ADD_ATTR(detectCustomStyle,"attribute",customStyle.name);
          ADD_ATTR(detectCustomStyle,"context",customStyle.name);
          if (customStyle.lineStartOnly)
            ADD_ATTR(detectCustomStyle,"firstNonSpace","true");
          ADD_ATTR(detectCustomStyle,"char",customStyle.beginning.left(1));
          ADD_ATTR(detectCustomStyle,"char1",customStyle.beginning.mid(1,1));
        }
        break;
      default:
        {
          CHILD_NODE(detectCustomStyle,defaultContext,"StringDetect");
          ADD_ATTR(detectCustomStyle,"attribute",customStyle.name);
          ADD_ATTR(detectCustomStyle,"context",customStyle.name);
          if (customStyle.lineStartOnly)
            ADD_ATTR(detectCustomStyle,"firstNonSpace","true");
          ADD_ATTR(detectCustomStyle,"String",customStyle.beginning);
        }
        break;
    }
  }
  foreach (const Syn_WordList &wordList, synprefs.wordLists) {
    CHILD_NODE(detectWordList,defaultContext,"keyword");
    ADD_ATTR(detectWordList,"attribute",wordList.name);
    ADD_ATTR(detectWordList,"context","#stay");
    ADD_ATTR(detectWordList,"String",wordList.name);
    if (!(wordList.caseSensitive || allWordListsCaseInsensitive))
      ADD_ATTR(detectWordList,"insensitive","true");
  }
  CHILD_NODE(numFloat,defaultContext,"Float");
  ADD_ATTR(numFloat,"attribute","Number");
  ADD_ATTR(numFloat,"context","#stay");
  CHILD_NODE(numFloatSuffix,numFloat,"AnyChar");
  ADD_ATTR(numFloatSuffix,"String","fF");
  ADD_ATTR(numFloatSuffix,"attribute","Number");
  ADD_ATTR(numFloatSuffix,"context","#stay");
  CHILD_NODE(numInt,defaultContext,"RegExpr");
  ADD_ATTR(numInt,"String","\\b\\d\\w*");
  ADD_ATTR(numInt,"attribute","Number");
  ADD_ATTR(numInt,"context","#stay");
  CHILD_NODE(numHex,defaultContext,"RegExpr");
  ADD_ATTR(numHex,"String","\\$\\w+");
  ADD_ATTR(numHex,"attribute","Number");
  ADD_ATTR(numHex,"context","#stay");
  CHILD_NODE(symbols,defaultContext,"AnyChar");
  ADD_ATTR(symbols,"String","<{[)]}>;:,.=+-*/\\|\"\'!?&%#@^~");
  ADD_ATTR(symbols,"attribute","Symbol");
  ADD_ATTR(symbols,"context","#stay");

  unsigned numParenthesisColors=synprefs.parenthesisColors.count();
  CHILD_NODE(parenOpen,defaultContext,"DetectChar");
  ADD_ATTR(parenOpen,"char","(");
  if (numParenthesisColors) {
    ADD_ATTR(parenOpen,"attribute","Paren0");
    ADD_ATTR(parenOpen,"context","Paren0");
  } else {
    ADD_ATTR(parenOpen,"attribute","Symbol");
    ADD_ATTR(parenOpen,"context","#stay");
  }
  for (unsigned i=0; i<numParenthesisColors; i++) {
    CHILD_NODE(pareniContext,contexts,"context");
    QString parenp1="Paren%1";
    QString pareni=parenp1.arg(i);
    QString pareni1=parenp1.arg((i+1==numParenthesisColors)?0:(i+1));
    ADD_ATTR(pareniContext,"name",pareni);
    ADD_ATTR(pareniContext,"attribute","Normal");
    ADD_ATTR(pareniContext,"lineEndContext","#stay");
    CHILD_NODE(push,pareniContext,"DetectChar");
    ADD_ATTR(push,"char","(");
    ADD_ATTR(push,"attribute",pareni1);
    ADD_ATTR(push,"context",pareni1);
    CHILD_NODE(pop,pareniContext,"DetectChar");
    ADD_ATTR(pop,"char",")");
    ADD_ATTR(pop,"attribute",pareni);
    ADD_ATTR(pop,"context","#pop");
    CHILD_NODE(includeRules,pareniContext,"IncludeRules");
    ADD_ATTR(includeRules,"context","Default");
  }

  for (QLinkedList<Syn_CustomStyle>::ConstIterator it=synprefs.customStyles.begin();
       it!=synprefs.customStyles.end(); ++it) {
    const Syn_CustomStyle &customStyle=*it;
    bool endsWithNewline=(customStyle.ending=="\n");
    bool endsWithSpace=(customStyle.ending==" ");
    bool noIgnoreEndingAfter=customStyle.ignoreEndingAfter.isNull();
    bool needIgnoreContext=!endsWithNewline && !noIgnoreEndingAfter;
    CHILD_NODE(customStyleContext,contexts,"context");
    ADD_ATTR(customStyleContext,"name",customStyle.name);
    ADD_ATTR(customStyleContext,"attribute",customStyle.name);
    ADD_ATTR(customStyleContext,"lineEndContext",(endsWithNewline||
      (endsWithSpace&&noIgnoreEndingAfter))?"#pop":"#stay");
    if (endsWithNewline && customStyle.ignoreEndingAfter=='\\') {
      CHILD_NODE(lineContinue,customStyleContext,"LineContinue");
      ADD_ATTR(lineContinue,"attribute",customStyle.name);
      ADD_ATTR(lineContinue,"context","#stay");
    } else if (needIgnoreContext) {
      CHILD_NODE(detectCustomStyle,customStyleContext,"DetectChar");
      ADD_ATTR(detectCustomStyle,"attribute",customStyle.name);
      ADD_ATTR(detectCustomStyle,"context",customStyle.name+" Ignore");
      ADD_ATTR(detectCustomStyle,"char",QString(customStyle.ignoreEndingAfter));
      if (customStyle.ignoreEndingAfter=='\\') {
        CHILD_NODE(detectCustomStyleTrigraph,customStyleContext,"StringDetect");
        ADD_ATTR(detectCustomStyleTrigraph,"attribute",customStyle.name);
        ADD_ATTR(detectCustomStyleTrigraph,"context",customStyle.name+" Ignore");
        ADD_ATTR(detectCustomStyleTrigraph,"String","?""?""/");
      }
    }
    if (endsWithSpace) {
      CHILD_NODE(detectCustomStyle,customStyleContext,"DetectSpaces");
      ADD_ATTR(detectCustomStyle,"attribute",customStyle.name);
      ADD_ATTR(detectCustomStyle,"context","#pop");
    } else if (!endsWithNewline) {
      switch (customStyle.ending.length()) {
        case 0: // No ending...
          break;
        case 1:
          {
            CHILD_NODE(detectCustomStyle,customStyleContext,"DetectChar");
            ADD_ATTR(detectCustomStyle,"attribute",customStyle.name);
            ADD_ATTR(detectCustomStyle,"context","#pop");
            ADD_ATTR(detectCustomStyle,"char",customStyle.ending.left(1));
          }
          break;
        case 2:
          {
            CHILD_NODE(detectCustomStyle,customStyleContext,"Detect2Chars");
            ADD_ATTR(detectCustomStyle,"attribute",customStyle.name);
            ADD_ATTR(detectCustomStyle,"context","#pop");
            ADD_ATTR(detectCustomStyle,"char",customStyle.ending.left(1));
            ADD_ATTR(detectCustomStyle,"char1",customStyle.ending.mid(1,1));
          }
          break;
        default:
          {
            CHILD_NODE(detectCustomStyle,customStyleContext,"StringDetect");
            ADD_ATTR(detectCustomStyle,"attribute",customStyle.name);
            ADD_ATTR(detectCustomStyle,"context","#pop");
            ADD_ATTR(detectCustomStyle,"String",customStyle.ending);
          }
          break;
      }
    }
    if (customStyle.switchable) {
      for (QLinkedList<Syn_CustomStyle>::ConstIterator it2=synprefs.customStyles.begin();
           it2!=synprefs.customStyles.end(); ++it2) {
        if (it2==it) continue;
        const Syn_CustomStyle &otherCustomStyle=*it2;
        if (otherCustomStyle.ending==customStyle.ending) {
          switch (otherCustomStyle.beginning.length()) {
            case 0: // Ignore these ones altogether.
              break;
            case 1:
              {
                CHILD_NODE(detectCustomStyle,customStyleContext,"DetectChar");
                ADD_ATTR(detectCustomStyle,"attribute",otherCustomStyle.name);
                ADD_ATTR(detectCustomStyle,"context","#pop");
                if (otherCustomStyle.lineStartOnly)
                  ADD_ATTR(detectCustomStyle,"firstNonSpace","true");
                ADD_ATTR(detectCustomStyle,"char",otherCustomStyle.beginning.left(1));
                ADD_ATTR(detectCustomStyle,"lookAhead","true");
              }
              break;
            case 2:
              {
                CHILD_NODE(detectCustomStyle,customStyleContext,"Detect2Chars");
                ADD_ATTR(detectCustomStyle,"attribute",otherCustomStyle.name);
                ADD_ATTR(detectCustomStyle,"context","#pop");
                if (otherCustomStyle.lineStartOnly)
                  ADD_ATTR(detectCustomStyle,"firstNonSpace","true");
                ADD_ATTR(detectCustomStyle,"char",otherCustomStyle.beginning.left(1));
                ADD_ATTR(detectCustomStyle,"char1",otherCustomStyle.beginning.mid(1,1));
                ADD_ATTR(detectCustomStyle,"lookAhead","true");
              }
              break;
            default:
              {
                CHILD_NODE(detectCustomStyle,customStyleContext,"StringDetect");
                ADD_ATTR(detectCustomStyle,"attribute",otherCustomStyle.name);
                ADD_ATTR(detectCustomStyle,"context","#pop");
                if (otherCustomStyle.lineStartOnly)
                  ADD_ATTR(detectCustomStyle,"firstNonSpace","true");
                ADD_ATTR(detectCustomStyle,"String",otherCustomStyle.beginning);
                ADD_ATTR(detectCustomStyle,"lookAhead","true");
              }
              break;
          }
        }
      }
    }
    if (needIgnoreContext) {
      CHILD_NODE(customStyleIgnoreContext,contexts,"context");
      ADD_ATTR(customStyleIgnoreContext,"name",customStyle.name+" Ignore");
      ADD_ATTR(customStyleIgnoreContext,"attribute",customStyle.name);
      ADD_ATTR(customStyleIgnoreContext,"lineEndContext","#pop");
      CHILD_NODE(pop,customStyleIgnoreContext,"RegExpr");
      ADD_ATTR(pop,"attribute",customStyle.name);
      ADD_ATTR(pop,"context","#pop");
      ADD_ATTR(pop,"String",".");
    }
  }

  CHILD_NODE(itemDatas,highlighting,"itemDatas");
  #define DEF_ITEM_DATA(idname,color,style) do { \
    CHILD_NODE(itemData,itemDatas,"itemData");\
    ADD_ATTR(itemData,"name",(idname));\
    ADD_ATTR(itemData,"defStyleNum","dsNormal");\
    QColor idcolor=(color);\
    if (idcolor.isValid())\
      ADD_ATTR(itemData,"color",idcolor.name());\
    Syn_Style idstyle=(style);\
    if (idstyle&SYNS_CUSTOM) {\
      ADD_ATTR(itemData,"bold",(idstyle&SYNS_BOLD)?"1":"0");\
      ADD_ATTR(itemData,"underline",(idstyle&SYNS_UNDERLINE)?"1":"0");\
      ADD_ATTR(itemData,"italic",(idstyle&SYNS_ITALIC)?"1":"0");\
      ADD_ATTR(itemData,"strikeOut",(idstyle&SYNS_STRIKEOUT)?"1":"0");\
    }\
  } while(0)
  DEF_ITEM_DATA("Normal",QColor(),0);
  DEF_ITEM_DATA("Number",synprefs.numberColor,synprefs.numberStyle);
  DEF_ITEM_DATA("Symbol",synprefs.symbolColor,synprefs.symbolStyle);
  unsigned i=0;
  foreach (const QColor &color, synprefs.parenthesisColors)
    DEF_ITEM_DATA(QString("Paren%1").arg(i++),color,synprefs.parenthesisStyle);
  foreach (const Syn_CustomStyle &customStyle, synprefs.customStyles)
    DEF_ITEM_DATA(customStyle.name,customStyle.color,customStyle.style);
  foreach (const Syn_WordList &wordList, synprefs.wordLists)
    DEF_ITEM_DATA(wordList.name,wordList.color,wordList.style);
  #undef DEF_ITEM_DATA

  CHILD_NODE(keywords,general,"keywords");
  ADD_ATTR(keywords,"casesensitive",allWordListsCaseInsensitive?"0":"1");
  ADD_ATTR(keywords,"additionalDeliminator","\'\"#@");

  #undef ADD_ATTR
  #undef ADD_TEXT
  #undef CHILD_NODE

  // Write it to disk.
  QString xmlFileName=QString("%1/share/apps/katepart/syntax/ktigcc%2.xml")
                      .arg(KGlobal::dirs()->localkdedir()).arg(internalName);
  mkdir_multi(xmlFileName);
  std::FILE *f=std::fopen(xmlFileName,"w");
  if (f) {
    if (fputs("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
              "<!-- Syntax highlighting description autogenerated by KTIGCC.\n"
              "     All changes to this file will be lost! -->\n",f)<0) {
      fclose(f);
      return;
    }
    (void) fputs(doc.toByteArray(2),f);
    fclose(f);
  }
}

static void updateSyntaxXML(void)
{
  writeSyntaxXML(preferences.synC,"C","c");
  writeSyntaxXML(preferences.synS,"GNU As","s");
  writeSyntaxXML(preferences.synAsm,"A68k","asm");
  writeSyntaxXML(preferences.synQll,"Quill","qll");
}

// True if version1 is newer than version2.
static bool isNewerVersion(const QString &version1, const QString &version2)
{
  QStringList vl1=version1.split('.',QString::SkipEmptyParts);
  QStringList vl2=version2.split('.',QString::SkipEmptyParts);
  QStringList::Iterator it1=vl1.begin(), it2=vl2.begin();
  for (; it1!=vl1.end() && it2!=vl2.end(); ++it1, ++it2) {
    bool ok1, ok2;
    unsigned v1=(*it1).toUInt(&ok1), v2=(*it2).toUInt(&ok2);
    if (!ok1 || !ok2) return TRUE;
    if (v1>v2) return TRUE;
    else if (v1<v2) return FALSE;
  }
  return (it1!=vl1.end());
}

static bool checkSynHighlightVersion(const QString &internalName)
{
  QString xmlFileName=QString("%1/share/apps/katepart/syntax/ktigcc%2.xml")
                      .arg(KGlobal::dirs()->localkdedir()).arg(internalName);
  QDomDocument doc("language");
  QFile file(xmlFileName);
  if (!file.open(QIODevice::ReadOnly))
    return FALSE;
  if (!doc.setContent(&file)) {
    file.close();
    return FALSE;
  }
  file.close();
  QDomNode language=doc.elementsByTagName("language").item(0);
  if (language.isNull() || language.nodeType()!=QDomNode::ElementNode)
    return FALSE;
  QDomAttr version=language.toElement().attributeNode("version");
  if (version.isNull())
    return FALSE;
  QString versionNumber=version.value();
  return !isNewerVersion(CURRENT_SYNFILE_VERSION,versionNumber);
}

static void checkSynHighlightVersions(void)
{
  if (!checkSynHighlightVersion("c"))
    writeSyntaxXML(preferences.synC,"C","c");
  if (!checkSynHighlightVersion("s"))
    writeSyntaxXML(preferences.synS,"GNU As","s");
  if (!checkSynHighlightVersion("asm"))
    writeSyntaxXML(preferences.synAsm,"A68k","asm");
  if (!checkSynHighlightVersion("qll"))
    writeSyntaxXML(preferences.synQll,"Quill","qll");
}

static bool loadSyntaxPreference(Syn_SettingsForDoc &synprefs, const QString &group)
{
  KConfigGroup config=pconfig->group(group+" Syntax Highlighting");
  synprefs.enabled=config.readEntry("Enabled",true);
  synprefs.numberColor=config.readEntry("Number Color",QColor());
  if (!synprefs.numberColor.isValid()) return FALSE;
  synprefs.symbolColor=config.readEntry("Symbol Color",QColor());
  if (!synprefs.symbolColor.isValid()) return FALSE;
  unsigned numParenthesisColors=config.readEntry("Num Parenthesis Colors",0u);
  for (unsigned i=0; i<numParenthesisColors; i++) {
    QColor parenthesisColor=config.readEntry(QString("Parenthesis Color %1").arg(i),QColor());
    if (!parenthesisColor.isValid()) return FALSE;
    synprefs.parenthesisColors.append(parenthesisColor);
  }
  synprefs.numberStyle=config.readEntry("Number Style",0u);
  synprefs.symbolStyle=config.readEntry("Symbol Style",0u);
  synprefs.parenthesisStyle=config.readEntry("Parenthesis Style",0u);
  unsigned numCustomStyles=config.readEntry("Num Custom Styles",0u);
  for (unsigned i=0; i<numCustomStyles; i++) {
    Syn_CustomStyle customStyle;
    customStyle.name=config.readEntry(QString("Custom Style %1 Name").arg(i),QString("Style %1").arg(i));
    customStyle.beginning=config.readEntry(QString("Custom Style %1 Beginning").arg(i));
    customStyle.ending=config.readEntry(QString("Custom Style %1 Ending").arg(i));
    if (customStyle.ending=="\\s") customStyle.ending=" "; // work around KDE bug
    QString ignoreEndingAfter=config.readEntry(QString("Custom Style %1 Ignore Ending After").arg(i));
    customStyle.ignoreEndingAfter=ignoreEndingAfter.isEmpty()?QChar():ignoreEndingAfter[0];
    customStyle.switchable=config.readEntry(QString("Custom Style %1 Switchable").arg(i),false);
    customStyle.lineStartOnly=config.readEntry(QString("Custom Style %1 Line Start Only").arg(i),false);
    customStyle.color=config.readEntry(QString("Custom Style %1 Color").arg(i),QColor());
    customStyle.style=config.readEntry(QString("Custom Style %1 Style").arg(i),0u);
    synprefs.customStyles.append(customStyle);
  }
  unsigned numWordLists=config.readEntry("Num Word Lists",0u);
  for (unsigned i=0; i<numWordLists; i++) {
    Syn_WordList wordList;
    wordList.name=config.readEntry(QString("Word List %1 Name").arg(i),QString("Word List %1").arg(i));
    wordList.list=config.readEntry(QString("Word List %1 List").arg(i),QStringList());
    wordList.color=config.readEntry(QString("Word List %1 Color").arg(i),QColor());
    wordList.style=config.readEntry(QString("Word List %1 Style").arg(i),0u);
    wordList.caseSensitive=config.readEntry(QString("Word List %1 Case Sensitive").arg(i),false);
    synprefs.wordLists.append(wordList);
  }
  return TRUE;
}

static bool loadSyntaxPreferences(void)
{
  return loadSyntaxPreference(preferences.synC,"C")
         && loadSyntaxPreference(preferences.synS,"GNU As")
         && loadSyntaxPreference(preferences.synAsm,"A68k")
         && loadSyntaxPreference(preferences.synQll,"Quill");
}

static void saveSyntaxPreference(const Syn_SettingsForDoc &synprefs, const QString &group)
{
  unsigned i;
  KConfigGroup config=pconfig->group(group+" Syntax Highlighting");
  config.writeEntry("Enabled",synprefs.enabled);
  config.writeEntry("Number Color",synprefs.numberColor);
  config.writeEntry("Symbol Color",synprefs.symbolColor);
  i=0;
  foreach (const QColor &color, synprefs.parenthesisColors)
    config.writeEntry(QString("Parenthesis Color %1").arg(i++),color);
  config.writeEntry("Num Parenthesis Colors",i);
  config.writeEntry("Number Style",(unsigned)synprefs.numberStyle);
  config.writeEntry("Symbol Style",(unsigned)synprefs.symbolStyle);
  config.writeEntry("Parenthesis Style",(unsigned)synprefs.parenthesisStyle);
  i=0;
  foreach (const Syn_CustomStyle &customStyle, synprefs.customStyles) {
    config.writeEntry(QString("Custom Style %1 Name").arg(i),customStyle.name);
    config.writeEntry(QString("Custom Style %1 Beginning").arg(i),customStyle.beginning);
    config.writeEntry(QString("Custom Style %1 Ending").arg(i),customStyle.ending);
    config.writeEntry(QString("Custom Style %1 Ignore Ending After").arg(i),QString(customStyle.ignoreEndingAfter));
    config.writeEntry(QString("Custom Style %1 Switchable").arg(i),customStyle.switchable);
    config.writeEntry(QString("Custom Style %1 Line Start Only").arg(i),customStyle.lineStartOnly);
    config.writeEntry(QString("Custom Style %1 Color").arg(i),customStyle.color);
    config.writeEntry(QString("Custom Style %1 Style").arg(i++),(unsigned)customStyle.style);
  }
  config.writeEntry("Num Custom Styles",i);
  i=0;
  foreach (const Syn_WordList &wordList, synprefs.wordLists) {
    config.writeEntry(QString("Word List %1 Name").arg(i),wordList.name);
    config.writeEntry(QString("Word List %1 List").arg(i),wordList.list);
    config.writeEntry(QString("Word List %1 Color").arg(i),wordList.color);
    config.writeEntry(QString("Word List %1 Style").arg(i),(unsigned)wordList.style);
    config.writeEntry(QString("Word List %1 Case Sensitive").arg(i++),wordList.caseSensitive);
  }
  config.writeEntry("Num Word Lists",i);
}

static void saveSyntaxPreferences(void)
{
  saveSyntaxPreference(preferences.synC,"C");
  saveSyntaxPreference(preferences.synS,"GNU As");
  saveSyntaxPreference(preferences.synAsm,"A68k");
  saveSyntaxPreference(preferences.synQll,"Quill");
  updateSyntaxXML();

  // Save to disk
  pconfig->sync();
}

void resetSyntaxPreference(Syn_SettingsForDoc *syn)
{
  bool synIsC=(syn==&(preferences.synC) || syn==&(preferences.tempSynC));
  bool synIsS=(syn==&(preferences.synS) || syn==&(preferences.tempSynS));
  bool synIsAsm=(syn==&(preferences.synAsm) || syn==&(preferences.tempSynAsm));
  bool synIsQll=(syn==&(preferences.synQll) || syn==&(preferences.tempSynQll));

  syn->enabled=true;
  syn->numberColor=(synIsQll?QColor(128,64,64):QColor(128,0,0));
  syn->symbolColor=QColor(128,128,0);
  syn->parenthesisColors.clear();
  if (synIsQll)
    syn->parenthesisColors << QColor(0,0,0) << QColor(255,0,128);
  else
    syn->parenthesisColors << QColor(128,0,128) << QColor(0,128,192)
                           << QColor(255,128,128) << QColor(0,128,0);
  syn->numberStyle=0;
  syn->symbolStyle=SYNS_CUSTOM|SYNS_BOLD;
  syn->parenthesisStyle=SYNS_CUSTOM|SYNS_BOLD;
  
  Syn_CustomStyle Comment_Area;
  Comment_Area.name="Comment Area";
  Comment_Area.beginning="/*";
  Comment_Area.ending="*/";
  Comment_Area.ignoreEndingAfter=0;
  Comment_Area.switchable=false;
  Comment_Area.lineStartOnly=false;
  Comment_Area.color=QColor(0,128,0);
  Comment_Area.style=SYNS_CUSTOM|SYNS_ITALIC;
  Syn_CustomStyle Comment_Line;
  Comment_Line.name="Comment Line";
  Comment_Line.beginning="//";
  Comment_Line.ending="\n";
  Comment_Line.ignoreEndingAfter=0;
  Comment_Line.switchable=false;
  Comment_Line.lineStartOnly=false;
  Comment_Line.color=QColor(0,128,0);
  Comment_Line.style=SYNS_CUSTOM|SYNS_ITALIC;
  Syn_CustomStyle SCS_String;
  SCS_String.name="String";
  SCS_String.beginning="\"";
  SCS_String.ending="\"";
  SCS_String.ignoreEndingAfter='\\';
  SCS_String.switchable=false;
  SCS_String.lineStartOnly=false;
  SCS_String.color=QColor(128,0,0);
  SCS_String.style=0;
  Syn_CustomStyle Character;
  Character.name="Character";
  Character.beginning="\'";
  Character.ending="\'";
  Character.ignoreEndingAfter='\\';
  Character.switchable=false;
  Character.lineStartOnly=false;
  Character.color=QColor(128,0,0);
  Character.style=0;
  Syn_CustomStyle Preprocessor_Directive;
  Preprocessor_Directive.name="Preprocessor Directive";
  Preprocessor_Directive.beginning="#";
  Preprocessor_Directive.ending=" ";
  Preprocessor_Directive.ignoreEndingAfter=0;
  Preprocessor_Directive.switchable=false;
  Preprocessor_Directive.lineStartOnly=false;
  Preprocessor_Directive.color=QColor(0,128,128);
  Preprocessor_Directive.style=SYNS_CUSTOM|SYNS_BOLD;
  Syn_CustomStyle Comment_Line_Pipe;
  Comment_Line_Pipe.name="Comment Line (|)";
  Comment_Line_Pipe.beginning="|";
  Comment_Line_Pipe.ending="\n";
  Comment_Line_Pipe.ignoreEndingAfter=0;
  Comment_Line_Pipe.switchable=false;
  Comment_Line_Pipe.lineStartOnly=false;
  Comment_Line_Pipe.color=QColor(0,128,0);
  Comment_Line_Pipe.style=SYNS_CUSTOM|SYNS_ITALIC;
  Syn_CustomStyle Comment_Line_Pound;
  Comment_Line_Pound.name="Comment Line (#)";
  Comment_Line_Pound.beginning="#";
  Comment_Line_Pound.ending="\n";
  Comment_Line_Pound.ignoreEndingAfter=0;
  Comment_Line_Pound.switchable=false;
  Comment_Line_Pound.lineStartOnly=true;
  Comment_Line_Pound.color=QColor(0,128,0);
  Comment_Line_Pound.style=SYNS_CUSTOM|SYNS_ITALIC;
  Syn_CustomStyle Comment_Line_Semicolon;
  Comment_Line_Semicolon.name="Comment";
  Comment_Line_Semicolon.beginning=";";
  Comment_Line_Semicolon.ending="\n";
  Comment_Line_Semicolon.ignoreEndingAfter=0;
  Comment_Line_Semicolon.switchable=false;
  Comment_Line_Semicolon.lineStartOnly=false;
  Comment_Line_Semicolon.color=QColor(0,128,0);
  Comment_Line_Semicolon.style=SYNS_CUSTOM|SYNS_ITALIC;
  Syn_CustomStyle String_DoubleQuoted;
  String_DoubleQuoted.name="String (double-quoted)";
  String_DoubleQuoted.beginning="\"";
  String_DoubleQuoted.ending="\"";
  String_DoubleQuoted.ignoreEndingAfter=0;
  String_DoubleQuoted.switchable=false;
  String_DoubleQuoted.lineStartOnly=false;
  String_DoubleQuoted.color=QColor(128,0,0);
  String_DoubleQuoted.style=0;
  Syn_CustomStyle String_SingleQuoted;
  String_SingleQuoted.name="String (single-quoted)";
  String_SingleQuoted.beginning="\'";
  String_SingleQuoted.ending="\'";
  String_SingleQuoted.ignoreEndingAfter=0;
  String_SingleQuoted.switchable=false;
  String_SingleQuoted.lineStartOnly=false;
  String_SingleQuoted.color=QColor(128,0,0);
  String_SingleQuoted.style=0;
  Syn_CustomStyle Compiler_Directive;
  Compiler_Directive.name="Compiler Directive";
  Compiler_Directive.beginning="#";
  Compiler_Directive.ending="\n";
  Compiler_Directive.ignoreEndingAfter='\\';
  Compiler_Directive.switchable=true;
  Compiler_Directive.lineStartOnly=false;
  Compiler_Directive.color=QColor(0,128,128);
  Compiler_Directive.style=SYNS_CUSTOM|SYNS_BOLD;

  syn->customStyles.clear();
  if (synIsC)
    syn->customStyles << Comment_Area << Comment_Line << SCS_String << Character << Preprocessor_Directive;
  else if (synIsS)
    syn->customStyles << Comment_Area << Comment_Line_Pipe << Comment_Line_Pound << SCS_String << Character;
  else if (synIsAsm)
    syn->customStyles << Comment_Line_Semicolon << String_DoubleQuoted << String_SingleQuoted;
  else if (synIsQll)
    syn->customStyles << Comment_Area << Comment_Line << SCS_String << Character << Compiler_Directive;

  Syn_WordList C_Keywords;
  C_Keywords.name="C Keywords";
  C_Keywords.list=QString(
                  "__alignof__\n"
                  "__asm__\n"
                  "__attribute__\n"
                  "__complex__\n"
                  "__const__\n"
                  "__extension__\n"
                  "__imag__\n"
                  "__inline__\n"
                  "__label__\n"
                  "__real__\n"
                  "__typeof__\n"
                  "asm\n"
                  "auto\n"
                  "break\n"
                  "case\n"
                  "char\n"
                  "const\n"
                  "continue\n"
                  "default\n"
                  "do\n"
                  "double\n"
                  "else\n"
                  "enum\n"
                  "extern\n"
                  "float\n"
                  "for\n"
                  "goto\n"
                  "if\n"
                  "inline\n"
                  "int\n"
                  "long\n"
                  "register\n"
                  "return\n"
                  "short\n"
                  "signed\n"
                  "sizeof\n"
                  "static\n"
                  "struct\n"
                  "switch\n"
                  "typedef\n"
                  "typeof\n"
                  "union\n"
                  "unsigned\n"
                  "void\n"
                  "volatile\n"
                  "while\n").split('\n',QString::SkipEmptyParts);
  C_Keywords.color=QColor(0,0,255);
  C_Keywords.style=SYNS_CUSTOM|SYNS_BOLD;
  C_Keywords.caseSensitive=true;
  Syn_WordList Data_Movement;
  Data_Movement.name="Data Movement";
  Data_Movement.list= QString(
                      "EXG\n"
                      "LEA\n"
                      "LINK\n"
                      "MOV\n"
                      "MOVE\n"
                      "MOVEA\n"
                      "MOVEM\n"
                      "MOVEP\n"
                      "MOVEQ\n"
                      "MOVM\n"
                      "MOVP\n"
                      "MOVQ\n"
                      "PEA\n"
                      "UNLK\n").split('\n',QString::SkipEmptyParts);
  Data_Movement.color=QColor(0,0,255);
  Data_Movement.style=0;
  Data_Movement.caseSensitive=false;
  Syn_WordList Integer_Arithmetic;
  Integer_Arithmetic.name="Integer Arithmetic";
  Integer_Arithmetic.list=QString(
                          "ADD\n"
                          "ADDA\n"
                          "ADDI\n"
                          "ADDQ\n"
                          "ADDX\n"
                          "CLR\n"
                          "CMP\n"
                          "CMPA\n"
                          "CMPI\n"
                          "CMPM\n"
                          "DIVS\n"
                          "DIVU\n"
                          "EXT\n"
                          "MULS\n"
                          "MULU\n"
                          "NEG\n"
                          "NEGX\n"
                          "SUB\n"
                          "SUBA\n"
                          "SUBI\n"
                          "SUBQ\n"
                          "SUBX\n"
                          "TAS\n").split('\n',QString::SkipEmptyParts);
  Integer_Arithmetic.color=QColor(0,0,255);
  Integer_Arithmetic.style=0;
  Integer_Arithmetic.caseSensitive=false;
  Syn_WordList Logical_Instructions;
  Logical_Instructions.name="Logical Instructions";
  Logical_Instructions.list=QString(
                            "AND\n"
                            "ANDI\n"
                            "EOR\n"
                            "EORI\n"
                            "NOT\n"
                            "OR\n"
                            "ORI\n").split('\n',QString::SkipEmptyParts);
  Logical_Instructions.color=QColor(0,0,255);
  Logical_Instructions.style=0;
  Logical_Instructions.caseSensitive=false;
  Syn_WordList ShiftRotation_Instructions;
  ShiftRotation_Instructions.name="Shift/Rotation Instructions";
  ShiftRotation_Instructions.list=QString(
                                  "ASL\n"
                                  "ASR\n"
                                  "LSL\n"
                                  "LSR\n"
                                  "ROL\n"
                                  "ROR\n"
                                  "ROXL\n"
                                  "ROXR\n"
                                  "SWAP\n").split('\n',QString::SkipEmptyParts);
  ShiftRotation_Instructions.color=QColor(0,0,255);
  ShiftRotation_Instructions.style=0;
  ShiftRotation_Instructions.caseSensitive=false;
  Syn_WordList Bit_Manipulation;
  Bit_Manipulation.name="Bit Manipulation";
  Bit_Manipulation.list=QString(
                        "BCHG\n"
                        "BCLR\n"
                        "BSET\n"
                        "BTST\n").split('\n',QString::SkipEmptyParts);
  Bit_Manipulation.color=QColor(0,0,255);
  Bit_Manipulation.style=0;
  Bit_Manipulation.caseSensitive=false;
  Syn_WordList Program_Control;
  Program_Control.name="Program Control";
  Program_Control.list= QString(
                        "BCC\n"
                        "BCS\n"
                        "BEQ\n"
                        "BGE\n"
                        "BGT\n"
                        "BHI\n"
                        "BLE\n"
                        "BLS\n"
                        "BLT\n"
                        "BMI\n"
                        "BNE\n"
                        "BPL\n"
                        "BRA\n"
                        "BSR\n"
                        "BVC\n"
                        "BVS\n"
                        "JBCC\n"
                        "JBCS\n"
                        "JBEQ\n"
                        "JBGE\n"
                        "JBGT\n"
                        "JBHI\n"
                        "JBLE\n"
                        "JBLS\n"
                        "JBLT\n"
                        "JBMI\n"
                        "JBNE\n"
                        "JBPL\n"
                        "JBRA\n"
                        "JBSR\n"
                        "JBVC\n"
                        "JBVS\n"
                        "JSR\n"
                        "JRA\n"
                        "JMP\n"
                        "NOP\n"
                        "RTR\n"
                        "RTS\n"
                        "SCC\n"
                        "SCS\n"
                        "SEQ\n"
                        "SF\n"
                        "SGE\n"
                        "SGT\n"
                        "SHI\n"
                        "SLE\n"
                        "SLS\n"
                        "SLT\n"
                        "SMI\n"
                        "SNE\n"
                        "SPL\n"
                        "ST\n"
                        "SVC\n"
                        "SVS\n"
                        "TST\n"
                        "JHI\n"
                        "JLS\n"
                        "JCC\n"
                        "JCS\n"
                        "JNE\n"
                        "JEQ\n"
                        "JVC\n"
                        "JVS\n"
                        "JPL\n"
                        "JMI\n"
                        "JGE\n"
                        "JLT\n"
                        "JGT\n"
                        "JLE\n"
                        "DBHI\n"
                        "DBLS\n"
                        "DBCC\n"
                        "DBCS\n"
                        "DBNE\n"
                        "DBEQ\n"
                        "DBVC\n"
                        "DBVS\n"
                        "DBPL\n"
                        "DBMI\n"
                        "DBGE\n"
                        "DBLT\n"
                        "DBGT\n"
                        "DBLE\n"
                        "DBF\n"
                        "DBRA\n"
                        "DBT\n"
                        "FJNE\n"
                        "FJEQ\n"
                        "FJGE\n"
                        "FJLT\n"
                        "FJGT\n"
                        "FJLE\n"
                        "FJF\n"
                        "FJT\n"
                        "FJGL\n"
                        "FJGLE\n"
                        "FJNGE\n"
                        "FJNGL\n"
                        "FJNGLE\n"
                        "FJNGT\n"
                        "FJNLE\n"
                        "FJNLT\n"
                        "FJOGE\n"
                        "FJOGL\n"
                        "FJOGT\n"
                        "FJOLE\n"
                        "FJOLT\n"
                        "FJOR\n"
                        "FJSEQ\n"
                        "FJSF\n"
                        "FJSNE\n"
                        "FJST\n"
                        "FJUEQ\n"
                        "FJUGE\n"
                        "FJUGT\n"
                        "FJULE\n"
                        "FJULT\n"
                        "FJUN\n").split('\n',QString::SkipEmptyParts);
  Program_Control.color=QColor(0,0,255);
  Program_Control.style=0;
  Program_Control.caseSensitive=false;
  Syn_WordList System_Control;
  System_Control.name="System Control";
  System_Control.list=QString(
                      "ILLEGAL\n"
                      "RTE\n"
                      "TRAP\n").split('\n',QString::SkipEmptyParts);
  System_Control.color=QColor(0,0,255);
  System_Control.style=0;
  System_Control.caseSensitive=false;
  Syn_WordList SWL_Extensions;
  SWL_Extensions.name="Extensions";
  SWL_Extensions.list=QString(
                      "B\n"
                      "L\n"
                      "S\n"
                      "W\n").split('\n',QString::SkipEmptyParts);
  SWL_Extensions.color=QColor(0,128,64);
  SWL_Extensions.style=0;
  SWL_Extensions.caseSensitive=false;
  Syn_WordList Assembler_Directives;
  Assembler_Directives.name="Assembler Directives";
  Assembler_Directives.list=QString(
                            "abort\n"
                            "align\n"
                            "altmacro\n"
                            "ascii\n"
                            "asciz\n"
                            "balign\n"
                            "balignw\n"
                            "balignl\n"
                            "byte\n"
                            "comm\n"
                            "data\n"
                            "def\n"
                            "dim\n"
                            "double\n"
                            "eject\n"
                            "else\n"
                            "end\n"
                            "elseif\n"
                            "endef\n"
                            "endfunc\n"
                            "endif\n"
                            "endm\n"
                            "endr\n"
                            "equ\n"
                            "equiv\n"
                            "err\n"
                            "even\n"
                            "exitm\n"
                            "extern\n"
                            "fail\n"
                            "file\n"
                            "fill\n"
                            "float\n"
                            "func\n"
                            "global\n"
                            "globl\n"
                            "hword\n"
                            "ident\n"
                            "if\n"
                            "include\n"
                            "incbin\n"
                            "int\n"
                            "irp\n"
                            "irpc\n"
                            "lcomm\n"
                            "lflags\n"
                            "line\n"
                            "ln\n"
                            "list\n"
                            "long\n"
                            "macro\n"
                            "mri\n"
                            "noaltmacro\n"
                            "nolist\n"
                            "octa\n"
                            "org\n"
                            "p2align\n"
                            "p2alignw\n"
                            "p2alignl\n"
                            "print\n"
                            "psize\n"
                            "purgem\n"
                            "quad\n"
                            "rept\n"
                            "sbttl\n"
                            "scl\n"
                            "section\n"
                            "set\n"
                            "short\n"
                            "single\n"
                            "size\n"
                            "sleb128\n"
                            "skip\n"
                            "space\n"
                            "stabd\n"
                            "stabn\n"
                            "stabs\n"
                            "string\n"
                            "struct\n"
                            "tag\n"
                            "text\n"
                            "title\n"
                            "type\n"
                            "uleb128\n"
                            "val\n"
                            "vtable_entry\n"
                            "word\n"
                            "xdef\n").split('\n',QString::SkipEmptyParts);
  Assembler_Directives.color=QColor(0,0,255);
  Assembler_Directives.style=SYNS_CUSTOM|SYNS_BOLD;
  Assembler_Directives.caseSensitive=true;
  Syn_WordList SWL_Registers;
  SWL_Registers.name="Registers";
  SWL_Registers.list= QString(
                      "a0\n"
                      "a1\n"
                      "a2\n"
                      "a3\n"
                      "a4\n"
                      "a5\n"
                      "a6\n"
                      "a7\n"
                      "d0\n"
                      "d1\n"
                      "d2\n"
                      "d3\n"
                      "d4\n"
                      "d5\n"
                      "d6\n"
                      "d7\n"
                      "fp\n"
                      "pc\n"
                      "sp\n"
                      "sr\n").split('\n',QString::SkipEmptyParts);
  SWL_Registers.color=QColor(255,0,0);
  SWL_Registers.style=SYNS_CUSTOM|SYNS_UNDERLINE;
  SWL_Registers.caseSensitive=false;
  Syn_WordList Data_Movement_a68k;
  Data_Movement_a68k.name="Data Movement";
  Data_Movement_a68k.list= QString(
                           "EXG\n"
                           "LEA\n"
                           "LINK\n"
                           "MOVE\n"
                           "MOVEA\n"
                           "MOVEM\n"
                           "MOVEP\n"
                           "MOVEQ\n"
                           "PEA\n"
                           "UNLK\n").split('\n',QString::SkipEmptyParts);
  Data_Movement_a68k.color=QColor(0,0,255);
  Data_Movement_a68k.style=0;
  Data_Movement_a68k.caseSensitive=false;
  Syn_WordList ShiftRotation_Instructions_a68k;
  ShiftRotation_Instructions_a68k.name="Shift/Rotation Instructions";
  ShiftRotation_Instructions_a68k.list=QString(
                                       "ASL\n"
                                       "ASR\n"
                                       "LSL\n"
                                       "LSR\n"
                                       "ROL\n"
                                       "ROLX\n"
                                       "ROR\n"
                                       "RORX\n"
                                       "ROXL\n"
                                       "ROXR\n"
                                       "SWAP\n").split('\n',QString::SkipEmptyParts);
  ShiftRotation_Instructions_a68k.color=QColor(0,0,255);
  ShiftRotation_Instructions_a68k.style=0;
  ShiftRotation_Instructions_a68k.caseSensitive=false;
  Syn_WordList Program_Control_a68k;
  Program_Control_a68k.name="Program Control";
  Program_Control_a68k.list=QString(
                            "BCC\n"
                            "BCS\n"
                            "BEQ\n"
                            "BGE\n"
                            "BGT\n"
                            "BHI\n"
                            "BHS\n"
                            "BLE\n"
                            "BLO\n"
                            "BLS\n"
                            "BLT\n"
                            "BMI\n"
                            "BNE\n"
                            "BPL\n"
                            "BRA\n"
                            "BSR\n"
                            "BVC\n"
                            "BVS\n"
                            "DBCC\n"
                            "DBCS\n"
                            "DBEQ\n"
                            "DBF\n"
                            "DBGE\n"
                            "DBGT\n"
                            "DBHI\n"
                            "DBHS\n"
                            "DBLE\n"
                            "DBLO\n"
                            "DBLS\n"
                            "DBLT\n"
                            "DBMI\n"
                            "DBNE\n"
                            "DBPL\n"
                            "DBRA\n"
                            "DBT\n"
                            "DBVC\n"
                            "DBVS\n"
                            "JMP\n"
                            "JSR\n"
                            "NOP\n"
                            "RTR\n"
                            "RTS\n"
                            "SCC\n"
                            "SCS\n"
                            "SEQ\n"
                            "SF\n"
                            "SGE\n"
                            "SGT\n"
                            "SHI\n"
                            "SHS\n"
                            "SLE\n"
                            "SLO\n"
                            "SLS\n"
                            "SLT\n"
                            "SMI\n"
                            "SNE\n"
                            "SPL\n"
                            "ST\n"
                            "SVC\n"
                            "SVS\n"
                            "TST\n").split('\n',QString::SkipEmptyParts);
  Program_Control_a68k.color=QColor(0,0,255);
  Program_Control_a68k.style=0;
  Program_Control_a68k.caseSensitive=false;
  Syn_WordList Assembler_Directives_a68k;
  Assembler_Directives_a68k.name="Assembler Directives";
  Assembler_Directives_a68k.list= QString(
                                  "BSS\n"
                                  "CNOP\n"
                                  "CSEG\n"
                                  "DSEG\n"
                                  "DC\n"
                                  "DCB\n"
                                  "DS\n"
                                  "END\n"
                                  "ENDC\n"
                                  "ENDIF\n"
                                  "ENDM\n"
                                  "EQU\n"
                                  "EQUR\n"
                                  "EVEN\n"
                                  "FAR\n"
                                  "IDNT\n"
                                  "IFC\n"
                                  "IFD\n"
                                  "IFEQ\n"
                                  "IFGE\n"
                                  "IFGT\n"
                                  "IFLE\n"
                                  "IFLT\n"
                                  "IFNC\n"
                                  "IFND\n"
                                  "IFNE\n"
                                  "INCBIN\n"
                                  "INCLUDE\n"
                                  "LIST\n"
                                  "MACRO\n"
                                  "NEAR\n"
                                  "NOLIST\n"
                                  "ORG\n"
                                  "PAGE\n"
                                  "PUBLIC\n"
                                  "REG\n"
                                  "RORG\n"
                                  "SECTION\n"
                                  "SET\n"
                                  "SPC\n"
                                  "TITLE\n"
                                  "TTL\n"
                                  "XDEF\n"
                                  "XREF\n").split('\n',QString::SkipEmptyParts);
  Assembler_Directives_a68k.color=QColor(0,0,255);
  Assembler_Directives_a68k.style=SYNS_CUSTOM|SYNS_BOLD;
  Assembler_Directives_a68k.caseSensitive=false;
  Syn_WordList SWL_Sections;
  SWL_Sections.name="Sections";
  SWL_Sections.list=QString(
                    "$$ACTIONS\n"
                    "$$CONNECTIONS\n"
                    "$$END\n"
                    "$$END_TEST\n"
                    "$$EVENTS\n"
                    "$$EXTERN\n"
                    "$$LOCATIONS\n"
                    "$$MESSAGES\n"
                    "$$OBJECTS\n"
                    "$$OLDSTYLE_SYSTEM_MESSAGES\n"
                    "$$PICTURES\n"
                    "$$PICTURES_TEST\n"
                    "$$SYSTEM_MESSAGES\n"
                    "$$TITLE\n"
                    "$$VOCABULARY\n").split('\n',QString::SkipEmptyParts);
  SWL_Sections.color=QColor(255,0,0);
  SWL_Sections.style=SYNS_CUSTOM|SYNS_BOLD;
  SWL_Sections.caseSensitive=true;
  Syn_WordList Section_Specific_Keywords;
  Section_Specific_Keywords.name="Section-specific Keywords";
  Section_Specific_Keywords.list= QString(
                                  "ACTION\n"
                                  "BITMAP\n"
                                  "CBLOCK\n"
                                  "CONN\n"
                                  "DEFINE\n"
                                  "DRAWING\n"
                                  "END_BITMAP\n"
                                  "END_CBLOCK\n"
                                  "END_DRAWING\n"
                                  "END_PACKED_BITMAP\n"
                                  "EVENT\n"
                                  "FROM\n"
                                  "LOC\n"
                                  "MSG\n"
                                  "OBJ\n"
                                  "PACKED_BITMAP\n"
                                  "WORD\n").split('\n',QString::SkipEmptyParts);
  Section_Specific_Keywords.color=QColor(64,128,128);
  Section_Specific_Keywords.style=SYNS_CUSTOM|SYNS_BOLD;
  Section_Specific_Keywords.caseSensitive=true;
  Syn_WordList AdditionalKeywords;
  AdditionalKeywords.name="Additional Keywords";
  AdditionalKeywords.list=QString(
                          "CONTINUE\n"
                          "ELSE\n").split('\n',QString::SkipEmptyParts);
  AdditionalKeywords.color=QColor(64,128,128);
  AdditionalKeywords.style=SYNS_CUSTOM|SYNS_BOLD;
  AdditionalKeywords.caseSensitive=true;
  Syn_WordList PredefinedAliases;
  PredefinedAliases.name="Predefined Aliases";
  PredefinedAliases.list= QString(
                          "$ALSOSEE\n"
                          "$ARG\n"
                          "$CARRIED\n"
                          "$CENTER\n"
                          "$CNT1\n"
                          "$CNT2\n"
                          "$CNT3\n"
                          "$CNT4\n"
                          "$CONT\n"
                          "$CURLOC\n"
                          "$DARK\n"
                          "$DARKCNT\n"
                          "$DESC\n"
                          "$DESC_CNT\n"
                          "$DESC_DARKCNT\n"
                          "$DESC_NOLIGHTCNT\n"
                          "$DONE\n"
                          "$ENDGAME\n"
                          "$EXIT\n"
                          "$FAIL\n"
                          "$FONT\n"
                          "$FULLSCR\n"
                          "$GCONTROL\n"
                          "$LSOURCE\n"
                          "$MAXCAR\n"
                          "$NOLIGHTCNT\n"
                          "$NOUN\n"
                          "$NOWHERE\n"
                          "$NULL\n"
                          "$NUMCAR\n"
                          "$PROMPT\n"
                          "$RESTART\n"
                          "$SCORE\n"
                          "$SPECIAL\n"
                          "$SUBROUTINE\n"
                          "$TURNHI\n"
                          "$TURNLO\n"
                          "$VERB\n"
                          "$WORN\n").split('\n',QString::SkipEmptyParts);
  PredefinedAliases.color=QColor(128,0,128);
  PredefinedAliases.style=SYNS_CUSTOM|SYNS_BOLD;
  PredefinedAliases.caseSensitive=true;
  Syn_WordList SWL_Conditions;
  SWL_Conditions.name="Conditions";
  SWL_Conditions.list=QString(
                      "ABSENT\n"
                      "AT\n"
                      "ATGT\n"
                      "ATLT\n"
                      "CARRIED\n"
                      "CHANCE\n"
                      "CREATED\n"
                      "EQ\n"
                      "EQWORD\n"
                      "EXTWORD\n"
                      "GT\n"
                      "HERE\n"
                      "ISAT\n"
                      "ISDESC\n"
                      "ISNOTAT\n"
                      "ISNOTNULL\n"
                      "ISNULL\n"
                      "LT\n"
                      "NEQWORD\n"
                      "NOTAT\n"
                      "NOTCARR\n"
                      "NOTCREATED\n"
                      "NOTEQ\n"
                      "NOTHERE\n"
                      "NOTSAME\n"
                      "NOTWORN\n"
                      "NOTZERO\n"
                      "PRESENT\n"
                      "SAME\n"
                      "TRYMOVE\n"
                      "WORN\n"
                      "ZERO\n").split('\n',QString::SkipEmptyParts);
  SWL_Conditions.color=QColor(0,0,255);
  SWL_Conditions.style=SYNS_CUSTOM|SYNS_BOLD;
  SWL_Conditions.caseSensitive=true;
  Syn_WordList SWL_Actions;
  SWL_Actions.name="Actions";
  SWL_Actions.list= QString(
                    "ADD\n"
                    "ALSOSEE\n"
                    "ANYKEY\n"
                    "AUTOD\n"
                    "AUTOG\n"
                    "AUTOR\n"
                    "AUTOW\n"
                    "BIGFONT\n"
                    "CANCEL\n"
                    "CLEAR\n"
                    "CLS\n"
                    "COPYFF\n"
                    "COPYFO\n"
                    "COPYOF\n"
                    "COPYOO\n"
                    "CREATE\n"
                    "DECCAR\n"
                    "DESC\n"
                    "DESTROY\n"
                    "DONE\n"
                    "DROP\n"
                    "DROPALL\n"
                    "END\n"
                    "ENDDESC\n"
                    "EXIT\n"
                    "EXTERN\n"
                    "GET\n"
                    "GETWORD\n"
                    "GOTO\n"
                    "INCCAR\n"
                    "INVEN\n"
                    "LET\n"
                    "LISTAT\n"
                    "LISTOBJ\n"
                    "LOAD\n"
                    "MAXCAR\n"
                    "MES\n"
                    "MESFLAG\n"
                    "MESSAGE\n"
                    "MINUS\n"
                    "NEWLINE\n"
                    "NOTDONE\n"
                    "OK\n"
                    "PAUSE\n"
                    "PICNORM\n"
                    "PICOFF\n"
                    "PICON\n"
                    "PLACE\n"
                    "PLUS\n"
                    "PRINT\n"
                    "PROMPT\n"
                    "PUTO\n"
                    "QUIT\n"
                    "QVERSION\n"
                    "RAMLOAD\n"
                    "RAMSAVE\n"
                    "RANDOM\n"
                    "REDRAW\n"
                    "REMOVE\n"
                    "RESTART\n"
                    "SAVE\n"
                    "SCORE\n"
                    "SET\n"
                    "SETNOUN\n"
                    "SETVERB\n"
                    "SHOWLOC\n"
                    "SMLFONT\n"
                    "SUB\n"
                    "SWAP\n"
                    "SYSMESS\n"
                    "TURNS\n"
                    "WEAR\n"
                    "WHATO\n"
                    "WHEREO\n"
                    "ZAPSCR\n").split('\n',QString::SkipEmptyParts);
  SWL_Actions.color=QColor(0,0,160);
  SWL_Actions.style=SYNS_CUSTOM|SYNS_BOLD;
  SWL_Actions.caseSensitive=true;
  Syn_WordList Drawing_Primitives;
  Drawing_Primitives.name="Drawing primitives";
  Drawing_Primitives.list=QString(
                          "AMOVE\n"
                          "CALL\n"
                          "ELLIPSE\n"
                          "FILL\n"
                          "INV_ELLIPSE\n"
                          "INV_LINE\n"
                          "INV_PLOT\n"
                          "INV_RPLOT\n"
                          "LINE\n"
                          "MOVE\n"
                          "PLOT\n"
                          "RPLOT\n"
                          "SHADE\n"
                          "XOR_ELLIPSE\n"
                          "XOR_LINE\n"
                          "XOR_PLOT\n"
                          "XOR_RPLOT\n").split('\n',QString::SkipEmptyParts);
  Drawing_Primitives.color=QColor(0,64,128);
  Drawing_Primitives.style=SYNS_CUSTOM|SYNS_BOLD;
  Drawing_Primitives.caseSensitive=true;
  Syn_WordList Drawing_Directions;
  Drawing_Directions.name="Drawing directions";
  Drawing_Directions.list=QString(
                          "DOWN\n"
                          "DOWN_LEFT\n"
                          "DOWN_RIGHT\n"
                          "LEFT\n"
                          "LEFT_DOWN\n"
                          "LEFT_UP\n"
                          "RIGHT\n"
                          "RIGHT_DOWN\n"
                          "RIGHT_UP\n"
                          "UP\n"
                          "UP_LEFT\n"
                          "UP_RIGHT\n").split('\n',QString::SkipEmptyParts);
  Drawing_Directions.color=QColor(0,128,0);
  Drawing_Directions.style=SYNS_CUSTOM|SYNS_BOLD;
  Drawing_Directions.caseSensitive=true;
  Syn_WordList Shading_Patterns;
  Shading_Patterns.name="Shading patterns";
  Shading_Patterns.list=QString(
                        "$BKSLASHFILL\n"
                        "$BRICKFILL\n"
                        "$CHAINFILL\n"
                        "$CIRCLEFILL\n"
                        "$CLOSEDASHFILL\n"
                        "$CLOSEDOTFILL\n"
                        "$CLOSEWAVEFILL\n"
                        "$CROSSFILL\n"
                        "$DASHFILL\n"
                        "$DOTFILL\n"
                        "$HATCHFILL\n"
                        "$INTERLEAVEFILL\n"
                        "$LIGHTDOTFILL\n"
                        "$LIGHTLINEFILL\n"
                        "$LINEFILL\n"
                        "$SLASHFILL\n"
                        "$SOLIDFILL\n"
                        "$SQDOTFILL\n"
                        "$SQUAREFILL\n"
                        "$THICKBKSLASHFILL\n"
                        "$THICKHATCHFILL\n"
                        "$THICKLINEFILL\n"
                        "$THICKSLASHFILL\n"
                        "$VDASHFILL\n"
                        "$VINTERLEAVEFILL\n"
                        "$VLDOTFILL\n"
                        "$VLIGHTLINEFILL\n"
                        "$VLINEFILL\n"
                        "$VTHICKLINEFILL\n"
                        "$WAVEFILL\n"
                        "$WIDEDOTFILL\n"
                        "$XMARKFILL\n"
                        "$ZIGZAGFILL\n").split('\n',QString::SkipEmptyParts);
  Shading_Patterns.color=QColor(128,0,128);
  Shading_Patterns.style=SYNS_CUSTOM|SYNS_BOLD;
  Shading_Patterns.caseSensitive=true;
  Syn_WordList NonFunctional_Keywords;
  NonFunctional_Keywords.name="Non-functional keywords";
  NonFunctional_Keywords.list=QString(
                              "BEEP\n"
                              "BLOCK\n"
                              "BORDER\n"
                              "BRIGHT\n"
                              "FLASH\n"
                              "INK\n"
                              "PAPER\n").split('\n',QString::SkipEmptyParts);
  NonFunctional_Keywords.color=QColor(192,192,192);
  NonFunctional_Keywords.style=SYNS_CUSTOM|SYNS_BOLD;
  NonFunctional_Keywords.caseSensitive=true;
  Syn_WordList External_Symbols;
  External_Symbols.name="External symbols";
  External_Symbols.list=QString(
                        "$ACTIONS$\n"
                        "$ARG$\n"
                        "$BMPUT$\n"
                        "$BPCKPUT$\n"
                        "$BUFFER$\n"
                        "$CONNECTIONS$\n"
                        "$EVENTS$\n"
                        "$EXTERN$\n"
                        "$FLAGS$\n"
                        "$FLAGS_BACKUP$\n"
                        "$GDF$\n"
                        "$GETLINE$\n"
                        "$LOCATIONS$\n"
                        "$LQL$\n"
                        "$MAXCAR$\n"
                        "$MESSAGES$\n"
                        "$NFLAG$\n"
                        "$NLOC$\n"
                        "$NMSG$\n"
                        "$NOBJ$\n"
                        "$NSYSMSG$\n"
                        "$NWORD$\n"
                        "$OBJECTS$\n"
                        "$PDRAW$\n"
                        "$PICTURE$\n"
                        "$PRINT$\n"
                        "$RAM_SAVED$\n"
                        "$SCALEX$\n"
                        "$SCALEY$\n"
                        "$SSCR$\n"
                        "$SYSTEM_MESSAGES$\n"
                        "$WORDS$\n").split('\n',QString::SkipEmptyParts);
  External_Symbols.color=QColor(0,128,64);
  External_Symbols.style=SYNS_CUSTOM|SYNS_BOLD;
  External_Symbols.caseSensitive=true;
  
  syn->wordLists.clear();
  if (synIsC)
    syn->wordLists << C_Keywords;
  else if (synIsS)
    syn->wordLists << Data_Movement << Integer_Arithmetic << Logical_Instructions << ShiftRotation_Instructions << Bit_Manipulation << Program_Control << System_Control << SWL_Extensions << Assembler_Directives << SWL_Registers;
  else if (synIsAsm)
    syn->wordLists << Data_Movement_a68k << Integer_Arithmetic << Logical_Instructions << ShiftRotation_Instructions_a68k << Bit_Manipulation << Program_Control_a68k << System_Control << SWL_Extensions << Assembler_Directives_a68k << SWL_Registers;
  else if (synIsQll)
    syn->wordLists << C_Keywords << SWL_Sections << Section_Specific_Keywords << AdditionalKeywords << PredefinedAliases << SWL_Conditions << SWL_Actions << Drawing_Primitives << Drawing_Directions << Shading_Patterns << NonFunctional_Keywords << External_Symbols;
}

static void defaultSynHighlight(void)
{
  resetSyntaxPreference(&(preferences.synC));
  resetSyntaxPreference(&(preferences.synS));
  resetSyntaxPreference(&(preferences.synAsm));
  resetSyntaxPreference(&(preferences.synQll));
  saveSyntaxPreferences();
}

// Update the Kate schema from our internal ones.
static void updateEditorPreferences(void)
{
  KConfig kateschema("kateschemarc");
  KConfigGroup kateNormal=kateschema.group("kate - Normal");
  KConfigGroup ktigccNormal=kateschema.group("ktigcc - Normal");
  QColor color;
  if (preferences.useBgColor) {
    ktigccNormal.writeEntry("Color Background",preferences.bgColor);
    ktigccNormal.writeEntry("Color Highlighted Line",preferences.bgColor);
  } else {
    color=kateNormal.readEntry("Color Background",QColor(255,255,255));
    ktigccNormal.writeEntry("Color Background",color);
    color=kateNormal.readEntry("Color Highlighted Line",QColor(240,240,240));
    ktigccNormal.writeEntry("Color Highlighted Line",color);
  }
  color=kateNormal.readEntry("Color Highlighted Bracket",QColor(255,255,153));
  ktigccNormal.writeEntry("Color Highlighted Bracket",color);
  color=kateNormal.readEntry("Color Icon Bar",QColor(234,233,232));
  ktigccNormal.writeEntry("Color Icon Bar",color);
  color=kateNormal.readEntry("Color Line Number",QColor(0,0,0));
  ktigccNormal.writeEntry("Color Line Number",color);
  color=kateNormal.readEntry("Color MarkType1",QColor(0,0,255));
  ktigccNormal.writeEntry("Color MarkType1",color);
  color=kateNormal.readEntry("Color MarkType2",QColor(255,0,0));
  ktigccNormal.writeEntry("Color MarkType2",color);
  color=kateNormal.readEntry("Color MarkType3",QColor(255,255,0));
  ktigccNormal.writeEntry("Color MarkType3",color);
  color=kateNormal.readEntry("Color MarkType4",QColor(255,0,255));
  ktigccNormal.writeEntry("Color MarkType4",color);
  color=kateNormal.readEntry("Color MarkType5",QColor(160,160,164));
  ktigccNormal.writeEntry("Color MarkType5",color);
  color=kateNormal.readEntry("Color MarkType6",QColor(0,255,0));
  ktigccNormal.writeEntry("Color MarkType6",color);
  color=kateNormal.readEntry("Color MarkType7",QColor(255,0,0));
  ktigccNormal.writeEntry("Color MarkType7",color);
  color=kateNormal.readEntry("Color Selection",QColor(76,89,166));
  ktigccNormal.writeEntry("Color Selection",color);
  color=kateNormal.readEntry("Color Tab Marker",QColor(0,0,0));
  ktigccNormal.writeEntry("Color Tab Marker",color);
  color=kateNormal.readEntry("Color Word Wrap Marker",QColor(120,120,120));
  ktigccNormal.writeEntry("Color Word Wrap Marker",color);
  ktigccNormal.writeEntry("Font",preferences.editorFont);
}

void loadPreferences(void)
{
  // This doesn't really _load_ a preference...
  if (!pconfig->hasGroup("Kate Document Defaults")) {
    KConfigGroup docDefaults=pconfig->group("Kate Document Defaults");
    docDefaults.writeEntry("Tab Handling",0);
    docDefaults.writeEntry("Basic Config Flags",0x1000020u);
    pconfig->sync();
  }

  KConfigGroup config=pconfig->group("Preferences");

  // General
  preferences.stopAtFirstError=config.readEntry("Stop at First Error",false);
  preferences.jumpToError=config.readEntry("Jump to Error",true);
  preferences.successMessage=config.readEntry("Success Message",true);
  preferences.deleteAsmFiles=config.readEntry("Delete Asm Files",true);
  preferences.deleteObjFiles=config.readEntry("Delete Object Files",false);
  preferences.splitSourceFiles=config.readEntry("Split Source Files",true);
  preferences.allowImplicitDeclaration=config.readEntry("Allow Implicit Declaration",true);
  preferences.autoSave=config.readEntry("Auto Save",true);
  preferences.downloadHeadlines=config.readEntry("Download Headlines",false);
  preferences.deleteOverwrittenErrors=config.readEntry("Delete Overwritten Errors",true);
  preferences.useSystemIcons=config.readEntry("Use System Icons",true);

  // Transfer
  preferences.linkTarget=(LinkTargets)config.readEntry("Link Target",(int)LT_NONE);
  preferences.linkPort=(CablePort)config.readEntry("Link Port",(int)PORT_1);
  preferences.linkCable=(CableModel)config.readEntry("Link Cable",(int)CABLE_GRY);
  // Don't allow selecting a USB cable if libticables2 has been compiled without
  // USB support or if USB support can't be used.
  if (!have_usb) {
    if (preferences.linkCable==CABLE_SLV || preferences.linkCable==CABLE_USB) {
      preferences.linkCable=CABLE_GRY;
      preferences.linkTarget=LT_NONE;
    }
  }

  // Editor
  preferences.tabWidthC=config.readEntry("Tab Width C",2u);
  preferences.tabWidthAsm=config.readEntry("Tab Width Asm",8u);
  preferences.useBgColor=config.readEntry("Use Background Color",false);
  preferences.bgColor=config.readEntry("Background Color",QColor(255,255,255));
  preferences.editorFont=config.readEntry("Editor Font",QFont("Monospace",10));
  preferences.useCalcCharset=config.readEntry("Use Calc Charset",true);
  preferences.autoBlocks=config.readEntry("Auto Blocks",true);
  preferences.removeTrailingSpaces=config.readEntry("Remove Trailing Spaces",false);

  updateEditorPreferences();

  // Coding
  if (config.hasKey("Num Coding Templates")) {
    unsigned numTemplates=config.readEntry("Num Coding Templates",0u);
    preferences.templates.clear();
    for (unsigned i=0; i<numTemplates; i++) {
      preferences.templates.append(qMakePair(
        config.readEntry(QString("Coding Template %1 Name").arg(i)),
        config.readEntry(QString("Coding Template %1 Text").arg(i))));
    }
  } else {
    preferences.templates.clear();
    // These are 7-bit ASCII, so either fromLatin1 or fromUtf8 will work.
    // fromLatin1 is probably faster.
    preferences.templates
      << qMakePair(QString::fromLatin1("do"),QString::fromLatin1("do {\n\t|\n} while ();"))
      << qMakePair(QString::fromLatin1("for"),QString::fromLatin1("for (|; ; ) {"))
      << qMakePair(QString::fromLatin1("if"),QString::fromLatin1("if (|) {"))
      << qMakePair(QString::fromLatin1("if else"),QString::fromLatin1("if (|) {\n} else {\n}"))
      << qMakePair(QString::fromLatin1("switch"),QString::fromLatin1("switch (|) {\n\tcase:\n\t\tbreak;\n\n\tdefault:\n\t\tbreak;\n}"))
      << qMakePair(QString::fromLatin1("while"),QString::fromLatin1("while (|) {"));
  }

  // Syntax
  if (!loadSyntaxPreferences())
    defaultSynHighlight();
  checkSynHighlightVersions();
}

void savePreferences(void)
{
  KConfigGroup config=pconfig->group("Preferences");

  // General
  config.writeEntry("Stop at First Error",(bool)preferences.stopAtFirstError);
  config.writeEntry("Jump to Error",(bool)preferences.jumpToError);
  config.writeEntry("Success Message",(bool)preferences.successMessage);
  config.writeEntry("Delete Asm Files",(bool)preferences.deleteAsmFiles);
  config.writeEntry("Delete Object Files",(bool)preferences.deleteObjFiles);
  config.writeEntry("Split Source Files",(bool)preferences.splitSourceFiles);
  config.writeEntry("Allow Implicit Declaration",(bool)preferences.allowImplicitDeclaration);
  config.writeEntry("Auto Save",(bool)preferences.autoSave);
  config.writeEntry("Download Headlines",(bool)preferences.downloadHeadlines);
  config.writeEntry("Delete Overwritten Errors",(bool)preferences.deleteOverwrittenErrors);
  config.writeEntry("Use System Icons",(bool)preferences.useSystemIcons);

  // Transfer
  config.writeEntry("Link Target",(int)preferences.linkTarget);
  config.writeEntry("Link Port",(int)preferences.linkPort);
  config.writeEntry("Link Cable",(int)preferences.linkCable);

  // Editor
  config.writeEntry("Tab Width C",(unsigned)preferences.tabWidthC);
  config.writeEntry("Tab Width Asm",(unsigned)preferences.tabWidthAsm);
  config.writeEntry("Use Background Color",(bool)preferences.useBgColor);
  config.writeEntry("Background Color",preferences.bgColor);
  config.writeEntry("Editor Font",preferences.editorFont);
  config.writeEntry("Use Calc Charset",(bool)preferences.useCalcCharset);
  config.writeEntry("Auto Blocks",(bool)preferences.autoBlocks);
  config.writeEntry("Remove Trailing Spaces",(bool)preferences.removeTrailingSpaces);

  updateEditorPreferences();

  // Coding
  unsigned i=0;
  typedef const QPair<QString,QString> &StringPairConstRef;
  foreach (StringPairConstRef pair, preferences.templates) {
    config.writeEntry(QString("Coding Template %1 Name").arg(i),pair.first);
    config.writeEntry(QString("Coding Template %1 Text").arg(i++),pair.second);
  }
  config.writeEntry("Num Coding Templates",i);

  // Syntax, save to disk
  saveSyntaxPreferences();
}

int showPreferencesDialog(QWidget *parent, bool haveA68k, bool haveQuill)
{
  preferences.haveA68k=haveA68k;
  preferences.haveQuill=haveQuill;
  Preferences *prefdlg=new Preferences(parent);
  prefdlg->exec();
  int result=prefdlg->result();
  delete prefdlg;
  if (result==QDialog::Accepted)
    savePreferences();
  return result;
}
