{- This module was generated from data in the Kate syntax
   highlighting file mathematica.xml, version 8.1, by Sven Brauch (svenbrauch@gmail.com) -}

module Text.Highlighting.Kate.Syntax.Mathematica
          (highlight, parseExpression, syntaxName, syntaxExtensions)
where
import Text.Highlighting.Kate.Types
import Text.Highlighting.Kate.Common
import Text.ParserCombinators.Parsec hiding (State)
import Control.Monad.State
import Data.Char (isSpace)
import qualified Data.Set as Set

-- | Full name of language.
syntaxName :: String
syntaxName = "Mathematica"

-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.nb"

-- | Highlight source code using this syntax definition.
highlight :: String -> [SourceLine]
highlight input = evalState (mapM parseSourceLine $ lines input) startingState

parseSourceLine :: String -> State SyntaxState SourceLine
parseSourceLine = mkParseSourceLine (parseExpression Nothing)

-- | Parse an expression using appropriate local context.
parseExpression :: Maybe (String,String)
                -> KateParser Token
parseExpression mbcontext = do
  (lang,cont) <- maybe currentContext return mbcontext
  result <- parseRules (lang,cont)
  optional $ do eof
                updateState $ \st -> st{ synStPrevChar = '\n' }
                pEndLine
  return result

