{- This module was generated from data in the Kate syntax
   highlighting file maxima.xml, version 1, by Alexey Beshenov <al@beshenov.ru> -}

module Text.Highlighting.Kate.Syntax.Maxima
          (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 = "Maxima"

-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.mac;*.MAC;*.dem;*.DEM"

-- | 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 = [("Maxima","Normal Text")], synStLineNumber = 0, synStPrevChar = '\n', synStPrevNonspace = False, synStContinuation = False, synStCaseSensitive = True, synStKeywordCaseSensitive = True, 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 }
      ("Maxima","Normal Text") -> (popContext) >> pEndLine
      ("Maxima","String") -> return ()
      ("Maxima","Comment") -> 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_MaximaKeyword = Set.fromList $ words $ "and do else elseif false for if in not or step then thru true while"
list_SpecialComment = Set.fromList $ words $ "FIXME TODO"
list_MaximaFunction = Set.fromList $ words $ "abasep abs absint absolute_real_time acos acosh acot acoth acsc acsch activate addcol add_edge add_edges addmatrices addrow add_vertex add_vertices adjacency_matrix adjoin adjoint af agd airy_ai airy_bi airy_dai airy_dbi algsys alg_type alias allroots alphacharp alphanumericp antid antidiff AntiDifference append appendfile apply apply1 apply2 applyb1 apropos args arithmetic arithsum array arrayapply arrayinfo arraymake ascii asec asech asin asinh askinteger asksign assoc assoc_legendre_p assoc_legendre_q assume asympa at atan atan2 atanh atensimp atom atvalue augcoefmatrix augmented_lagrangian_method av average_degree backtrace barsplot bashindices batch batchload bc2 bdvac belln bern bernpoly bessel bessel_i bessel_j bessel_k bessel_y beta bezout bffac bfhzeta bfloat bfloatp bfpsi bfpsi0 bfzeta biconected_components bimetric binomial bipartition block blockmatrixp bode_gain bode_phase bothcoef box boxplot break bug_report build_info buildq burn cabs canform canten cardinality carg cartan cartesian_product catch cbffac cdf_bernoulli cdf_beta cdf_binomial cdf_cauchy cdf_chi2 cdf_continuous_uniform cdf_discrete_uniform cdf_exp cdf_f cdf_gamma cdf_geometric cdf_gumbel cdf_hypergeometric cdf_laplace cdf_logistic cdf_lognormal cdf_negative_binomial cdf_normal cdf_pareto cdf_poisson cdf_rank_sum cdf_rayleigh cdf_signed_rank cdf_student_t cdf_weibull cdisplay ceiling central_moment cequal cequalignore cf cfdisrep cfexpand cgeodesic cgreaterp cgreaterpignore changename changevar chaosgame charat charfun charfun2 charlist charp charpoly chebyshev_t chebyshev_u checkdiv check_overlaps cholesky christof chromatic_index chromatic_number cint circulant_graph clear_edge_weight clear_rules clear_vertex_label clebsch_graph clessp clesspignore close closefile cmetric coeff coefmatrix cograd col collapse collectterms columnop columnspace columnswap columnvector combination combine comp2pui compare compfile compile compile_file complement_graph complete_bipartite_graph complete_graph components concan concat conjugate conmetderiv connected_components connect_vertices cons constantp constituent cont2part content continuous_freq contortion contour_plot contract contract_edge contragrad contrib_ode convert coord copy copy_graph copylist copymatrix cor cos cosh cot coth cov cov1 covdiff covect covers create_graph create_list csc csch csetup cspline ctaylor ct_coordsys ctransform ctranspose cube_graph cunlisp cv cycle_digraph cycle_graph dblint deactivate declare declare_translated declare_weight decsym defcon define define_variable defint defmatch defrule deftaylor degree_sequence del delete deleten delta demo demoivre denom depends derivdegree derivlist describe desolve determinant dgauss_a dgauss_b dgeev dgesvd diag diagmatrix diag_matrix diagmatrixp diameter diff digitcharp dimacs_export dimacs_import dimension direct discrete_freq disjoin disjointp disolate disp dispcon dispform dispfun dispJordan display disprule dispterms distrib divide divisors divsum dkummer_m dkummer_u dlange dodecahedron_graph dotproduct dotsimp dpart draw draw2d draw3d draw_graph dscalar echelon edge_coloring edges eigens_by_jacobi eigenvalues eigenvectors eighth einstein eivals eivects elapsed_real_time elapsed_run_time ele2comp ele2polynome ele2pui elem elementp eliminate elliptic_e elliptic_ec elliptic_eu elliptic_f elliptic_kc elliptic_pi ematrix empty_graph emptyp endcons entermatrix entertensor entier equal equalp equiv_classes erf errcatch error errormsg euler ev eval_string evenp every evolution evolution2d evundiff example exp expand expandwrt expandwrt_factored explose exponentialize express expt exsec extdiff extract_linear_equations extremal_subset ezgcd f90 facsum factcomb factor factorfacsum factorial factorout factorsum facts fast_central_elements fast_linsolve fasttimes featurep fft fib fibtophi fifth filename_merge file_search file_type fillarray findde find_root first fix flatten flength float floatnump floor flower_snark flush flush1deriv flushd flushnd forget fortran fourcos fourexpand fourier fourint fourintcos fourintsin foursimp foursin fourth fposition frame_bracket freeof freshline from_adjacency_matrix frucht_graph full_listify fullmap fullmapl fullratsimp fullratsubst fullsetify funcsolve fundef funmake funp gamma gauss_a gauss_b gaussprob gcd gcdex gcdivide gcfac gcfactor gd genfact gen_laguerre genmatrix geometric geometric_mean geosum get get_edge_weight get_lu_factors get_pixel get_vertex_label gfactor gfactorsum ggf girth global_variances gnuplot_close gnuplot_replot gnuplot_reset gnuplot_restart gnuplot_start go Gosper GosperSum gradef gramschmidt graph6_decode graph6_encode graph6_export graph6_import graph_center graph_charpoly graph_eigenvalues graph_order graph_periphery graph_product graph_size graph_union grid_graph grind grobner_basis grotzch_graph hamilton_cycle hamilton_path hankel harmonic harmonic_mean hav heawood_graph hermite hessian hilbert_matrix hipow histogram hodge horner ic1 ic2 ic_convert ichr1 ichr2 icosahedron_graph icurvature ident identfor identity idiff idim idummy ieqn ifactors iframes ifs ift igeodesic_coords ilt imagpart imetric implicit_derivative implicit_plot indexed_tensor indices induced_subgraph inferencep inference_result infix init_atensor init_ctensor in_neighbors innerproduct inpart inprod inrt integerp integer_partitions integrate intersect intersection intervalp intopois intosum invariant1 invariant2 inverse_jacobi_cd inverse_jacobi_cn inverse_jacobi_cs inverse_jacobi_dc inverse_jacobi_dn inverse_jacobi_ds inverse_jacobi_nc inverse_jacobi_nd inverse_jacobi_ns inverse_jacobi_sc inverse_jacobi_sd inverse_jacobi_sn invert invert_by_lu inv_mod is is_biconnected is_bipartite is_connected is_digraph is_edge_in_graph is_graph is_graph_or_digraph ishow is_isomorphic isolate isomorphism is_planar isqrt is_sconnected is_tree is_vertex_in_graph items_inference jacobi jacobian jacobi_cd jacobi_cn jacobi_cs jacobi_dc jacobi_dn jacobi_ds jacobi_nc jacobi_nd jacobi_ns jacobi_p jacobi_sc jacobi_sd jacobi_sn JF join jordan julia kdels kdelta kill killcontext kostka kron_delta kronecker_product kummer_m kummer_u kurtosis kurtosis_bernoulli kurtosis_beta kurtosis_binomial kurtosis_chi2 kurtosis_continuous_uniform kurtosis_discrete_uniform kurtosis_exp kurtosis_f kurtosis_gamma kurtosis_geometric kurtosis_gumbel kurtosis_hypergeometric kurtosis_laplace kurtosis_logistic kurtosis_lognormal kurtosis_negative_binomial kurtosis_normal kurtosis_pareto kurtosis_poisson kurtosis_rayleigh kurtosis_student_t kurtosis_weibull labels lagrange laguerre lambda laplace laplacian_matrix last lbfgs lc2kdt lcharp lc_l lcm lc_u ldefint ldisp ldisplay legendre_p legendre_q leinstein length let letrules letsimp levi_civita lfreeof lgtreillis lhs li liediff limit Lindstedt linear linearinterpol linear_program line_graph linsolve listarray list_correlations listify list_nc_monomials listoftens listofvars listp lmax lmin load loadfile local locate_matrix_entry log logand logarc logcontract logor logxor lopow lorentz_gauge lowercasep lpart lratsubst lreduce lriemann lsquares_estimates lsquares_estimates_approximate lsquares_estimates_exact lsquares_mse lsquares_residual_mse lsquares_residuals lsum ltreillis lu_backsub lu_factor macroexpand macroexpand1 make_array makebox makefact makegamma make_level_picture makelist makeOrders make_poly_continent make_poly_country make_polygon make_random_state make_rgb_picture makeset make_transform mandelbrot map mapatom maplist matchdeclare matchfix mat_cond mat_fullunblocker mat_function mat_norm matrix matrixmap matrixp matrix_size mattrace mat_trace mat_unblocker max max_clique max_degree max_flow maxi maximize_lp max_independent_set max_matching maybe mean mean_bernoulli mean_beta mean_binomial mean_chi2 mean_continuous_uniform mean_deviation mean_discrete_uniform mean_exp mean_f mean_gamma mean_geometric mean_gumbel mean_hypergeometric mean_laplace mean_logistic mean_lognormal mean_negative_binomial mean_normal mean_pareto mean_poisson mean_rayleigh mean_student_t mean_weibull median median_deviation member metricexpandall min min_degree minfactorial mini minimalPoly minimize_lp minimum_spanning_tree minor mnewton mod mode_declare mode_identity ModeMatrix moebius mon2schur mono monomial_dimensions multi_elem multinomial multinomial_coeff multi_orbit multi_pui multsym multthru mycielski_graph nary nc_degree ncexpt ncharpoly negative_picture neighbors newcontext newdet new_graph newline newton next_prime niceindices ninth noncentral_moment nonmetricity nonnegintegerp nonscalarp nonzeroandfreeof notequal nounify nptetrad nroots nterms ntermst nthroot nullity nullspace num numbered_boundaries numberp num_distinct_partitions numerval numfactor num_partitions nusum odd_girth oddp ode2 ode_check odelin op opena openr openw operatorp opsubst optimize orbit orbits ordergreat ordergreatp orderless orderlessp orthogonal_complement orthopoly_recur orthopoly_weight outermap out_neighbors outofpois pade parGosper parse_string part part2cont partfrac partition partition_set partpol path_digraph path_graph pdf_bernoulli pdf_beta pdf_binomial pdf_cauchy pdf_chi2 pdf_continuous_uniform pdf_discrete_uniform pdf_exp pdf_f pdf_gamma pdf_geometric pdf_gumbel pdf_hypergeometric pdf_laplace pdf_logistic pdf_lognormal pdf_negative_binomial pdf_normal pdf_pareto pdf_poisson pdf_rank_sum pdf_rayleigh pdf_signed_rank pdf_student_t pdf_weibull pearson_skewness permanent permut permutation permutations petersen_graph petrov pickapart picture_equalp picturep piechart planar_embedding playback plog plot2d plot3d plotdf plsquares pochhammer poisdiff poisexpt poisint poismap poisplus poissimp poissubst poistimes poistrim polarform polartorect poly_add poly_buchberger poly_buchberger_criterion poly_colon_ideal poly_content polydecomp poly_depends_p poly_elimination_ideal poly_exact_divide poly_expand poly_expt poly_gcd poly_grobner poly_grobner_equal poly_grobner_member poly_grobner_subsetp poly_ideal_intersection poly_ideal_polysaturation poly_ideal_polysaturation1 poly_ideal_saturation poly_ideal_saturation1 poly_lcm poly_minimization polymod poly_multiply polynome2ele polynomialp poly_normal_form poly_normalize poly_normalize_list poly_polysaturation_extension poly_primitive_part poly_pseudo_divide poly_reduced_grobner poly_reduction poly_saturation_extension poly_s_polynomial poly_subtract polytocompanion potential power_mod powers powerseries powerset prev_prime primep print printf print_graph printpois printprops prodrac product properties propvars psi ptriangularize pui pui2comp pui2ele pui2polynome pui_direct puireduc put qput qrange quad_qag quad_qagi quad_qags quad_qawc quad_qawf quad_qawo quad_qaws quantile quantile_bernoulli quantile_beta quantile_binomial quantile_cauchy quantile_chi2 quantile_continuous_uniform quantile_discrete_uniform quantile_exp quantile_f quantile_gamma quantile_geometric quantile_gumbel quantile_hypergeometric quantile_laplace quantile_logistic quantile_lognormal quantile_negative_binomial quantile_normal quantile_pareto quantile_poisson quantile_rayleigh quantile_student_t quantile_weibull quartile_skewness quit qunit quotient radcan radius random random_bernoulli random_beta random_binomial random_cauchy random_chi2 random_continuous_uniform random_digraph random_discrete_uniform random_exp random_f random_gamma random_geometric random_graph random_graph1 random_gumbel random_hypergeometric random_laplace random_logistic random_lognormal random_negative_binomial random_network random_normal random_pareto random_permutation random_poisson random_rayleigh random_regular_graph random_student_t random_tournament random_tree random_weibull range rank rat ratcoef ratdenom ratdiff ratdisrep ratexpand rational rationalize ratnumer ratnump ratp ratsimp ratsubst ratvars ratweight read read_hashed_array readline read_lisp_array read_list read_matrix read_maxima_array read_nested_list readonly read_xpm realpart realroots rearray rectform recttopolar rediff reduce_consts reduce_order region_boundaries rem remainder remarray rembox remcomps remcon remcoord remfun remfunction remlet remove remove_edge remove_vertex rempart remrule remsym remvalue rename reset residue resolvante resolvante_alternee1 resolvante_bipartite resolvante_diedrale resolvante_klein resolvante_klein3 resolvante_produit_sym resolvante_unitaire resolvante_vierer rest resultant return reveal reverse revert revert2 rgb2level rhs ricci riemann rinvariant risch rk rncombine romberg room rootscontract row rowop rowswap rreduce run_testsuite save scalarp scaled_bessel_i scaled_bessel_i0 scaled_bessel_i1 scalefactors scanmap scatterplot schur2comp sconcat scopy scsimp scurvature sdowncase sec sech second sequal sequalignore setdifference set_edge_weight setelmx setequalp setify setp set_partitions set_plot_option set_random_state setunits setup_autoload set_up_dot_simplifications set_vertex_label seventh sexplode sf shortest_path show showcomps showratvars sign signum similaritytransform simple_linear_regression simplify_sum simplode simpmetderiv simtran sin sinh sinsert sinvertcase sixth skewness skewness_bernoulli skewness_beta skewness_binomial skewness_chi2 skewness_continuous_uniform skewness_discrete_uniform skewness_exp skewness_f skewness_gamma skewness_geometric skewness_gumbel skewness_hypergeometric skewness_laplace skewness_logistic skewness_lognormal skewness_negative_binomial skewness_normal skewness_pareto skewness_poisson skewness_rayleigh skewness_student_t skewness_weibull slength smake smismatch solve solve_rec solve_rec_rat some somrac sort sparse6_decode sparse6_encode sparse6_export sparse6_import specint spherical_bessel_j spherical_bessel_y spherical_hankel1 spherical_hankel2 spherical_harmonic splice split sposition sprint sqfr sqrt sqrtdenest sremove sremovefirst sreverse ssearch ssort sstatus ssubst ssubstfirst staircase status std std1 std_bernoulli std_beta std_binomial std_chi2 std_continuous_uniform std_discrete_uniform std_exp std_f std_gamma std_geometric std_gumbel std_hypergeometric std_laplace std_logistic std_lognormal std_negative_binomial std_normal std_pareto std_poisson std_rayleigh std_student_t std_weibull stirling stirling1 stirling2 strim striml strimr string stringout stringp strong_components sublis sublist sublist_indices submatrix subsample subset subsetp subst substinpart substpart substring subvar subvarp sum sumcontract summand_to_rec supcase supcontext symbolp symmdifference symmetricp system take_channel take_inference tan tanh taylor taylorinfo taylorp taylor_simplifier taytorat tcl_output tcontract tellrat tellsimp tellsimpafter tentex tenth test_mean test_means_difference test_normality test_rank_sum test_sign test_signed_rank test_variance test_variance_ratio tex texput %th third throw time timedate timer timer_info tldefint tlimit todd_coxeter toeplitz tokens to_lisp topological_sort totaldisrep totalfourier totient tpartpol trace tracematrix trace_options translate translate_file transpose tree_reduce treillis treinat triangularize trigexpand trigrat trigreduce trigsimp trunc tr_warnings_get ueivects uforget ultraspherical underlying_graph undiff union unique uniteigenvectors unit_step unitvector unknown unorder unsum untellrat untimer untrace uppercasep uricci uriemann uvect vandermonde_matrix var var1 var_bernoulli var_beta var_binomial var_chi2 var_continuous_uniform var_discrete_uniform var_exp var_f var_gamma var_geometric var_gumbel var_hypergeometric var_laplace var_logistic var_lognormal var_negative_binomial var_normal var_pareto var_poisson var_rayleigh var_student_t var_weibull vectorpotential vectorsimp verbify vers vertex_coloring vertex_degree vertex_distance vertex_eccentricity vertex_in_degree vertex_out_degree vertices vertices_to_cycle vertices_to_path weyl wheel_graph with_stdout write_data writefile wronskian xgraph_curves xreduce xthru Zeilberger zeroequiv zerofor zeromatrix zeromatrixp zeta zlange"
list_MaximaVariable = Set.fromList $ words $ "_ __ % %% absboxchar activecontexts additive algebraic algepsilon algexact aliases all_dotsimp_denoms allbut allsym arrays askexp assume_pos assume_pos_pred assumescalar atomgrad backsubst berlefact besselexpand bftorat bftrunc boxchar breakup cauchysum cflength cframe_flag cnonmet_flag context contexts cosnpiflag ctaypov ctaypt ctayswitch ctayvar ct_coords ctorsion_flag ctrgsimp current_let_rule_package debugmode default_let_rule_package demoivre dependencies derivabbrev derivsubst detout diagmetric dim dispflag display2d display_format_internal doallmxops domain domxexpt domxmxops domxnctimes dontfactor doscmxops doscmxplus dot0nscsimp dot0simp dot1simp dotassoc dotconstrules dotdistrib dotexptsimp dotident dotscrules draw_graph_program %edispflag %emode %enumer epsilon_lp erfflag error error_size error_syms %e_to_numlog evflag evfun expandwrt_denom expon exponentialize expop exptdispflag exptisolate exptsubst facexpand factlim factorflag file_output_append file_search_demo file_search_lisp file_search_maxima find_root_abs find_root_error find_root_rel flipflag float2bf fortindent fortspaces fpprec fpprintprec functions gammalim gdet genindex gensumnum GGFCFMAX GGFINFINITY globalsolve gradefs grind halfangles %iargs ibase icounter idummyx ieqnprint iframe_bracket_form igeowedge_flag imetric inchar infeval inflag infolists in_netmath integrate_use_rootsof integration_constant integration_constant_counter intfaclim isolate_wrt_times keepfloat labels letrat let_rule_packages lhospitallim limsubst linechar linel linenum linsolve_params linsolvewarn lispdisp listarith listconstvars listdummyvars lmxchar loadprint logabs logarc logconcoeffp logexpand lognegint lognumer logsimp m1pbranch macroexpansion maperror mapprint matrix_element_add matrix_element_mult matrix_element_transpose maxapplydepth maxapplyheight maxima_tempdir maxima_userdir maxnegex maxposex maxpsifracdenom maxpsifracnum maxpsinegint maxpsiposint maxtayorder method mode_check_errorp mode_checkp mode_check_warnp modulus multiplicities myoptions negdistrib negsumdispflag newtonepsilon newtonmaxiter niceindicespref nolabels nonegative_lp noundisp obase opproperties opsubst optimprefix optionset outchar packagefile partswitch pfeformat %piargs piece plot_options poislim poly_coefficient_ring poly_elimination_order poly_grobner_algorithm poly_grobner_debug poly_monomial_order poly_primary_elimination_order poly_return_term_list poly_secondary_elimination_order poly_top_reduction_only powerdisp prederror primep_number_of_tests product_use_gamma programmode prompt psexpand radexpand radsubstflag random_beta_algorithm random_binomial_algorithm random_chi2_algorithm random_exp_algorithm random_f_algorithm random_gamma_algorithm random_geometric_algorithm random_hypergeometric_algorithm random_negative_binomial_algorithm random_normal_algorithm random_poisson_algorithm random_student_t_algorithm ratalgdenom ratchristof ratdenomdivide rateinstein ratepsilon ratexpand ratfac ratmx ratprint ratriemann ratsimpexpons ratvars ratweights ratweyl ratwtlvl realonly refcheck rmxchar %rnum_list rombergabs rombergit rombergmin rombergtol rootsconmode rootsepsilon savedef savefactors scalarmatrixp setcheck setcheckbreak setval showtime simplify_products simpsum sinnpiflag solvedecomposes solveexplicit solvefactors solve_inconsistent_error solvenullwarn solveradcan solvetrigwarn sparse sqrtdispflag stardisp stats_numer stringdisp sublis_apply_lambda sumexpand sumsplitfact taylordepth taylor_logexpand taylor_order_coefficients taylor_truncate_polynomials tensorkill testsuite_files timer_devalue tlimswitch transcompile transrun tr_array_as_ref tr_bound_function_applyp tr_file_tty_messagesp tr_float_can_branch_complex tr_function_call_default trigexpandplus trigexpandtimes triginverses trigsign tr_numer tr_optimize_max_loop tr_semicompile tr_state_vars tr_warn_bad_function_calls tr_warn_fexpr tr_warn_meval tr_warn_mode tr_warn_undeclared tr_warn_undefined_variable tr_windy ttyoff use_fast_arrays values vect_cross verbose zerobern zeta%pi"

