<?xml version="1.0" encoding="UTF-8"?>

<!-- 
 Copyright (C) 2012 Tobias Marczewski
 Author: Tobias Marczewski <tmarczewski@ed-alumni.net>

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

 This library 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
 Library General Public License for more details.

 You should have received a copy of the GNU Library General Public
 License along with this library; if not, write to the
 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 Boston, MA 02111-1307, USA.

 NOTES ************************************************************************
 For most commands the book "Guide to LaTeX" by H. Kopka and P.W. Daly
 served as a reference (Helmut Kopka and Patrick W. Daly, May 2006,
 Guide to Latex, Fourth Edition, Addison-Wesley, ISBN 0-321-17385-6)
 
 I tried to include most widely used commands that have special structures into
 this language file. This definition will, however, vary as it depends on the
 purpose for which an author uses LaTeX. Furthermore, LaTeX is a very flexible
 language which often makes definitions (in terms of regexes or structures)
 difficult. Much more could be done, but the more complicated a language file
 gets, the easier errors can sneak in and the functionality achived at the
 moment was sufficient for my purposes. Please let me know if errors occur or
 other potentially wrong highlighting can be observed. Also please feel free to
 improve this file; some suggestions are at the bottom of this file.
 I hope this improves your experience while TeX-ing with gedit!
 ******************************************************************************
 -->