startingState = SyntaxState {synStContexts = [("Mathematica","Normal")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = False, synStCaptures = []}

pEndLine = do
  updateState $ \st -> st{ synStPrevNonspace = False }
  context <- currentContext
  contexts <- synStContexts `fmap` getState
  st <- getState
  if length contexts >= 2
    then case context of
      _ | synStContinuation st -> updateState $ \st -> st{ synStContinuation = False }
      ("Mathematica","Normal") -> return ()
      _ -> return ()
    else return ()

withAttribute attr txt = do
  when (null txt) $ fail "Parser matched no text"
  updateState $ \st -> st { synStPrevChar = last txt
                          , synStPrevNonspace = synStPrevNonspace st || not (all isSpace txt) }
  return (attr, txt)

list_functions = Set.fromList $ words $ "a abeliangroup all arcsinh abort allowgroupclose arctan abortkernels allowreversegroupclose arctanh abortprotect alphachannel arg abs alternatinggroup argmax absolutecurrentvalue alternativehypothesis argmin absolutedashing alternatives arithmeticgeometricmean absolutefilename anchoredsearch array absoluteoptions and arraycomponents absolutepointsize andersondarlingtest arraydepth absolutethickness angerj arrayflatten absolutetime anglebracket arraypad absolutetiming animate arrayplot accountingform animationdirection arrayq accumulate animationdisplaytime arrayrules accuracy animationrate arrow accuracygoal animationrepetitions arrowheads actionmenu animationrunning aspectratio activestyle animator assert acyclicgraphq annotation assuming addto annuity assumptions adjacencygraph annuitydue astronomicaldata adjacencymatrix antialiasing asynchronous adjustmentbox apart atomq affinetransform apartsquarefree attributes airyai appearance augmentedsymmetricpolynomial airyaiprime appearanceelements autoaction airyaizero appellf1 autoindent airybi append autoitalicwords airybiprime appendto automatic airybizero apply automultiplicationsymbol algebraicintegerq arccos autorunsequencing algebraicnumber arccosh autoscroll algebraicnumberdenominator arccot autospacing algebraicnumbernorm arccoth axes algebraicnumberpolynomial arccsc axesedge algebraicnumbertrace arccsch axeslabel algebraics arcsec axesorigin algebraicunitq arcsech axesstyle alignment arcsin axis alignmentpoint arcsindistribution b babymonstergroupb betaregularized booleangraph back betweennesscentrality booleanmaxterms background beziercurve booleanminimize backslash bezierfunction booleanminterms backward bilateralfilter booleans band binarize booleantable barabasialbertgraphdistribution binaryformat booleanvariables barchart binaryimageq borderdimensions barchart3d binaryread boreltannerdistribution barnesg binaryreadlist bottom barorigin binarywrite bottomhattransform barspacing bincounts boundarystyle baseform binlists boxdata baseline binomial boxed baselineposition binomialdistribution boxmatrix basestyle binormaldistribution boxratios batesdistribution biorthogonalsplinewavelet boxstyle battlelemariewavelet bipartitegraphq boxwhiskerchart because birnbaumsaundersdistribution bracketingbar beckmanndistribution bitand braycurtisdistance beep bitclear breadthfirstscan begin bitget break begindialogpacket bitlength brown beginpackage bitnot brownforsythetest bellb bitor bsplinebasis belly bitset bsplinecurve benforddistribution bitshiftleft bsplinefunction beninidistribution bitshiftright bsplinesurface benktandergibratdistribution bitxor bubblechart benktanderweibulldistribution black bubblechart3d bernoullib blank bubblescale bernoullidistribution blanknullsequence bubblesizes bernoulligraphdistribution blanksequence butterflygraph bernsteinbasis blend button besseli block buttonbar besselj blockrandom buttonbox besseljzero blue buttondata besselk blur buttonframe bessely bodeplot buttonfunction besselyzero bold buttonminheight beta bookmarks buttonnotebook betabinomialdistribution boole buttonsource betadistribution booleanconvert byte betanegativebinomialdistribution booleancountingfunction bytecount betaprimedistribution booleanfunction byteordering c c citydata continuousaction callpacket clear continuoustimemodelq canberradistance clearall continuouswaveletdata cancel clearattributes continuouswavelettransform cancelbutton clearsystemcache contourdetect candlestickchart clebschgordan contourlabels cap clickpane contourplot capform clip contourplot3d capitaldifferentiald clippingstyle contours carmichaellambda clock contourshading cases close contourstyle cashflow closekernels contraharmonicmean casoratian closenesscentrality control catalan closing controlactive catalannumber clusteringcomponents controllabilitygramian catch cmykcolor controllabilitymatrix cauchydistribution coefficient controllabledecomposition cayleygraph coefficientarrays controllablemodelq cdf coefficientlist controllerinformation cdfwavelet coefficientrules controllerlinking ceiling coifletwavelet controllermanipulate cell collect controllermethod cellautooverwrite colon controllerpath cellbaseline colorcombine controllerstate cellchangetimes colorconvert controlplacement cellcontext colordata controlsrendering celldingbat colordatafunction controltype celldynamicexpression colorfunction convergents celleditduplicate colorfunctionscaling conversionrules cellepilog colorize convolve cellevaluationduplicate colornegate conwaygroupco1 cellevaluationfunction colorquantize conwaygroupco2 celleventactions colorrules conwaygroupco3 cellframe colorseparate coordinatestooloptions cellframemargins colorsetter coprimeq cellgroup colorslider coproduct cellgroupdata colorspace copuladistribution cellgrouping column copyable celllabel columnalignments copydirectory celllabelautodelete columnlines copyfile cellmargins columnsequal copytoclipboard cellopen columnspacings cornerfilter cellprint columnwidths cornerneighbors cellprolog commonest correlation celltags commonestfilter correlationdistance cellularautomaton compilationoptions cos censoreddistribution compilationtarget cosh censoring compile coshintegral center compiled cosinedistance centerdot compiledfunction cosintegral centralmoment complement cot centralmomentgeneratingfunction completegraph coth cform completegraphq count champernownenumber completekarytree countroots chanvesebinarize complex countrydata character complexes covariance characterencoding complexexpand covarianceestimatorfunction characteristicfunction complexinfinity cramervonmisestest characteristicpolynomial complexityfunction createarchive characterrange componentmeasurements createdialog characters composelist createdirectory chartbasestyle composeseries createdocument chartelementfunction composition createintermediatedirectories chartelements compoundexpression createpalette chartlabels compress createscheduledtask chartlayout condition createwindow chartlegends conditionalexpression criticalsection chartstyle conditioned cross chebyshevt cone crossingdetect chebyshevu confidencelevel crossmatrix check congruent csc checkabort conjugate csch checkbox conjugatetranspose cubics checkboxbar conjunction cuboid chemicaldata connectedcomponents cumulant chessboarddistance connectedgraphq cumulantgeneratingfunction chidistribution conovertest cup chineseremainder constant cupcap chisquaredistribution constantarray currentimage choicebuttons constants currentvalue choicedialog contentpadding curvatureflowfilter choleskydecomposition contentselectable curveclosed chop contentsize cyan circle context cyclegraph circledot contexts cycles circleminus contexttofilename cyclicgroup circleplus continue cyclotomic circletimes continuedfraction cylinder circulantgraph continuedfractionk cylindricaldecomposition d d depthfirstscan diskmatrix dagumdistribution derivative dispatch dameraulevenshteindistance derivativefilter dispersionestimatorfunction darker designmatrix displayallsteps dashed det displayendpacket dashing dgaussianwavelet displayform datadistribution diagonal displayfunction datarange diagonalmatrix displaypacket datareversed dialog distancefunction datedifference dialoginput distancetransform datefunction dialognotebook distribute datelist dialogprolog distributed datelistlogplot dialogreturn distributedcontexts datelistplot dialogsymbols distributedefinitions datepattern diamond distributionchart dateplus diamondmatrix distributionfittest datestring dicedissimilarity distributionparameterassumptions dateticksformat dictionarylookup distributionparameterq daubechieswavelet differencedelta divide davisdistribution differenceroot divideby dawsonf differencerootreduce dividers debruijngraph differences divisible declarepackage differentiald divisors decompose differentialroot divisorsigma decrement differentialrootreduce divisorsum dedekindeta digitblock dmslist default digitcharacter dmsstring defaultaxesstyle digitcount do defaultbasestyle digitq dockedcells defaultboxstyle dihedralgroup documentnotebook defaultbutton dilation dot defaultduplicatecellstyle dimensions dotdashed defaultduration diraccomb dotequal defaultelement diracdelta dotted defaultfacegridsstyle directededge doublebracketingbar defaultfieldhintstyle directededges doubledownarrow defaultframestyle directedgraph doubleleftarrow defaultframeticksstyle directedgraphq doubleleftrightarrow defaultgridlinesstyle directedinfinity doublelongleftarrow defaultlabelstyle direction doublelongleftrightarrow defaultmenustyle directive doublelongrightarrow defaultnewcellstyle directory doublerightarrow defaultoptions directoryname doubleuparrow defaultticksstyle directoryq doubleupdownarrow defer directorystack doubleverticalbar definition dirichletcharacter downarrow degree dirichletconvolve downarrowbar degreecentrality dirichletdistribution downarrowuparrow degreegraphdistribution dirichletl downleftrightvector deinitialization dirichlettransform downleftteevector del discreteconvolve downleftvector deletable discretedelta downleftvectorbar delete discreteindicator downrightteevector deletebordercomponents discretelqestimatorgains downrightvector deletecases discretelqregulatorgains downrightvectorbar deletecontents discretelyapunovsolve downteearrow deletedirectory discreteplot downvalues deleteduplicates discreteplot3d draganddrop deletefile discreteratio drop deletesmallcomponents discretericcatisolve dsolve delimiter discreteshift dt delimiterflashtime discretetimemodelq dualsystemsmodel denominator discreteuniformdistribution dumpsave densityhistogram discretewaveletdata dynamic densityplot discretewaveletpackettransform dynamicevaluationtimeout dependentvariables discretewavelettransform dynamicmodule deploy discriminant dynamicmodulevalues deployed disjunction dynamicsetting depth disk dynamicwrapper e e end exactnumberq edgeadd enddialogpacket exampledata edgecount endoffile except edgecoverq endofline excludedforms edgedelete endofstring excludepods edgedetect endpackage exclusions edgeform engineeringform exclusionsstyle edgeindex enterexpressionpacket exists edgelabeling entertextpacket exit edgelabels entropy exp edgelist entropyfilter expand edgeq environment expandall edgerenderingfunction epilog expanddenominator edgerules equal expandfilename edgeshapefunction equaltilde expandnumerator edgestyle equilibrium expectation edgeweight equivalent expgammadistribution editable erf expintegrale editdistance erfc expintegralei effectiveinterest erfi exponent eigensystem erlangdistribution exponentfunction eigenvalues erosion exponentialdistribution eigenvectorcentrality errorbox exponentialfamily eigenvectors estimateddistribution exponentialgeneratingfunction element estimatorgains exponentialmovingaverage elementdata estimatorregulator exponentialpowerdistribution eliminate euclideandistance exponentstep elliptice eulere export ellipticexp eulergamma exportstring ellipticexpprime euleriangraphq expression ellipticf eulerphi expressioncell elliptick evaluatable exptotrig ellipticlog evaluate extendedgcd ellipticnomeq evaluatepacket extension ellipticpi evaluationelements extentelementfunction elliptictheta evaluationmonitor extentmarkers ellipticthetaprime evaluationnotebook extentsize emitsound evaluationobject extract empiricaldistribution evaluator extractarchive emptygraphq evenq extremevaluedistribution enabled eventhandler encode eventlabels f faceform findfit formbox facegrids findgeneratingfunction fortranform facegridsstyle findgeolocation forward factor findgeometrictransform forwardbackward factorial findgraphisomorphism fourier factorial2 findhamiltoniancycle fouriercoefficient factorialmoment findindependentedgeset fouriercoscoefficient factorialmomentgeneratingfunction findindependentvertexset fouriercosseries factorialpower findinstance fouriercostransform factorinteger findintegernullvector fourierdct factorlist findlibrary fourierdst factorsquarefree findlinearrecurrence fourierparameters factorsquarefreelist findlist fouriersequencetransform factorterms findmaximum fourierseries factortermslist findmaxvalue fouriersincoefficient false findminimum fouriersinseries feedbacktype findminvalue fouriersintransform fibonacci findpermutation fouriertransform fieldhint findroot fouriertrigseries fieldhintstyle findsequencefunction fractionalpart fieldmasked findshortestpath fractionbox fieldsize findshortesttour frame filebasename findthreshold framebox filebytecount findvertexcover framed filedate finishdynamic framelabel fileexistsq finiteabeliangroupcount framemargins fileextension finitegroupcount framestyle fileformat finitegroupdata frameticks filehash first frameticksstyle filenamedepth fischergroupfi22 fratiodistribution filenamedrop fischergroupfi23 frechetdistribution filenamejoin fischergroupfi24prime freeq filenames fisherhypergeometricdistribution fresnelc filenamesetter fisherratiotest fresnels filenamesplit fisherzdistribution frobeniusnumber filenametake fit frobeniussolve fileprint fittedmodel fromcharactercode filetype fixedpoint fromcoefficientrules filledcurve fixedpointlist fromcontinuedfraction filling flat fromdigits fillingstyle flatten fromdms fillingtransform flattenat front filterrules flipview frontenddynamicexpression financialbond floor frontendeventactions financialdata fold frontendexecute financialderivative foldlist frontendtoken financialindicator fontcolor frontendtokenexecute find fontfamily full findargmax fontsize fulldefinition findargmin fontslant fullform findclique fontsubstitutions fullgraphics findclusters fonttracking fullsimplify findcurvepath fontvariations function finddistributionparameters fontweight functionexpand finddivisions for functioninterpolation findedgecover forall functionspace findeuleriancycle format findfile formattype g gaborwavelet geopositionxyz graphstyle gainmargins geoprojectiondata graphunion gainphasemargins get gray gamma glaisher graylevel gammadistribution glow greater gammaregularized goldenratio greaterequal gappenalty gompertzmakehamdistribution greaterequalless gather goto greaterfullequal gatherby gradient greatergreater gaussianfilter gradientfilter greaterless gaussianintegers graph greaterslantequal gaussianmatrix graphcenter greatertilde gcd graphcomplement green gegenbauerc graphdata grid general graphdiameter gridbox generalizedlinearmodelfit graphdifference griddefaultelement generateconditions graphdisjointunion gridgraph generatedcell graphdistance gridlines generatedparameters graphdistancematrix gridlinesstyle generatingfunction graphhighlight groebnerbasis genericcylindricaldecomposition graphhighlightstyle groupactionbase genomedata graphics groupcentralizer genomelookup graphics3d groupelementposition geodesicdilation graphicscolumn groupelementq geodesicerosion graphicscomplex groupelements geodestination graphicsgrid groupgenerators geodesydata graphicsgroup groupmultiplicationtable geodirection graphicsrow grouporbits geodistance graphintersection grouporder geogridposition graphlayout grouppagebreakwithin geometricdistribution graphperiphery groupsetwisestabilizer geometricmean graphplot groupstabilizer geometricmeanfilter graphplot3d groupstabilizerchain geometrictransformation graphpower gudermannian geoposition graphq gumbeldistribution geopositionenu graphradius h haarwavelet hermitianmatrixq hue halfnormaldistribution hessenbergdecomposition humpdownhump hamiltoniangraphq hexadecimalcharacter humpequal hammingdistance highlightgraph hurwitzlerchphi hankelh1 higmansimsgrouphs hurwitzzeta hankelh2 hilbertmatrix hyperbolicdistribution hankelmatrix histogram hypercubegraph haradanortongrouphn histogram3d hyperfactorial hararygraph histogramdistribution hypergeometric0f1 harmonicmean histogramlist hypergeometric0f1regularized harmonicmeanfilter hitmisstransform hypergeometric1f1 harmonicnumber hitscentrality hypergeometric1f1regularized hash hold hypergeometric2f1 haversine holdall hypergeometric2f1regularized hazardfunction holdallcomplete hypergeometricdistribution head holdcomplete hypergeometricpfq heads holdfirst hypergeometricpfqregularized heavisidelambda holdform hypergeometricu heavisidepi holdpattern hyperlink heavisidetheta holdrest hyphenation heldgrouphe hornerform hypothesistestdata hermitedecomposition hotellingtsquaredistribution hermiteh hoytdistribution i i importstring interrupt identity in intersection identitymatrix incidencegraph interval if incidencematrix intervalintersection ignorecase includeconstantbasis intervalmemberq im includepods intervalunion image increment inverse imageadd independentedgesetq inversebetaregularized imageadjust independentvertexsetq inversecdf imagealign indeterminate inversechisquaredistribution imageapply indexgraph inversecontinuouswavelettransform imageaspectratio inexactnumberq inversedistancetransform imageassemble infinity inverseellipticnomeq imagecapture infix inverseerf imagechannels information inverseerfc imageclip inherited inversefourier imagecolorspace initialization inversefouriercostransform imagecompose initializationcell inversefouriersequencetransform imageconvolve inner inversefouriersintransform imagecooccurrence inpaint inversefouriertransform imagecorrelate input inversefunction imagecorrespondingpoints inputaliases inversefunctions imagecrop inputassumptions inversegammadistribution imagedata inputautoreplacements inversegammaregularized imagedeconvolve inputfield inversegaussiandistribution imagedifference inputform inversegudermannian imagedimensions inputnamepacket inversehaversine imageeffect inputnotebook inversejacobicd imagefilter inputpacket inversejacobicn imageforestingcomponents inputstream inversejacobics imageforwardtransformation inputstring inversejacobidc imagehistogram inputstringpacket inversejacobidn imagekeypoints insert inversejacobids imagelevels insertresults inversejacobinc imagelines inset inversejacobind imagemargins install inversejacobins imagemultiply installservice inversejacobisc imagepad instring inversejacobisd imagepadding integer inversejacobisn imagepartition integerdigits inverselaplacetransform imageperspectivetransformation integerexponent inversepermutation imageq integerlength inverseradon imagereflect integerpart inverseseries imageresize integerpartitions inversesurvivalfunction imageresolution integerq inversewavelettransform imagerotate integers inverseweierstrassp imagescaled integerstring inverseztransform imagesize integrate invisible imagesizeaction interactivetradingchart irreduciblepolynomialq imagesizemultipliers interleaving isolatinginterval imagesubtract internallybalanceddecomposition isomorphicgraphq imagetake interpolatingfunction isotopedata imagetransformation interpolatingpolynomial italic imagetrim interpolation item imagetype interpolationorder itemaspectratio imagevalue interpretation itemsize implies interpretationbox itemstyle import interquartilerange j jaccarddissimilarity jacobins jankogroupj4 jacobiamplitude jacobip jarqueberaalmtest jacobicd jacobisc johnsondistribution jacobicn jacobisd join jacobics jacobisn joined jacobidc jacobisymbol joinedcurve jacobidn jacobizeta joinform jacobids jankogroupj1 jordandecomposition jacobinc jankogroupj2 jordanmodeldecomposition jacobind jankogroupj3 k kagichart kelvinker kolmogorovsmirnovtest kalmanestimator kernelmixturedistribution kroneckerdelta karhunenloevedecomposition kernelobject kroneckerproduct karytree kernels kroneckersymbol katzcentrality khinchin kuipertest kcorecomponents kirchhoffgraph kumaraswamydistribution kdistribution kirchhoffmatrix kurtosis kelvinbei kleininvariantj kuwaharafilter kelvinber knighttourgraph kelvinkei knotdata l label libraryfunction listdensityplot labeled libraryfunctionerror listinterpolation labelingfunction libraryfunctioninformation listlineintegralconvolutionplot labelstyle libraryfunctionload listlineplot laguerrel libraryfunctionunload listloglinearplot landaudistribution libraryload listloglogplot languagecategory libraryunload listlogplot laplacedistribution liftingfilterdata listplay laplacetransform liftingwavelettransform listplot laplacianfilter lightblue listplot3d laplaciangaussianfilter lightbrown listpointplot3d large lightcyan listpolarplot larger lighter liststreamdensityplot last lightgray liststreamplot latitude lightgreen listsurfaceplot3d latitudelongitude lighting listvectordensityplot latticedata lightingangle listvectorplot latticereduce lightmagenta listvectorplot3d launchkernels lightorange localizevariables layeredgraphplot lightpink locationequivalencetest layersizefunction lightpurple locationtest lcm lightred locator leafcount lightyellow locatorautocreate leastsquares likelihood locatorpane left limit locatorregion leftarrow limitspositioning locked leftarrowbar lindleydistribution log leftarrowrightarrow line log10 leftdownteevector linearfractionaltransform log2 leftdownvector linearmodelfit logbarnesg leftdownvectorbar linearoffsetfunction loggamma leftrightarrow linearprogramming loggammadistribution leftrightvector linearrecurrence logicalexpand leftteearrow linearsolve logintegral leftteevector linearsolvefunction logisticdistribution lefttriangle linebreakchart logitmodelfit lefttrianglebar linegraph loglikelihood lefttriangleequal lineindent loglinearplot leftupdownvector lineindentmaxfraction loglogisticdistribution leftupteevector lineintegralconvolutionplot loglogplot leftupvector lineintegralconvolutionscale lognormaldistribution leftupvectorbar linespacing logplot leftvector linkclose logseriesdistribution leftvectorbar linkconnect longest legendappearance linkcreate longestcommonsequence legended linkfunction longestcommonsubsequence legendrep linkinterrupt longitude legendreq linklaunch longleftarrow length linkobject longleftrightarrow lengthwhile linkpatterns longrightarrow lerchphi linkprotocol loopfreegraphq less linkread lowercaseq lessequal linkreadyq lowerleftarrow lessequalgreater links lowerrightarrow lessfullequal linkwrite lowertriangularize lessgreater liouvillelambda lqestimatorgains lessless list lqgregulator lessslantequal listable lqoutputregulatorgains lesstilde listanimate lqregulatorgains lettercharacter listcontourplot lucasl letterq listcontourplot3d ludecomposition level listconvolve lyapunovsolve levenetest listcorrelate lyonsgrouply levicivitatensor listcurvepathplot levydistribution listdeconvolve m machinenumberq maxdetect mindetect machineprecision maxextrabandwidths minfilter magenta maxextraconditions minimalpolynomial magnification maxfilter minimalstatespacemodel magnify maximize minimize majority maxiterations minors makeboxes maxmemoryused minstabledistribution makeexpression maxmixturekernels minus mangoldtlambda maxplotpoints minusplus manhattandistance maxrecursion minvalue manipulate maxstabledistribution missing manipulator maxstepfraction mixturedistribution mannwhitneytest maxsteps mod mantissaexponent maxstepsize modal manual maxvalue modularlambda map maxwelldistribution module mapall mclaughlingroupmcl modulus mapat mean moebiusmu mapindexed meandeviation moment mapthread meanfilter momentconvert marcumq meanshift momentevaluate mardiacombinedtest meanshiftfilter momentgeneratingfunction mardiakurtosistest median monitor mardiaskewnesstest mediandeviation monomiallist marginaldistribution medianfilter monstergroupm masking medium morletwavelet matchingdissimilarity meijerg morphologicalbinarize matchlocalnames memberq morphologicalbranchpoints matchq memoryconstrained morphologicalcomponents mathieuc memoryinuse morphologicaleulernumber mathieucharacteristica menucommandkey morphologicalgraph mathieucharacteristicb menupacket morphologicalperimeter mathieucharacteristicexponent menusortingvalue morphologicaltransform mathieucprime menustyle most mathieugroupm11 menuview mouseannotation mathieugroupm12 mesh mouseappearance mathieugroupm22 meshfunctions mouseover mathieugroupm23 meshshading mouseposition mathieugroupm24 meshstyle movingaverage mathieus message movingmedian mathieusprime messagedialog moyaldistribution mathmlform messagelist multiedgestyle matrixexp messagename multinomial matrixform messagepacket multinomialdistribution matrixplot messages multinormaldistribution matrixpower method multiplicativeorder matrixq mexicanhatwavelet multivariatehypergeometricdistribution matrixrank meyerwavelet multivariatepoissondistribution max min multivariatetdistribution n n normalizedsquaredeuclideandistance notprecedesslantequal nakagamidistribution normalsfunction notprecedestilde nameq normfunction notreverseelement names not notrighttriangle nand notcongruent notrighttrianglebar nargmax notcupcap notrighttriangleequal nargmin notdoubleverticalbar notsquaresubset ncache notebook notsquaresubsetequal ndsolve notebookapply notsquaresuperset nearest notebookautosave notsquaresupersetequal nearestfunction notebookclose notsubset needlemanwunschsimilarity notebookdelete notsubsetequal needs notebookdirectory notsucceeds negative notebookdynamicexpression notsucceedsequal negativebinomialdistribution notebookevaluate notsucceedsslantequal negativemultinomialdistribution notebookeventactions notsucceedstilde neighborhoodgraph notebookfilename notsuperset nest notebookfind notsupersetequal nestedgreatergreater notebookget nottilde nestedlessless notebookinformation nottildeequal nestlist notebooklocate nottildefullequal nestwhile notebookobject nottildetilde nestwhilelist notebookopen notverticalbar nevillethetac notebookprint nprobability nevillethetad notebookput nproduct nevillethetan notebookread nroots nevillethetas notebooks nsolve nexpectation notebooksave nsum nextprime notebookselection null nholdall notebookwrite nullrecords nholdfirst notelement nullspace nholdrest notequaltilde nullwords nicholsgridlines notexists number nicholsplot notgreater numberfieldclassnumber nintegrate notgreaterequal numberfielddiscriminant nmaximize notgreaterfullequal numberfieldfundamentalunits nmaxvalue notgreatergreater numberfieldintegralbasis nminimize notgreaterless numberfieldnormrepresentatives nminvalue notgreaterslantequal numberfieldregulator nominalvariables notgreatertilde numberfieldrootsofunity noncentralbetadistribution nothumpdownhump numberfieldsignature noncentralchisquaredistribution nothumpequal numberform noncentralfratiodistribution notlefttriangle numberformat noncentralstudenttdistribution notlefttrianglebar numbermarks noncommutativemultiply notlefttriangleequal numbermultiplier nonconstants notless numberpadding none notlessequal numberpoint nonlinearmodelfit notlessfullequal numberq nonnegative notlessgreater numberseparator nonpositive notlessless numbersigns nor notlessslantequal numberstring norlundb notlesstilde numerator norm notnestedgreatergreater numericfunction normal notnestedlessless numericq normaldistribution notprecedes nyquistgridlines normalize notprecedesequal nyquistplot o o operate outputform observabilitygramian operatingsystem outputnamepacket observabilitymatrix optional outputresponse observabledecomposition options outputsizelimit observablemodelq optionspattern outputstream oddq optionvalue overbar off or overdot offset orange overflow on order overhat onangroupon orderdistribution overlaps oneidentity orderedq overlay opacity ordering overscript openappend orderless overscriptbox opener orthogonalize overtilde openerview out overvector opening outer owent openread outputcontrollabilitymatrix ownvalues openwrite outputcontrollablemodelq p packingmethod permutationlist popupmenu paddedform permutationlistq popupview padding permutationmax popupwindow padeapproximant permutationmin position padleft permutationorder positive padright permutationpower positivedefinitematrixq pagebreakabove permutationproduct possiblezeroq pagebreakbelow permutationreplace postfix pagebreakwithin permutations power pagefooters permutationsupport powerdistribution pageheaders permute powerexpand pagerankcentrality peronamalikfilter powermod pagewidth pertdistribution powermodlist pairedbarchart petersengraph powersrepresentations pairedhistogram phasemargins powersymmetricpolynomial pairedttest pi precedenceform pairedztest pick precedes palettenotebook piecewise precedesequal pane piecewiseexpand precedesslantequal panel piechart precedestilde paneled piechart3d precision paneselector pink precisiongoal paraboliccylinderd pixelconstrained predecrement paragraphindent pixelvalue preemptprotect paragraphspacing placed prefix parallelarray placeholder preincrement parallelcombine placeholderreplace prepend paralleldo plain prependto parallelevaluate play preserveimageoptions parallelization playrange pricegraphdistribution parallelize plot prime parallelmap plot3d primenu parallelneeds plotlabel primeomega parallelproduct plotlayout primepi parallelsubmit plotmarkers primepowerq parallelsum plotpoints primeq paralleltable plotrange primes paralleltry plotrangeclipping primezetap parameterestimator plotrangepadding primitiveroot parametermixturedistribution plotregion principalcomponents parametricplot plotstyle principalvalue parametricplot3d plus print parentdirectory plusminus printingstyleenvironment paretodistribution pochhammer printtemporary part podstates probability particledata podwidth probabilitydistribution partition point probabilityplot partitionsp pointfigurechart probabilityscaleplot partitionsq pointsize probitmodelfit pascaldistribution poissonconsuldistribution product passeventsdown poissondistribution productdistribution passeventsup polaraxes productlog paste polaraxesorigin progressindicator pastebutton polargridlines projection path polarplot prolog pathgraph polarticks properties pathgraphq polezeromarkers property pattern polyaaepplidistribution propertylist patternsequence polygamma propertyvalue patterntest polygon proportion paulimatrix polyhedrondata proportional paulwavelet polylog protect pause polynomialextendedgcd protected pdf polynomialgcd proteindata pearsonchisquaretest polynomiallcm pruning pearsondistribution polynomialmod pseudoinverse performancegoal polynomialq purple permutationcycles polynomialquotient put permutationcyclesq polynomialquotientremainder putappend permutationgroup polynomialreduce permutationlength polynomialremainder q qbinomial qrdecomposition quartiles qfactorial quadraticirrationalq quartileskewness qgamma quantile quiet qhypergeometricpfq quantileplot quit qpochhammer quartics quotient qpolygamma quartiledeviation quotientremainder r radicalbox refreshrate rightarrowbar radiobutton regionbinarize rightarrowleftarrow radiobuttonbar regionfunction rightcosetrepresentative radon regionplot rightdownteevector ramanujantau regionplot3d rightdownvector ramanujantaul regularexpression rightdownvectorbar ramanujantautheta regularization rightteearrow ramanujantauz releasehold rightteevector randomchoice reliefimage righttriangle randomcomplex reliefplot righttrianglebar randomgraph remove righttriangleequal randomimage removealphachannel rightupdownvector randominteger removeproperty rightupteevector randompermutation removescheduledtask rightupvector randomprime renamedirectory rightupvectorbar randomreal renamefile rightvector randomsample renkochart rightvectorbar randomvariate repeated rogerstanimotodissimilarity range repeatednull root rangefilter replace rootapproximant rankedmax replaceall rootintervals rankedmin replacelist rootlocusplot raster replacepart rootmeansquare rasterize replacerepeated rootofunityq rastersize resampling rootreduce rational rescale roots rationalize rescalingtransform rootsum rationals resetdirectory rotate ratios resetscheduledtask rotatelabel rawboxes residue rotateleft rawdata resolve rotateright rayleighdistribution rest rotationaction re resultant rotationmatrix read resumepacket rotationtransform readlist return round readprotected returnexpressionpacket roundingradius real returnpacket row realblockdiagonalform returntextpacket rowalignments realdigits reverse rowbox realexponent reversebiorthogonalsplinewavelet rowlines reals reverseelement rowminheight reap reverseequilibrium rowreduce record reversegraph rowsequal recordlists reverseupequilibrium rowspacings recordseparators revolutionaxis rsolve rectangle revolutionplot3d rudvalisgroupru rectanglechart rgbcolor rule rectanglechart3d riccatisolve ruledelayed recurrencetable ricedistribution run red ridgefilter runscheduledtask reduce riemannr runthrough referencelinestyle riemannsiegeltheta runtimeattributes refine riemannsiegelz runtimeoptions reflectionmatrix riffle russellraodissimilarity reflectiontransform right refresh rightarrow s sameq sin stationarywaveletpackettransform sametest sinc stationarywavelettransform sampledepth singhmaddaladistribution statusarea sampledsoundfunction singleletteritalics stepmonitor sampledsoundlist singularvaluedecomposition stieltjesgamma samplerate singularvaluelist stirlings1 samplingperiod singularvalueplot stirlings2 satisfiabilitycount sinh stopscheduledtask satisfiabilityinstances sinhintegral streamcolorfunction satisfiableq sinintegral streamcolorfunctionscaling save sixjsymbol streamdensityplot savedefinitions skeleton streamplot sawtoothwave skeletontransform streampoints scale skellamdistribution streamposition scaled skewness streams scalingfunctions skewnormaldistribution streamscale scalingmatrix skip streamstyle scalingtransform slider string scan slider2d stringcases scheduledtaskobject slideview stringcount scheduledtasks slot stringdrop schurdecomposition slotsequence stringexpression scientificform small stringform screenstyleenvironment smallcircle stringformat scriptbaselineshifts smaller stringfreeq scriptminsize smithwatermansimilarity stringinsert scriptsizemultipliers smoothdensityhistogram stringjoin scrollbars smoothhistogram stringlength scrollposition smoothhistogram3d stringmatchq sec smoothkerneldistribution stringposition sech sokalsneathdissimilarity stringq sechdistribution solve stringreplace sectorchart solvealways stringreplacelist sectorchart3d sort stringreplacepart sectororigin sortby stringreverse sectorspacing sound stringskeleton seedrandom soundnote stringsplit select soundvolume stringtake selectable sow stringtostream selectcomponents spacer stringtrim selectednotebook spacings structuredselection selectionanimate span struveh selectioncreatecell spanfromabove struvel selectionevaluate spanfromboth stub selectionevaluatecreatecell spanfromleft studenttdistribution selectionmove sparsearray style selfloopstyle speak stylebox semialgebraiccomponentinstances specularity styledata sendmail spellingcorrection styledefinitions sequence sphere subfactorial sequencealignment sphericalbesselj subgraph sequencehold sphericalbessely subminus series sphericalhankelh1 subplus seriescoefficient sphericalhankelh2 subresultants seriesdata sphericalharmonicy subscript sessiontime sphericalplot3d subscriptbox set sphericalregion subset setaccuracy spheroidaleigenvalue subsetequal setalphachannel spheroidaljoiningfactor subsets setattributes spheroidalps substar setdelayed spheroidalpsprime subsuperscript setdirectory spheroidalqs subsuperscriptbox setfiledate spheroidalqsprime subtract setoptions spheroidalradialfactor subtractfrom setprecision spheroidals1 succeeds setproperty spheroidals1prime succeedsequal setselectednotebook spheroidals2 succeedsslantequal setsharedfunction spheroidals2prime succeedstilde setsharedvariable splice suchthat setstreamposition splineclosed sum setsystemoptions splinedegree sumconvergence setter splineknots superdagger setterbar splineweights superminus setting split superplus shallow splitby superscript shannonwavelet spokenstring superscriptbox shapirowilktest sqrt superset share sqrtbox supersetequal sharpen square superstar shearingmatrix squaredeuclideandistance survivaldistribution shearingtransform squarefreeq survivalfunction short squareintersection suspendpacket shortdownarrow squaresr suzukidistribution shortest squaresubset suzukigroupsuz shortestpathfunction squaresubsetequal switch shortleftarrow squaresuperset symbol shortrightarrow squaresupersetequal symbolname shortuparrow squareunion symletwavelet show squarewave symmetricgroup showautostyles stabilitymargins symmetricmatrixq showcellbracket stabilitymarginsstyle symmetricpolynomial showcelllabel stabledistribution symmetricreduction showcelltags stack synchronousinitialization showcursortracker stackbegin synchronousupdating showgroupopener stackcomplete syntaxinformation showpagebreaks stackinhibit syntaxlength showselection standarddeviation syntaxpacket showspecialcharacters standarddeviationfilter syntaxq showstringcharacters standardform systemdialoginput shrinkingdelay standardize systeminformation siegeltheta star systemopen siegeltukeytest stargraph systemoptions sign startingstepsize systemsmodeldelete signature startofline systemsmodeldimensions signedranktest startofstring systemsmodelextract significancelevel startscheduledtask systemsmodelfeedbackconnect signpadding statefeedbackgains systemsmodellabels signtest stateoutputestimator systemsmodelorder similarityrules stateresponse systemsmodelparallelconnect simplegraph statespacemodel systemsmodelseriesconnect simplegraphq statespacerealization systemsmodelstatefeedbackconnect simplify statespacetransform t table tilde traceon tablealignments tildeequal traceoriginal tabledepth tildefullequal traceprint tabledirections tildetilde tracescan tableform timeconstrained trackedsymbols tableheadings timeconstraint tradingchart tablespacing times traditionalform tabview timesby transferfunctioncancel tagbox timeused transferfunctionexpand taggingrules timevalue transferfunctionfactor tagset timezone transferfunctionmodel tagsetdelayed timing transferfunctionpoles tagunset tiny transferfunctionzeros take titsgroupt transformationfunction takewhile toboxes transformationfunctions tally tocharactercode transformationmatrix tan tocontinuoustimemodel transformeddistribution tanh todiscretetimemodel translate targetfunctions toeplitzmatrix translationtransform tautologyq toexpression transparent temporary together transpose texform toggler treeform text togglerbar treegraph textalignment tokenwords treegraphq textcell tolerance treeplot textclipboardtype tolowercase trendstyle textdata tonumberfield trianglewave textjustification tooltip triangulardistribution textpacket tooltipdelay trig textrecognize top trigexpand texture tophattransform trigfactor texturecoordinatefunction topologicalsort trigfactorlist texturecoordinatescaling toradicals trigger therefore torules trigreduce thick tostring trigtoexp thickness total trimmedmean thin totalvariationfilter true thinning totalwidth trueq thompsongroupth touppercase truncateddistribution thread tr ttest threejsymbol trace tube threshold traceabove tukeylambdadistribution through tracebackward tuples throw tracedepth turangraph thumbnail tracedialog turingmachine ticks traceforward ticksstyle traceoff u uncompress uniformsumdistribution uparrowbar undefined uninstall uparrowdownarrow underbar union update underflow unionplus updateinterval underlined unique updownarrow underoverscript unitbox upequilibrium underoverscriptbox unitize uppercaseq underscript unitstep upperleftarrow underscriptbox unittriangle upperrightarrow undirectededge unitvector uppertriangularize undirectedgraph unprotect upset undirectedgraphq unsameq upsetdelayed unequal unsavedvariables upteearrow unevaluated unset upvalues uniformdistribution unsetshared usingfrontend uniformgraphdistribution uparrow v validationlength vertexadd vertexreplace valueq vertexcolors vertexshape variables vertexcomponent vertexshapefunction variance vertexcoordinaterules vertexsize varianceequivalencetest vertexcoordinates vertexstyle varianceestimatorfunction vertexcount vertextexturecoordinates variancetest vertexcoverq vertexweight vectorangle vertexdegree verticalbar vectorcolorfunction vertexdelete verticalseparator vectorcolorfunctionscaling vertexeccentricity verticalslider vectordensityplot vertexincomponent verticaltilde vectorplot vertexindegree viewangle vectorplot3d vertexindex viewcenter vectorpoints vertexlabeling viewmatrix vectorq vertexlabels viewpoint vectorscale vertexlist viewrange vectorstyle vertexnormals viewvector vee vertexoutcomponent viewvertical verbatim vertexoutdegree visible verifyconvergence vertexq vonmisesdistribution verifytestassumptions vertexrenderingfunction w waitall weierstrasshalfperiods windowfloating waitnext weierstrassinvariants windowframe wakebydistribution weierstrassp windowmargins walleniushypergeometricdistribution weierstrasspprime windowmovable waringyuledistribution weierstrasssigma windowopacity watershedcomponents weierstrasszeta windowsize watsonusquaretest weightedadjacencygraph windowstatusarea wattsstrogatzgraphdistribution weightedadjacencymatrix windowtitle waveletbestbasis weightedgraphq windowtoolbars waveletfiltercoefficients weights with waveletimageplot wheelgraph wolframalpha waveletlistplot which word waveletmapindexed while wordboundary waveletmatrixplot white wordcharacter waveletphi whitespace worddata waveletpsi whitespacecharacter wordsearch waveletscale whittakerm wordseparators waveletscalogram whittakerw workingprecision waveletthreshold wienerfilter write weatherdata wignerd writestring webere wignersemicircledistribution wronskian wedge windowclickselect weibulldistribution windowelements x xmlelement xnor xmlobject xor y yellow yuledissimilarity z zerniker zetazero ztransform zerotest zipfdistribution zeta ztest $ $aborted $inspector $outputsizelimit $assertfunction $installationdirectory $packages $assumptions $iterationlimit $parentlink $basedirectory $kernelcount $parentprocessid $batchinput $kernelid $path $batchoutput $language $pathnameseparator $byteordering $librarypath $performancegoal $canceled $licenseexpirationdate $post $characterencoding $licenseid $pre $characterencodings $licenseserver $preprint $commandline $line $preread $compilationtarget $linked $processid $configuredkernels $machineaddresses $processorcount $context $machinedomains $processortype $contextpath $machineepsilon $recursionlimit $controlactivesetting $machineid $releasenumber $creationdate $machinename $rootdirectory $currentlink $machineprecision $scheduledtask $datestringformat $machinetype $scriptcommandline $defaultimagingdevice $maxextraprecision $sessionid $display $maxmachinenumber $sharedfunctions $displayfunction $maxnumber $sharedvariables $distributedcontexts $maxpiecewisecases $sounddisplayfunction $dynamicevaluation $maxprecision $syntaxhandler $echo $maxrootdegree $system $epilog $messagegroups $systemcharacterencoding $exportformats $messagelist $systemid $failed $messagepreprint $systemwordlength $frontend $messages $temporarydirectory $frontendsession $minmachinenumber $timedout $geolocation $minnumber $timeunit $historylength $minprecision $timezone $homedirectory $modulenumber $urgent $ignoreeof $newmessage $userbasedirectory $imagingdevices $newsymbol $userdocumentsdirectory $importformats $notebooks $username $initialdirectory $numbermarks $version $input $operatingsystem $versionnumber $inputfilename $output"

regex_'5ba'2dzA'2dZ'5f0'2d9'5d'2b'5c'5f = compileRegex True "[a-zA-Z_0-9]+\\_"
regex_'28'5c'2d'5c'3e'7c'5c'2f'5c'2e'29 = compileRegex True "(\\-\\>|\\/\\.)"
regex_'28'3a'3d'7c'3d'29 = compileRegex True "(:=|=)"

parseRules ("Mathematica","Normal") =
  (((pKeyword " \n\t.():!+,<=>&*/;?[]^{|}~\\" list_functions >>= withAttribute FunctionTok))
   <|>
   ((pInt >>= withAttribute DecValTok))
   <|>
   ((pFloat >>= withAttribute FloatTok))
   <|>
   ((pRegExpr regex_'5ba'2dzA'2dZ'5f0'2d9'5d'2b'5c'5f >>= withAttribute DataTypeTok))
   <|>
   ((pRegExpr regex_'28'5c'2d'5c'3e'7c'5c'2f'5c'2e'29 >>= withAttribute NormalTok))
   <|>
   ((pAnyChar "+*/%\\|-^" >>= withAttribute NormalTok))
   <|>
   ((pRegExpr regex_'28'3a'3d'7c'3d'29 >>= withAttribute NormalTok))
   <|>
   (currentContext >>= \x -> guard (x == ("Mathematica","Normal")) >> pDefault >>= withAttribute NormalTok))


parseRules x = parseRules ("Mathematica","Normal") <|> fail ("Unknown context" ++ show x)
