{- This module was generated from data in the Kate syntax
   highlighting file sci.xml, version 1.03, by  -}

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

-- | Filename extensions for this language.
syntaxExtensions :: String
syntaxExtensions = "*.sci;*.sce"

-- | 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 = [("scilab","main")], 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 }
      ("scilab","main") -> 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_Structure'2dkeywords = Set.fromList $ words $ "do else for if elseif end select then while"
list_Control'2dkeywords = Set.fromList $ words $ "abort break quit return resume pause"
list_Function'2dkeywords = Set.fromList $ words $ "function endfunction"
list_Warning'2dkeywords = Set.fromList $ words $ "error warning"
list_Constants'2dkeyword = Set.fromList $ words $ "%F %f %T %t %e %pi %inf %i %z %io %s %nan $ %eps MSDOS"
list_functions = Set.fromList $ words $ "zpell zpch2 zpch1 zpbutt zgrid zeros zeropen ZCROSS_f yulewalk xtitle xtape xstringl xstringb xstring xsetm xsetech xset xselect xsegs xsave xs2fig xrpoly xrects xrect xpolys xpoly xpause xnumb xname x_message_modeless x_message x_mdialog x_matrix xload xlfont xinit xinfo xgrid xgraduate xgetmouse xgetfile xgetech xget xfrect xfpolys xfpoly xfarcs xfarc xend x_dialog xdel xclip xclick xclear xclea x_choose x_choices xchange xbasr xbasimp xbasc xaxis xarrows xarcs xarc WRITEC_f write4b write writb winsid window wigner wiener whos who whereis whereami where what wfir WFILE_f wavwrite wavread warning WaitMsg varn varargout varargin user unsetmenu unobs unix_x unix_w unix_s unix_g unix unique union ulink ui_observer uint8 uint32 uint16 uimenu uicontrol typeof typename type trzeros triu trisolve tril trianfml trfmod TRASH_f translatepaths trans_closure trans trace toeplitz tlist TK_SetVar TK_GetVar TK_EvalStr TK_EvalFile titlepage timer time_id TIME_f tilda tf2ss tf2des TEXT_f texprint testmatrix tdinit TCLSS_f tanm tanhm tanh tangent TANBLK_f tan systmat systems system syssize syslin sysfact- sysdiag sysconv symbols sylv sylm svplot svd sva supernode SUPER_f sum successors subplot subgraph subf strsubst strong_con_nodes strong_connex stripblanks strings string strindex strcat str2code STOP_f st_ility st_deviation startup star standard_output standard_origin standard_input standard_draw standard_define stacksize stabil ssrand ssprint sskf sscanf ss2tf ss2ss ss2des srkf srfaur squarewave square sqrtm sqrt sqroot spzeros sprintf sprand spones SPLIT_f split_edge splin spget speye specfact spec spcompack spchol sparse spantwo spanplus spaninter sp2adj sound sort SOM_f solve %sn smooth sm2ss sm2des slash size sinm sinhm sinh sincd sinc SINBLK_f sin simp_mode simp signm sign showprofile show_nodes show_graph show_arcs shortest_path sgrid Sgrayplot Sfgrayplot sfact setscicosvars setmenu setfield setbpt set sensi SendMsg semidef semicolumn semi SELECT_f secto3d sd2sci SCOPXY_f SCOPE_f scilink ScilabEval scilab scifunc_block scicos_model scicos_menus scicos_main scicos_link scicosim scicos_graphics scicos_cpr scicos_block scicos sciargs sci2map sci2for sci2exp schur scanf_conversion scanf scaling SAWTOOTH_f savewave save_graph save SAT_f SAMPLEHOLD_f salesman rtitr rref rpem rowshuff rowregul rowinout rowcompr rowcomp routh_t round rotate roots rlist ric_desc riccati ricc RFILE_f residu replot repfreq remezb remez RELAY_f reglin REGISTER_f recur real readmps READC_f readc_ readb read4b read rdivf rcond rational rat rank range randpencil RAND_f rand quote quit quaskro quapro QUANT_f qr qassign pwd pvm_tidtohost pvm_start pvm_spawn_independent pvm_spawn pvm_set_timer pvm_send pvm_sci2f77 pvm_reduce pvm_recv pvm_probe pvm_mytid pvm_lvgroup pvm_kill pvm_joingroup pvm_halt pvm_gsize pvm_get_timer pvm_getinst pvm_exit pvm_error pvm_delhosts pvmd3 pvm_config pvm_bufinfo pvm_bcast pvm_addhosts pvm pspect psmall projspec projsl proj profile PROD_f prod printing printf_conversion printf print predef predecessors prbs_a ppol power POWBLK_f POSTONEG_f portrait portr3d poly polfact polarplot polar pol2tex pol2str pol2des pmodulo p_margin plzr plus plotprofile plot_graph plotframe plot3d3 plot3d2 plot3d1 plot3d plot2d4 plot2d3 plot2d2 plot2d1 plot2d plot playsnd pipe_network pinv phc phasemag pfss pertrans perfect_match percent penlaur pencan pen2ea pdiv pbig path_2_nodes part parrot parents paramfplot2d param3d1 param3d overloading OUT_f orth or optim ones oldsave oldload ode_root odeoptions ode_discrete odedi odedc ode obsvss obsv_mat obs_gram observer obscont1 obscont nyquist numer null not norm noisegen nodes_degrees nodes_2_path node_number nnz nlev nf3d newfun newest netwindows netwindow netclose neighbors nehari NEGTOPOS_f narsimul names MUX_f mulf mu2lin mtlb_sparse mtlb_save mtlb_mode mtlb_load mtell msscanf msprintf mseek mscanf mrfit mputstr mputl mput mps2linpro mprintf mopen modulo mode mlist min_weight_tree minus minss minreal min_qcost_flow min_lcost_flow2 min_lcost_flow1 min_lcost_cflow mini MIN_f mine min milk_drop mgetstr mgetl mgeti mget mfscanf mfprintf mfile2sci mfft MFCLCK_f metanet_sync metanet mesh2d mese meof median mean mclose MCLOCK_f mclearerr m_circle maxi max_flow MAX_f max_clique max_cap_path max matrix matrices Matplot1 Matplot mat_2_graph markp2ss mapsound manedit man make_graph macrovar macro macr2lst macglov lyap lusolve luget lufact ludel lu ltitr lstcat lsslist lqr lqg_ltr lqg2stan lqg lqe lotest LOOKUP_f logspace logm LOGBLK_f log2 log10 log locate loadwave load_graph load lmitool lmisolver list linspace linsolve linpro link linfn linf lines line_graph lindquist lin2mu lin lib lgfft lft lex_sort levin lev less leqr length legends left leastsq ldivf ldiv lcmdiag lcm lcf lattp lattn lasterror kroneck kron krac2 kpure knapsack keyboard kernel karmarkar kalm %k jmat isreal isoview isnan isinf isglobal iserror isdef is_connex invsyslin invr inv_coeff INVBLK_f inv inttype inttrap intsplin INTRPLBLK_f INTRP2BLK_f intppty intl intg intersect intersci interpln interp integrate INTEGRAL_f intdec intc int8 int3d int32 int2d int16 int insertion input IN_f imrep2ss impl im_inv imag ilib_gen_Make ilib_gen_loader ilib_gen_gateway ilib_for_link ilib_compile ilib_build iirlp iirgroup iir IFTHEL_f ieee iconvert hypermatrices hypermat htrianr hrmt householder hotcolormap host horner h_norm histplot hist3d h_inf_st h_inf hilb hex2dec hess hermit %helps help h_cl havewindow hat hankelsv hank hamilton HALT_f halt h2norm gtild gstacksize gspec gsort gschur group gr_menu grep graypolarplot grayplot graycolormap graph_union graph_sum graph_simp graph_power graph-list Graphics graph_diameter graph_complement graph_center graph_2_mat grand graduate gpeche g_margin G_make global glist glever givens girth gfrancis gfare getversion getvalue getsymbol getscicosvars getpid GetMsg getmark getlinestyle getio get_function_path getfont getfield getf getenv getdate getd getcwd getcolor getblocklabel get geom3d GENSQR_f GENSIN_f gen_net genmarkov genlib genfac3d GENERIC_f GENERAL_f gcf gcd gcare gammaln gamma gamitg gainplot GAIN_f GAINBLK_f fusee funptr funcprot fun2string fullrfk fullrf full fstair fstabst fspecg fsolve fsfirlin fscanfMat fscanf frmag frfit frexp freson freq frep2tf fprintfMat fprintf fplot3d1 fplot3d fplot2d fourplan fort formatman format flts floor fix fit_dat find_path findobj findm find_freq find filter fileinfo file figure fgrayplot fft ffilt feval feedback fec fcontour2d fcontour fchamp faurre factors fac3d eye extraction external expm EXPBLK_f exp exit exists execstr ExecScilab ExeclScilab ExecAppli exec excel2sci Example EVTGEN_f EVTDLY_f evstr EVENTSCOPE_f evans eval3dp eval3d eval error errclear errcatch errbar erfcx erfc erf ereduc equil1 equil equal eqiir eqfir emptystr empty ell1mag eigenmarkov edit_curv edit edge_number dtsi dt_ility dsimul dscr driver drawaxis dragrect double dot DLSS_f DLR_f DLRADAPT_f dlgamma dispfile dispbpt disp diophant diary diag dhnorm dft detr determ det DestroyLink des2tf des2ss derivative- derivat denom DEMUX_f demos delmenu delip delete_nodes delete_arcs delbpt DELAYV_f DELAY_f degree deff dec2hex debug ddp dcf dbphi date datafit dassl dasrt czt cycle_basis CURV_f curblock cumsum cumprod ctr_gram cspect csim CreateLink cothm coth cotg cosm coshm cosh COSBLK_f cos corr copfac convstr convol convex_hull contrss contract_edge contr contourf contour2di contour2d contour cont_mat cont_frm CONST_f con_nodes connex conj cond companion comp Communications colregul colormap colon colnew colinout colcompr colcomp coffg coff coeff code2str cmndred cmb_lin CLSS_f cls2dls CLR_f close CLOCK_f CLKSPLIT_f CLKSOMV_f CLKSOM_f CLKOUTV_f CLKOUT_f CLKINV_f CLKIN_f c_link CLINDUMMY_f clearglobal clearfun clear clean classmarkov circuit chsolve chol chfact chepol check_graph cheb2mag cheb1mag chdir chart champ1 champ chaintest chain_struct cepstrum ceil cdft cdfpoi cdfnor cdfnbn cdfgam cdffnc cdff cdfchn cdfchi cdfbin cdfbet ccontrg casc canon call calfrq calerf cainv bvode buttmag bstap boucle boolean bool2s bode bloc2ss bloc2exp black binomial bilin BIGSOM_f bifish bezout best_match bessely besselk besselj besseli bdiag bandwr balreal balanc backslash auwrite auread augment atanm atanhm atanh atan %asn asinm asinhm asinh asin ascii articul artest arsimul armax1 armax armac arma2p arma arl2 arhnk argn arc_number arc_graph apropos ans ANIMXY_f ANDLOG_f and analyze analpf amell alufunctions AFFICH_f aff2ab adj_lists adj2sp add_node addmenu addinter addf add_edge addcolor AdCommunications acosm acoshm acosh acos ABSBLK_f abs abinv abcd"