<language id="latex" _name="LaTeX" version="2.0" _section="Markup">
  <metadata>
    <property name="mimetypes">text/x-tex</property>
    <property name="globs">*.tex;*.ltx;*.sty;*.cls;*.dtx;*.ins;*.bbl</property>
    <property name="line-comment-start">%</property>
  </metadata>

  <styles>
    <style id="error"           _name="Error"             map-to="def:error"/>
    <style id="comment"         _name="Comment"           map-to="def:comment"/>
    <style id="verbatim"        _name="Verbatim"          map-to="def:doc-comment"/>
    <style id="special-char"    _name="Special Character" map-to="def:special-char"/>

    <style id="usepackage"      _name="Usepackage"        map-to="def:preprocessor"/>
    <style id="documentclass"   _name="Documentclass"     map-to="def:preprocessor"/>
    <style id="item"            _name="Item"              map-to="def:identifier"/>
    <style id="begin-end-env"   _name="Environment"       map-to="def:statement"/>

    <style id="command"         _name="Command"           map-to="def:function"/>
    <style id="common-command"  _name="Command"           map-to="def:function"/>
    <style id="structure"       _name="Structure"         map-to="def:keyword"/>
    <style id="spacing"         _name="Spacing"           map-to="def:function"/>
    <style id="referencing"     _name="Referencing"       map-to="def:builtin"/>
    <style id="font-style"      _name="Font Style"        map-to="def:function"/>
    <style id="math-command"    _name="Math Command"      map-to="def:function"/>
    <style id="graphics"        _name="Graphics"          map-to="def:function"/>

    <style id="options"         _name="Attributes"        map-to="def:special-constant"/>
    <style id="arguments"       _name="Attributes"/>
    <style id="label"           _name="Attributes"        map-to="def:string"/>

    <!-- names, e.g., name of package, name of environment, name of class -->
    <style id="name"            _name="Attributes"        map-to="def:character"/>
    <style id="sub-superscript" _name="Sub-Superscript"   map-to="def:floating-point"/>
    <style id="in-environ"      _name="Environment"/>
    <!-- style inside the make-@ environment (@-letter, @-other) -->
    <style id="make-at"         _name="Make At"/>
    <!-- footnote/caption style applying to whole expression, i.e. to set a background -->
    <style id="footnote"        _name="Footnote"/>
    <style id="caption"         _name="Caption"/>
    
    <style id="math-mode-delim" _name="Math Mode"/>
    <style id="text-math"       _name="Math Mode"         map-to="def:type"/>
    <style id="display-math"    _name="Math Mode"         map-to="def:type"/>
  </styles>

  <definitions>

    <context id="latex">
      <include>

        <context ref="preamble-commands"/>
        <context id="latex-text">
          <include>
            <context ref="comment"/>
            <context ref="special-char"/>
            <context ref="math-mode"/>
            <context ref="spacing"/>
            <context ref="referencing"/>
            <!-- <context ref="math-only-in-text"/> [see line 630] -->
            <context ref="environ"/>
            <context ref="command-opt-arg"/>
          </include>
        </context>

      </include>
    </context>

  <!-- 1) ************************* Commenting ***************************** -->
    <context id="comment">
      <include>
    <!-- normal comment -->
        <context id="end-line-comment" style-ref="comment">
          <start>%</start> <end>$</end>
            <include> <context ref="def:in-comment"/> </include>
        </context>
    <!-- comment env -->
        <context id="verbatim-comment" style-ref="comment" style-inside="true">
          <start>(\\begin)\{(comment)\}</start>
          <end>(\\end)\{(\%{2@start})\}</end>
            <include> 
              <context sub-pattern="1" where="start" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="start" style-ref="name"/>
              <context sub-pattern="1" where="end" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="end" style-ref="name"/>
              <context ref="def:in-comment"/>
            </include>
        </context>
    <!-- Verbatim -->
        <context id="verbatim-env" style-ref="verbatim" style-inside="true">
          <start>(\\begin)\{(verbatim\*?|lstlisting|alltt)\}</start>
          <end>(\\end)\{(\%{2@start})\}</end>
            <include> 
              <context sub-pattern="1" where="start" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="start" style-ref="name"/>
              <context sub-pattern="1" where="end" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="end" style-ref="name"/>
            </include>
        </context>
    <!-- Verbatim inline -->
        <context id="verbatim-inline" style-ref="verbatim">
          <start>\\(verb\*?|lstinline)(\S)</start>
          <end>\%{2@start}</end>
        </context>
      </include>
    </context>


  <!-- 2) ************************ Special Symbols ************************* -->
    <define-regex id="accents" extended="true">
      (\\(                                      #leading backslash
         (                                      #1-Accents-
          [bcdHruv\.\^'`~"=]                    #  accent symbol
          \s*\{([a-zA-Z] | \\i | \\j)\} |       #  letter (\i \j for i,j without dot)
          [\.\^'`~"=]\s*([a-zA-Z] | \\i | \\j) |#  non-letter accents without braces
          t\s*\{([a-zA-Z] | \\i | \\j){2}\}     #  special accent over two letters
         ) | (                                  #2-Special letters-
          (aa|AA | ae|AE | oe|OE | ss|SS |      #  letters followed by a non-word
          [oO] | [lL])(?=\W)                    #  character or e.g. \l causes 
         )                                      #  unwanted behaviour (i.e. \label)
        )) | (!` | \?`)                         #3-Spanish punctuation
    </define-regex>

    <!-- double backslash (\\'new line') will not be included here, as it is used
         as a spacing command, see there.
         Carefull here with the '#' as it is used to indicate comments
         when an extended=true is used -->
    <define-regex id="command-symbols">\\(\$|%|\^|&amp;|_|\{|\}|#|~)</define-regex>

    <context id="special-char">
      <include>
      <!-- Include accents here before the escaped command symbols because for
           example the hat (^) can be used as an accent and will be placed over
           the following letter (e.g. \^o will NOT produce ^o) -->
        <context id="accents" style-ref="special-char">
          <match>\%{accents}</match>
        </context>
        <context id="command-symbols" style-ref="special-char">
          <match>\%{command-symbols}</match>
        </context>
      </include>
    </context>


  <!-- 3) **************************** Commands **************************** -->

    <!-- [3, a] Commands in preamble ________________________________________-->
    <context id="preamble-commands">
      <include>
      <!-- Different colouring of options and package name in "usepackage" -->
        <context id="usepackage">
          <match>(\\usepackage)(\[(.*)\])?\{([0-9a-zA-Z,\s]+)\}(\[(.*)\])?</match>
            <include>
              <context sub-pattern="1" style-ref="usepackage"/>
              <context sub-pattern="3" style-ref="options"/>
              <context sub-pattern="4" style-ref="name"/>
              <context sub-pattern="6" style-ref="verbatim"/>
            </include>
        </context>
      <!-- Enable different colouring in "documentclass" -->
        <context id="documentclass">
          <match>(\\documentclass)(\[(.*)\])?\{([a-zA-Z]+)\}</match>
            <include>
              <context sub-pattern="1" style-ref="documentclass"/>
              <context sub-pattern="3" style-ref="options"/>
              <context sub-pattern="4" style-ref="name"/>
            </include>
        </context>
      <!-- exclude text within \begin{document} from 'in environment' -->
        <context id="begin-end-document">
          <start>(\\begin)\{(document)\}</start>
          <end>\s*(\\end)\{(\%{2@start})\}</end>
            <include>
              <context sub-pattern="1" where="start" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="start" style-ref="name"/>
              <context sub-pattern="1" where="end" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="end" style-ref="name"/>
              <context ref="latex-text"/>
            </include>
        </context>
      
      </include>
    </context>

    <!-- [3, b] Spacing commands (including line/pagebreaks) ________________-->
    <define-regex id="spacing" extended="true">
      \\(                                    #leading backslash
        (no)?(line|page)break(\[[1-4]\])?|   #'line/page-breaks'
        \\\*?                                #'new line' and optional: asterisk;
         (\[-?\d+([\.,]\d{1,2})?             #number, perhaps with decimals;
         (cm|mm|in|pt|bp|pc|dd|cc|em|ex)\])?|#allowed length units.
        (v|h)space\*?\{-?\d+([\.,]\d{1,2})?  #'vertical/horizontal space'
         (cm|mm|in|pt|bp|pc|dd|cc|em|ex) \}  #same pattern as "new line"
      )
    </define-regex>
    
    <context id="spacing">
      <include>
        <context id="spacing-1" style-ref="spacing">
          <match>\%{spacing}</match>
        </context>
        <!-- include \@ as it enforces spacing with regards to punctuation -->
        <context id="spacing-2" style-ref="spacing">
          <match>\\@(?=\W)</match>
        </context>
        
        <context id="spacing-keywords" style-ref="spacing">
          <prefix>\\</prefix>
          <suffix>(?=\b)</suffix> <!-- for security: demand a word-boundry -->
            <keyword>clear(double)?page</keyword>
            <keyword>new(page|line)</keyword>
            <keyword>(no)?indent</keyword>
            <keyword>(v|h)?fill</keyword>
            <keyword>q{1,2}uad</keyword>
            <keyword>(big|med|small)skip</keyword>
            <keyword>xspace</keyword>
        </context>
        
        <context id="small-space" style-ref="spacing">
          <match>\\,</match>
        </context>
        
        <context id="space-no-break" style-ref="spacing">
          <match>~</match>
        </context>
        
      </include>
    </context>
    

    <!-- [3, c] Labelling and referencing commands __________________________-->
    <define-regex id="referencing" extended="true">
      \\(
        label|(auto)?(page)?ref\*?|  #internal references
        cite(d\*? | p\*?)?           #citations
      )
    </define-regex>
    
    <context id="referencing">
      <include>
        <context id="label">
          <start>(\%{referencing})(?!\w)</start>
          <end>(?=.)</end>
            <include>
              <context sub-pattern="0" where="start" style-ref="referencing"/>
              <context ref="options"/>
              <context ref="arguments" style-ref="label"/>
              <context ref="comment"/>
            </include>
        </context>
        
        <context id="footnote" style-ref="footnote">
          <start>\\footnote\b</start>
          <end>(?=.)</end>
            <include>
              <context sub-pattern="0" where="start" style-ref="referencing"/>
              <context ref="comment"/>
              <context id="footnote-text" style-ref="arguments"
                       style-inside="true" once-only="true">
                <start>\s*\{</start> <end>\}</end>
                  <include> 
                    <context ref="latex-text"/>
                    <context ref="arguments" ignore-style="true"/>
                  </include>
              </context>
            </include>
        </context>
        
        <context id="caption" style-ref="caption">
          <start>\\caption\b</start>
          <end>(?=.)</end>
            <include>
              <context sub-pattern="0" where="start" style-ref="referencing"/>
              <context ref="options"/>
              <context ref="arguments"/>
              <context ref="comment"/>
            </include>
        </context>
      </include>
    </context>
    
    <!-- ___________________________________________________________________ -->
    <!-- Declarations that change global variables, and counter related -->
    <define-regex id="declarations" extended="true">
       \\(                                             # leading backslash
         (new|set|addto|step|use)counter|pagenumbering|
         (this)?pagestyle|(new|set)length|
         ((re)?new|provide)command|newsavebox|
         value|arabic|[rR]oman|[aA]lph|fnsymbol|       # counter related
         include(only)?|input|                         # include command
         (make)?title|author|date                      # misc
       )(?=\b)
    </define-regex>
    <!-- environment to allow internal function identifier @ as letter -->
    <context id="make-at" style-ref="make-at" end-parent="true">
      <start>\\makeatletter\b</start>
      <end>\\makeatother</end>
        <include>
          <context sub-pattern="0" where="start" style-ref="common-command"/>
          <context sub-pattern="0" where="end" style-ref="common-command"/>
          <context ref="latex"/>
        </include>
    </context>
    
    <!-- Document structure -->
    <define-regex id="structure" extended="true">
       \\(                                                    #leading backslash
         (part|chapter|(sub){0,3}section|(sub)?paragraph)\*?| #chapters
         appendix|(front|main|back)matter|                    #others
         tableofcontents|listof(figures|tables)               #lists
       )(?=\b)
    </define-regex>
    <!-- Font settings -->
    <define-regex id="font-style" extended="true">
       \\(
          tiny | (script|footnote|normal)size | small | #Text Size
          (l|L)arge | LARGE | (h|H)uge |
          (rm|tt|sf)family | text(rm|tt|sf) |           #Family
          (up|it|sl|sc)shape | text(up|it|sl|sc) |      #Shape
          (md|bf)series | text(md|bf) |                 #Series
          textnormal | emph                             #Other
       )(?=\b)
    </define-regex>
    <!-- General command syntax -->
    <define-regex id="command" extended="true">
      \\[a-zA-Z@]+\*?
    </define-regex>

    <context id="commands" once-only="true">
      <start>(?=\%{command})</start>
      <!-- FIXME For some reason this 'start' structure,
           along with setting all contained contexts to end-parent,
           was necessary to use once-only="true" -->
      <include>
        <context ref="make-at"/>
        <context id="declarations" style-ref="common-command" end-parent="true">
          <match>\%{declarations}</match>
        </context>
        <context id="structure" style-ref="structure" end-parent="true">
          <match>\%{structure}</match>
        </context>
        <context id="font-style" style-ref="font-style" end-parent="true">
          <match>\%{font-style}</match>
        </context>
        <context id="command" style-ref="command" end-parent="true">
          <match>\%{command}</match>
        </context>
      </include>
    </context>

    <!-- Contents in squared brackets, normally options -->
    <context id="options" style-ref="options" once-only="true" style-inside="true">
      <start>\s*\[</start>
      <end>\]</end>
        <include>
          <context ref="comment"/>
          <context ref="special-char"/>
          <context ref="spacing"/>
          <context ref="command-opt-arg"/>
          <context ref="text-math-mode"/>
        </include>
    </context>
    <!-- Can appear twice e.g. in \newcommand, then the first [] is the number
         of arguments for the defined command. -->
    <context id="narg" once-only="true">
      <match>\s*\[(\d+)\]</match>
        <include>
          <context sub-pattern="1" style-ref="options"/>
        </include>
    </context>

    <!-- Contents in curly brackets, normally arguments -->
    <context id="arguments" style-ref="arguments" style-inside="true">
      <start>\s*\{</start>
      <end>\}</end>
        <include>
          <context ref="comment"/>
          <context ref="special-char"/>
          <context ref="spacing"/>
          <context ref="referencing"/>
          <context ref="command-opt-arg"/>
          <context ref="math-mode"/>
          <!-- allow curly bracketing inside arguments -->
          <context ref="arguments" ignore-style="true"/>
        </include>
    </context>

<!-- ################ Command/Escape sequence for functions ############### -->
    <!-- Commands/Identifiers that would match, but have to be excluded: -->
    <define-regex id="exclude-command" extended="true">
      \\(
         begin | end |   # environment identifiers
         item |          # special defined elsewhere
         makeatother     # ends the "makeatletter environment"
      )\b                # demand a word boundry to ensure exact command
    </define-regex>

    <context id="command-opt-arg">
      <start>(?=\%{command})(?!\%{exclude-command})</start>
      <end>(?=.)</end>
        <include>
          <context ref="comment"/>
          <context ref="graphics"/>
          <context ref="commands"/>
          <context ref="narg"/>
          <context ref="options"/>
          <context ref="arguments"/>
        </include>
    </context>

<!-- _______________________________________________________________________ -->
<!-- ### Graphics ### -->
    <define-regex id="graphics" extended="true">
       \\(                                                    #leading backslash
         graphicspath|DeclareGraphics[A-Z][a-zA-Z]*
       )(?=\b)
    </define-regex>
    
    <context id="includegraphics">
      <start>\\includegraphics\*?</start>
      <include>
        <context sub-pattern="0" where="start" style-ref="graphics"/>
      <!-- \includegraphics[][]{} %graphics [] in form of [llx,lly][urx,ury] -->
        <context id="includegraphic-s">
          <match>\[(\s*[a-zA-Z0-9]+\s*,\s*[a-zA-Z0-9]+\s*)\]</match>
            <include>
              <context sub-pattern="1" style-ref="options"/>
            </include>
        </context>
      <!-- \includegraphics[]{}   %graphix [] in form of key=value -->
        <context id="includegraphic-x" once-only="true" end-parent="true">
          <start>\[</start> <end>\]</end>
            <include>
              <context ref="command-opt-arg"/>
              <context id="includegraphicx-key" style-ref="options">
                <match>[a-zA-Z]+</match>
              </context>
              <context id="includegraphicx-value" style-ref="arguments"
                       style-inside="true">
                <start>=</start> <end>(,|(?=\]))</end>
                  <include>
                    <context ref="command-opt-arg"/>
                  </include>
              </context>
            </include>
        </context>
        <context id="filename" style-ref="name" style-inside="true"
                 once-only="true" end-parent="true">
          <start>\{</start> <end>\}</end>
        </context>
      </include>
    </context>
    
    <context id="graphics">
      <include>
        <context id="graphics-keywords" style-ref="graphics">
          <match>\%{graphics}</match>
        </context>
        <context ref="includegraphics"/>
      </include>
    </context>


  <!-- 4) *************************** Math Mode **************************** -->

    <!-- Math-mode commands (commands exclusive to math mode) -->
    <define-regex id="math-command" extended="true">
      \\(
        frac | sqrt | sum | (co)?prod | o?int |           #-Functions
        infty | (c|d|v)dots | nonumber |                  #-special in math mode
        mathnormal | math(rm|sf|tt|it|bf|cal) |           #-Math font commands
        (display|text|script(script)?)style |             #-Math size commands
        alpha | beta | (g|G)amma | (d|D)elta |            #-Greek letters
        (var)?epsilon | zeta | eta | ((vart)|t|T)heta |   ##
        iota | kappa | (l|L)ambda | mu | nu | (x|X)i |    ##
        ((varp)|p|P)i | (var)?rho | ((vars)|s|S)igma |    ##
        tau | (u|U)psilon | ((varp)|p|P)hi | chi |        ##
        (p|P)si | (o|O)mega |                             ##
        pm | mp | times | div | cdot | ast | star |       #-Binary operators
        dd?agger | amalg | (sq)?c(a|u)p | uplus | vee |   ##
        wedge | o(plus|minus|times) | (big)?circ |        ##
        bullet | (d|D)iamond | (un)?(l|r)hd |             ##
        o(slash|dot) | Box | bigtriangle(up|down) |       ##
        triangle(left|right) | setminus | wr |            ##
        gets | to | ((u|U)p(down)? | (d|D)own)arrow |     #-Arrows and pointers
        ((l|L)eft(right)?|(r|R)ight)arrow | (long)mapsto |##
        hook(left|right)arrow | (ne|se|sw|nw)arrow |      ##
        (left|right)harpoon(up|down) | rightleftharpoons |##
        (l|L)ong(left(right)?|right)arrow |               ##
        (wide)hat | check | dd?ot | breve | acute |       #-Accents in math mode
        grave | bar | vec | (wide)tilde | mathring |      ##
        (over|under)(line|brace) | (i|j)math |            ##i, j  dots removed
        (arc)?(cosh?|sinh?|tanh?) | arg | coth? | csc |   #-Function names
        deg | det | dim | exp | gcd | hom | inf | ker |   ##
        lg | lim(inf|sup)? | ln | log | max | min | Pr |  ##
        sec | sup                                         ##
      )(?=\b)
    </define-regex>

    <!-- most commands are not allowed in math mode, highlight them... -->
    <context id="commands-in-math" once-only="true">
      <start>(?=\%{command})</start>
      <!-- FIXME For some reason this 'start' structure,
           along with setting all contained contexts to end-parent,
           was necessary to use once-only="true" -->
      <include>
        <context id="math-command" style-ref="math-command" end-parent="true">
          <match>\%{math-command}</match>
        </context>
        <context ref="declarations" style-ref="error"/>
        <context ref="structure" style-ref="error"/>
        <context ref="font-style"/>
        <context ref="command"/>
      </include>
    </context>

    <!-- Use separate escape sequence for math commands:
         math commands do not have options (square brackets),
         and a separate argument context has to be used to not include
         other commands when inside a math environment. -->
    <context id="math-command-opt-arg">
      <start>(?=\%{command})(?!\\(begin|end)\b)</start>
      <end>(?=.)</end>
        <include>
          <context ref="commands-in-math"/>
          <context id="math-args">
            <start>\s*\{</start>
            <end>\}</end>
              <include>
                <context ref="in-math-mode"/>
              </include>
          </context>
        </include>
    </context>

    <!-- ____________Contexts that can only appear in math mode____________ -->
    <context id="math-only">
      <include>
      <!-- ### Spacing only availlable in math mode ### -->
        <context id="in-math-spacing" style-ref="spacing">
          <match>\\[;:!]</match>
        </context>
      <!-- ### Sized brackets ### -->
        <context id="math-brackets" style-ref="math-command">
          <match extended="true">
            \\(left | right | [bB]igg?[lr])  (      # bracket size specifier
              \(|\) | \[|\] | \\\{|\\\}   |         # normal brackets (curly escaped)
              \|  |  \\\|  |  /  |  \\backslash |   # pipe and slashes
              \\(                                   #-symbol commands
                [lr]floor | [lr]ceil | [lr]angle |  ##
                ([uU]p(down)?|[dD]own)arrow         ##
              )                                     ##
            )
          </match>
        </context>
      <!-- ### Exponents (raised) and indices (lowered) ###
           using a start-end syntax to include commands-->
        <context id="exponent">
          <include>
            <!-- sub/superscript enclosed by brackets -->
            <context id="exponent1" style-ref="sub-superscript">
              <start>((_|\^)\s*\{)</start>
              <end>\}</end>
                <include>
                  <context ref="exponent"/>
                  <context ref="math-command-opt-arg"/>
                </include>
            </context>
            <!-- simple sub/superscript, one character -->
            <context id="exponent2" style-ref="sub-superscript">
              <match>[_\^]\s*[0-9a-zA-Z]</match>
            </context>
            <!-- simple sub/superscript, character is function -->
            <context id="exponent3" style-ref="sub-superscript">
              <start>[_\^]\s*(?=\%{command})</start>
              <end>(?=.)</end>
                <include>
                  <context ref="math-command-opt-arg:*"/>
                </include>
            </context>
          </include>
        </context>
        
      </include>
    </context>

    <!-- originally the math symbols where supposed to be included as errors
         in the normal text (context id=latex) by just including them with:
         <context ref="math-only" style-ref="error"/>
         this, however, doesn't work for some reason, and the following context
         is used as a workaround FIXME
         XXX NOTE: This seems to cause too many problems with custom defined
         commands/structures - therefore commented out! -->