regex_'5ba'2dzA'2dZ'5f'5d'5ba'2dzA'2dZ0'2d9'25'5f'5d'2a = compileRegex True "[a-zA-Z_][a-zA-Z0-9%_]*"
regex_'5b'2d'2b'5d'3f'5cd'2b'5c'2e'5cd'2a'28'5bBbDdEeSs'5d'5b'2d'2b'5d'3f'5cd'2b'29'3f = compileRegex True "[-+]?\\d+\\.\\d*([BbDdEeSs][-+]?\\d+)?"
regex_'5b'2d'2b'5d'3f'5c'2e'5cd'2b'28'5bBbDdEeSs'5d'5b'2d'2b'5d'3f'5cd'2b'29'3f = compileRegex True "[-+]?\\.\\d+([BbDdEeSs][-+]?\\d+)?"
regex_'5b'2d'2b'5d'3f'5cd'2b'5bBbDdEeSs'5d'5b'2d'2b'5d'3f'5cd'2b = compileRegex True "[-+]?\\d+[BbDdEeSs][-+]?\\d+"
regex_'5b'2d'2b'5d'3f'5cd'2b = compileRegex True "[-+]?\\d+"

parseRules ("Maxima","Normal Text") =
  (((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\@#" list_MaximaFunction >>= withAttribute FunctionTok))
   <|>
   ((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\@#" list_MaximaVariable >>= withAttribute VariableTok))
   <|>
   ((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\@#" list_MaximaKeyword >>= withAttribute KeywordTok))
   <|>
   ((pDetectChar False '"' >>= withAttribute StringTok) >>~ pushContext ("Maxima","String"))
   <|>
   ((pDetect2Chars False '/' '*' >>= withAttribute CommentTok) >>~ pushContext ("Maxima","Comment"))
   <|>
   ((pRegExpr regex_'5ba'2dzA'2dZ'5f'5d'5ba'2dzA'2dZ0'2d9'25'5f'5d'2a >>= withAttribute NormalTok))
   <|>
   ((pRegExpr regex_'5b'2d'2b'5d'3f'5cd'2b'5c'2e'5cd'2a'28'5bBbDdEeSs'5d'5b'2d'2b'5d'3f'5cd'2b'29'3f >>= withAttribute FloatTok))
   <|>
   ((pRegExpr regex_'5b'2d'2b'5d'3f'5c'2e'5cd'2b'28'5bBbDdEeSs'5d'5b'2d'2b'5d'3f'5cd'2b'29'3f >>= withAttribute FloatTok))
   <|>
   ((pRegExpr regex_'5b'2d'2b'5d'3f'5cd'2b'5bBbDdEeSs'5d'5b'2d'2b'5d'3f'5cd'2b >>= withAttribute FloatTok))
   <|>
   ((pRegExpr regex_'5b'2d'2b'5d'3f'5cd'2b >>= withAttribute DecValTok))
   <|>
   ((pDetectChar False '\'' >>= withAttribute CommentTok))
   <|>
   (currentContext >>= \x -> guard (x == ("Maxima","Normal Text")) >> pDefault >>= withAttribute NormalTok))

parseRules ("Maxima","String") =
  (((pDetectChar False '"' >>= withAttribute StringTok) >>~ (popContext))
   <|>
   (currentContext >>= \x -> guard (x == ("Maxima","String")) >> pDefault >>= withAttribute StringTok))

parseRules ("Maxima","Comment") =
  (((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\@#" list_SpecialComment >>= withAttribute SpecialStringTok))
   <|>
   ((pDetectSpaces >>= withAttribute CommentTok))
   <|>
   ((pDetect2Chars False '*' '/' >>= withAttribute CommentTok) >>~ (popContext))
   <|>
   (currentContext >>= \x -> guard (x == ("Maxima","Comment")) >> pDefault >>= withAttribute CommentTok))


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