regex_'2f'2f'2e'2a'24 = compileRegex True "//.*$"

parseRules ("scilab","main") =
  (((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\" list_Structure'2dkeywords >>= withAttribute NormalTok))
   <|>
   ((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\" list_Control'2dkeywords >>= withAttribute NormalTok))
   <|>
   ((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\" list_Function'2dkeywords >>= withAttribute FunctionTok))
   <|>
   ((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\" list_Warning'2dkeywords >>= withAttribute NormalTok))
   <|>
   ((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\" list_Constants'2dkeyword >>= withAttribute NormalTok))
   <|>
   ((pKeyword " \n\t.():!+,-<=>&*/;?[]^{|}~\\" list_functions >>= withAttribute FunctionTok))
   <|>
   ((pFloat >>= withAttribute NormalTok))
   <|>
   ((pInt >>= withAttribute DecValTok))
   <|>
   ((pRegExpr regex_'2f'2f'2e'2a'24 >>= withAttribute CommentTok))
   <|>
   ((pRangeDetect '"' '"' >>= withAttribute StringTok))
   <|>
   (currentContext >>= \x -> guard (x == ("scilab","main")) >> pDefault >>= withAttribute NormalTok))


parseRules x = parseRules ("scilab","main") <|> fail ("Unknown context" ++ show x)