<!--    <context id="math-only-in-text">
      <include>
        <context ref="in-math-spacing" style-ref="error"/>
        <context ref="math-brackets" style-ref="error"/>
        <context ref="math-command" style-ref="error"/>
        <context id="unallowed-structures" style-ref="error">
          <start extended="true">
            (?&lt;!\\)(_|\^)  |  # exponents only in math mode
            \\begin\{array\}
          </start>
        </context>
      </include>
    </context>  -->

    <context id="in-math-mode">
      <include>
        <!-- Error - empty line NOT allowed in math mode -->
        <context id="math-empty-line" style-ref="error">
          <start>^\s*$$</start>
        </context>
        <context ref="comment"/>
        <context ref="command-symbols"/>
        <!-- colour ampersand even when not escaped (e.g. column identfier) -->
        <context id="col-sep-ampersand" style-ref="spacing">
          <match>&amp;</match>
        </context>
        <context ref="accents" style-ref="error"/>
        <context ref="spacing"/>
        <context ref="referencing"/>
        <context ref="math-only"/>
        <context ref="environ-in-math"/>
        <context ref="math-command-opt-arg"/>
      </include>
    </context>

    <!-- ##################### Math mode environments ##################### -->
    <context id="math-mode">
      <include>
        <context ref="text-math-mode"/>
        <context ref="display-math-mode"/>
      </include>
    </context>

    <!-- Text Math -->
    <context id="text-math-mode">
      <include>
        <context id="text-math-mode1" style-ref="text-math">
          <start>(\\begin)\{(math)\}</start>
          <end>(\\end)\{(\%{2@start})\}</end>
            <include>
              <context sub-pattern="1" where="start" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="start" style-ref="name"/>
              <context sub-pattern="1" where="end" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="end" style-ref="name"/>
              <context ref="in-math-mode"/>
            </include>
        </context>
        <context id="text-math-mode2" style-ref="text-math">
          <start>\$(?!\$)</start> <!-- exclude display math $$ -->
          <end>\$</end>
            <include>
              <context sub-pattern="0" where="start" style-ref="math-mode-delim"/>
              <context sub-pattern="0" where="end" style-ref="math-mode-delim"/>
              <context ref="in-math-mode"/>
            </include>
        </context>
        <context id="text-math-mode3" style-ref="text-math">
          <start>\\\(</start>
          <end>\\\)</end>
            <include>
              <context sub-pattern="0" where="start" style-ref="math-mode-delim"/>
              <context sub-pattern="0" where="end" style-ref="math-mode-delim"/>
              <context ref="in-math-mode"/>
            </include>
        </context>
      </include>
    </context>

    <!-- Display Math -->
    <context id="display-math-mode">
      <include>
        <context id="display-math-mode1" style-ref="display-math">
          <start>(\\begin)\{(displaymath|equation\*?|align\*?|eqnarray\*?)\}</start>
          <end>\s*(\\end)\{(\%{2@start})\}</end>
            <include>
              <context sub-pattern="1" where="start" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="start" style-ref="name"/>
              <context sub-pattern="1" where="end" style-ref="begin-end-env"/>
              <context sub-pattern="2" where="end" style-ref="name"/>
              <context ref="in-math-mode"/>
            </include>
        </context>
        <context id="display-math-mode2" style-ref="display-math">
          <start>\$\$</start>
          <end>\$\$</end>
            <include>
              <context sub-pattern="0" where="start" style-ref="math-mode-delim"/>
              <context sub-pattern="0" where="end" style-ref="math-mode-delim"/>
              <context ref="in-math-mode"/>
            </include>
        </context>
        <context id="display-math-mode3" style-ref="display-math">
          <start>\\\[</start>
          <end>\\\]</end>
            <include>
              <context sub-pattern="0" where="start" style-ref="math-mode-delim"/>
              <context sub-pattern="0" where="end" style-ref="math-mode-delim"/>
              <context ref="in-math-mode"/>
            </include>
        </context>
      </include>
    </context>

    <!-- environment when in math mode
        (otherwise math only will show up as errors) -->
    <context id="environ-in-math">
      <start>(\\begin)\{([a-zA-Z]+\*?)\}</start>
      <end>\s*(\\end)\{(\%{2@start})\}</end>
        <include>
          <context sub-pattern="1" where="start" style-ref="begin-end-env"/>
          <context sub-pattern="2" where="start" style-ref="name"/>
          <context sub-pattern="1" where="end" style-ref="begin-end-env"/>
          <context sub-pattern="2" where="end" style-ref="name"/>
          <context ref="options"/>
          <context ref="tab-col-def"/>
          <context ref="col-sep-ampersand"/>
          <context ref="comment"/>
          <context ref="command-symbols"/>
          <context ref="math-only"/>
          <context ref="spacing"/>
          <context ref="referencing"/>
          <context ref="command-opt-arg"/>
          <context ref="environ-in-math"/>
        </include>
    </context>


    <!-- ####################### Other Environments ####################### -->

    <!-- Column parameters (argument) for tabular environment
         column delimitation in array, tabular, longtable... environments -->
    
    <context id="tab-col-def" once-only="true">
      <start>\s*\{</start>
      <end>\}</end>
        <include>
          <context ref="comment"/>
        <!-- separators -->
          <!-- column separation by pipe (line) -->
          <context id="col-sep-pipe" style-ref="verbatim">
            <match>\|</match>
          </context>
          <!-- column separation by at-expression (text) -->
          <context id="col-sep-at">
            <start>@\{</start>
            <end>\}</end>
            <include>
              <context sub-pattern="0" where="start" style-ref="verbatim"/>
              <context sub-pattern="0" where="end" style-ref="verbatim"/>
              <context ref="col-sep-pipe"/>
              <context ref="comment"/>
              <context ref="special-char"/>
              <context ref="math-mode"/>
              <context ref="spacing"/>
              <!-- <context ref="math-only-in-text"/> [see line 630] -->
              <context ref="command-opt-arg"/>
            </include>
          </context>
        <!-- define multiple columns (*) -->
          <context id="star-cols">
            <start>(\*\{)\d+(\}\{)</start>
            <end>\}</end>
            <include>
              <context sub-pattern="1" where="start" style-ref="verbatim"/>
              <context sub-pattern="2" where="start" style-ref="verbatim"/>
              <context sub-pattern="0" where="end" style-ref="verbatim"/>
              <context ref="col-sep-pipe"/>
              <context ref="col-sep-at"/>
              <context ref="col-decl"/>
            </include>
          </context>
        <!-- add declaration before {decl}> or/and after <{decl} column-->
          <context id="col-decl">
            <start>(&lt;|&gt;)\{</start>
            <end>\}</end>
            <include>
              <context sub-pattern="0" where="start" style-ref="verbatim"/>
              <context sub-pattern="0" where="end" style-ref="verbatim"/>
              <context ref="comment"/>
              <context ref="command-opt-arg"/>
            </include>
          </context>
        </include>
    </context>

    <!-- General environment structure -->
    <context id="environ"> <!--style-ref="in-environ"-->
      <start>(\\begin)\{([a-zA-Z]+\*?)\}</start>
      <end>\s*(\\end)\{(\%{2@start})\}</end>
        <include>
          <context sub-pattern="1" where="start" style-ref="begin-end-env"/>
          <context sub-pattern="2" where="start" style-ref="name"/>
          <context sub-pattern="1" where="end" style-ref="begin-end-env"/>
          <context sub-pattern="2" where="end" style-ref="name"/>
          <context ref="options"/>
          <context ref="tab-col-def"/>
          <context ref="item"/>
          <context ref="col-sep-ampersand"/>
          <context ref="latex-text"/>
        </include>
    </context>

    <!-- Item  >> special structure for \item -->
    <context id="item">
      <start>(\\(sub){0,2}item\b)</start>
      <end>(?=(\\(sub){0,2}item|\\end|\\begin)\b)</end>
        <include>
          <context sub-pattern="1" where="start" style-ref="item"/>
          <!--optional name/identifier of the item -->
          <context once-only="true" style-ref="options" style-inside="true">
            <start>\s*\[</start>
            <end>(?=\])</end>
              <include>
                <context ref="comment"/>
                <context ref="special-char"/>
                <context ref="spacing"/>
                <context ref="referencing"/>
                <context ref="text-math-mode"/>
                <context ref="display-math-mode2" style-ref="error"/>
                <context ref="display-math-mode3" style-ref="error"/>
                <context ref="command-opt-arg"/>
              </include>
          </context>
          <!-- item text (in curly brackets) -->
          <context id="item-text-brackets" style-ref="arguments"
                   style-inside="true" once-only="true" end-parent="true">
            <start>\s*\{</start>
            <end>\}</end>
              <include>
                <context ref="latex-text"/>
              </include>
          </context>
          <context id="item-text-no-brackets" style-ref="arguments"
                   once-only="true" end-parent="true">
            <start>.(?!\s*\{)</start>
            <end>(?=(\\(sub){0,2}item|\\end|\\begin)\b)</end>
              <include> <context ref="item-text-brackets:*"/> </include>
          </context>
        </include>
    </context>
    
  </definitions>
</language>



<!-- TODO commands to be included ??

==logical==
%package{ifthen}
\ifthenelse{test}{then}{else}
\whiledo{test}{do}
\isodd{}
\equal{1}{2}
\lengthtest{relation}  % relation [a x b] x:<, >, =
\newboolean{<str>}
\setboolean{<str>}{<val>}
\boolean{<str>}
\and
\or
\not
\(
\)

==Paragraph formatting==
\parskip
\parindent
\baseline(skip|stretch)
\text(width|height)
\linewidth
\setlength
\(odd|even)sidemargin
\topmargin
\headhight
\headsep
\(top|foot)skip
\paper(width|height)
==arrays and tables
\array(colsep|rulewidth|stretch)

==CODING==
-preamble-
\At(Begin|End)Documentclass
\AtEndOf(Class|Package)

Keywords:
plus minus (see p.25)

-->
