latex = {}

require("eu_sci")
require("eu_core")

function latex.init_after_callback(p)
  local pnode = eu_core.ffi.cast("void *", p)
  local res = eu_core.euapi.on_doc_init_after_scilexer(pnode, "latex")  -- enable latex lex
  if (res == 0) then
    eu_core.euapi.on_doc_enable_foldline(pnode)                         -- enable fold line
  end
  return res
end

function latex.get_comments()
  -- 行注释与块注释, 注释头与注释尾用&&分开
  local line_t = "% "
  local block_t = "\\begin{comment}&&\\end{comment}"
  return line_t, block_t
end

function latex.get_styles()
  local style_t = {
    [SCE_L_COMMENT] = 0xC0C0C0,
    [SCE_L_COMMENT2] = 0xC0C0C0,
    -- 给关键字加上粗体
    [SCE_L_COMMAND] = 0x00B050 + SCE_BOLD_FONT,
    [SCE_L_SHORTCMD] = 0x00B050,
    [SCE_L_CMDOPT] = 0xBBBB00 + SCE_BOLD_FONT,
    [SCE_L_TAG] = 0xC080FF,
    [SCE_L_TAG2] = 0xC080FF,
  }
  return style_t
end

function latex.get_autocomplete()
  local autocomplete_set = "Alph Alpha AltMacroFont AmSTeX Appendix Arrowvert AtBeginDocument AtEndClass AtEndDocument AtEndOfClass AtEndOfPackage AtEndPackage Bbb Bbbk Beta BibTeX Big Box CJK CJK* CJKfamily Cap CharacterTable CheckCommand CheckCommand* CheckModules CheckSum ClassError ClassInfo ClassWarning ClassWarningNoLine CodelineFont CodelineIndex CodelineNumbered CurrentOption DeclareErrorFont DeclareFixedFont DeclareFontEncoding DeclareFontEncodingDefaults DeclareFontFamily DeclareFontShape DeclareFontSubstitution DeclareInputMath DeclareInputText DeclareMathAccent DeclareMathAlphabet DeclareMathSizes DeclareMathSymbol DeclareMathVersion DeclareOldFontCommand DeclareOption DeclareOption* DeclareRobustCommand DeclareRobustCommand* DeclareSymbolFont DeclareSymbolFontAlphabet DeclareTextAccent DeclareTextAccentDefault DeclareTextCommand DeclareTextCommandDefault DeclareTextCompositeCommand DeclareTextFontCommand DeclareTextSymbol DeclareTextSymbolDefault DeleteShortVerb Delta DescribeEnv DescribeEnvironment DescribeMacro Diamond DisableCrossrefs DoNotIndex DocInput DocstyleParms DontCheckModules Downarrow EnableCrossrefs Esper EuFrak EuScript ExecuteOptions Finale Finv GBK Game Gamma GapDepth GapWidth GetFileInfo GlossaryMin GlossaryParms GlossaryPrologue HUGE Huge IfFileExists Im IndexInput IndexMin IndexParms IndexPrologue InputIfFileExists Join LARGE LTcapuidth LTchunksize LTleft LTpost LTpre LTright LaTeX LaTeXe Lambda Large Leftarrow Leftrightarrow Lentrylabel Lleftarrow LoadClass Longleftarrow Longleftrightarrow Longrightarrow Lsh MacroFont MacroIndent MacrocodeTopsep MakeLowercase MakePrivateLetters MakeShortVerb MakeUppercase Mentry Mentrylabel Module Msgrigid NeedsTeXFormat{format} NouveauLangage Omega OnlyDescription OptionNotUsed Ovalbox PScommands PackageError PackageInfo PackageWarning PackageWarningNoLine PageIndex PassOptionsToClass PassOptionsToPackage Phi Pi Pifill Pifont Piline Pisymbol PreserveBackslash PrintChanges PrintDescribeEnv PrintDescribeMacro PrintIndex PrintMacroName ProcessOptions ProcessOptions* ProvideTextCommand ProvideTextCommandDefault ProvidesClass ProvidesFile ProvidesPackage Psi REVTeX Re RecordChanges Relbar RequirePackage Rightarrow Roman Rsh SS SetMathAlphabet SetSymbolFont Sigma SortIndex SortNoop SpecialEnvIndex SpecialEscapechar SpecialIndex SpecialMainIndex SpecialUsageIndex StopEventually Subset Supset TH TeX TheSbox Theta Thicklines ULforem UTF8 Uparrow Updownarrow Upsilon Vdash Vert Vvdeah WideMargins Xarea XeTeX Xi Xsize Yarea Ysize above abovecaptionskip abovedisplayshortskip abovedisplayskip abovewithdelims abstract abstractname abstractname{name} accent accentedsymbol acknowledgments active actualchar acute addcontentsline adddialect addlanguage addpenalty address addtime addto addtocontents addtocounter addtolength addtoreset addtoversion addvspace adjdemerits advance advancepageno afterassignment aftergroup afterpage aleph align align* alignat aligned allinethickness allocationnumber allowbreak allowdisplaybreaks allowhyphens alph alpha also amalg and angle annotations appendix appendixname approx approxeq arabic arc arccos arcsin arctan arg arraybackslash arraycolsep arrayrulewidth arraystretch arrowvert article ast astroncite asymp atop atopwithdelims author backepsilon backprime backsim backsimeq backslash badness bar barwedge baselineskip baselinestretch batchfile batchmode because begin beginchapter begindisplay begingroup beginsection begintt belowcaptionskip belowdisplayshortskip belowdisplayskip beta beth between bezier bf bfdefault bffam bfseries bgroup bibhang bibindent bibitem bibliography bibliographystyle bibliographyunit bibname bibpunct big bigbreak bigcap bigcirc bigcircle bigcup bigodot bigoplus bigotimes bigskip bigskipamount bigsqcup bigstar bigstrutjot bigtriangledown bigtriangleup bigtype biguplus bigvee bigwedge binom binoppenalty blacklozenge blacksquare blacktriangle blacktriangledown blacktriangleleft blacktriangleright bmit bmod body boldmath boldsymbol book boolean bordermatrix bot botfigrule botmark bottomcaption bottomfraction bottomnumber bowtie box boxdot boxed boxmaxdepth boxminus boxplus boxtimes brace braceld bracelu bracerd braceru bracevert brack branch branchlabels break breve brokenpenalty brush bslash buildrel bull bullet bumpeq bye cal cap caption captionwidth cases catcode cbend cbstart ccname cctart cctbook cdot cdotp cdots centerdot centering centerline cents cfoot cfrac changebarsep changebarwidth changes chapter chapter* chaptermark chaptername char chardef chead check chi choose chunk circ circeq circle circle* circlearrowleft circlearrowright circledS circledast circledcirc circleddash cite citeA citeN citeNP citen citeyear cleaders cleardoublepage clearemptydoublepage clearpage cleartabs cline closecurve closein closeout closing clubpenalty clubsuit colon color colorbox columns columnsep columnseprule columnwidth complement cong contentsline contentsname coprod copy copyright cornersize cos cosh cot coth count countdef cr csc csname cstok ctex ctexart ctexbook cup curlyeqprec curlyeqsucc curlyvee curlywedge curve curvearrowleft curvearrowright curvedashes curvesymbol cwfsu cwhbu cwku cwmu cwyu dag dagger daleth dash dashbox dashleftarrow dashline dashlinestretch dashrightarrow dashv date datelang day dbinom dblfigrule dblfloatpagefraction dblfloatsep dbltextfloatsep dbltopfraction dbltopnumber ddag ddagger ddddot dddot ddot ddots ddraft ddt deadcycles def defaulthyphenchar defaultscriptratio defaultscriptscriptratio defaultskewchar deffootnote definecounter deg delcode deletebarwidth delimiter delimiterfactor delimitershortfall delta depth description descriptionlabel det dfrac diagdown diagup diamond diamondpar diamondsuit digamma dim dimendef ding dingfill dingline discretionary displaybreak displayindent displaylimits displaylines displaymath displaystyle displaywidowpenalty displaywidth div divide divideontimes do docdate document documentclass documentstyle dominitoc dospecials dosupereject dot doteq doteqdot dotfill dotplus dots dotsb dotsc dotsep dotsi dotsm dottedline dottedtocline doublebarwedge doublebox doublehyphendemerits doublerulesep downarrow downbracefill downdownarrows downharpoonleft downharpoonright draw drawline drawlinestretch drawwith driver dummy dump edef egroup eightpoint eject ell ellipse else em emergencystretch emph empty emptyset encapchar encl enclname encodingdefault end endabstract endchapter endcsname enddisplay endfig endfoot endgraf endgroup endhead endinput endinsert endlastfoot endletter endline endlinechar endlist endnote endnotesize endpostamble endpreamble endquotation endtemplate endtt enlargethispage enlargethispage* enskip enspace ensuremath entrylabel epsf epsfbox epsfig epsfxsize epsfysize epsilon eqalign eqalignno eqcirc eqnarray eqref eqslantgtr eqslantless equal equation equiv errhelp errmessage errorcontextlines errorstopmode escapechar esper eta eth evenfoot evenhead evensidemargin everycr everydisplay everyhbox everyjob everymath everypar everyvbox excludeversion exercise exhyphenpenalty exists exp expandafter externaldocument extracolsep extralang extrarowheight extratabsurround extrealang faketableofcontents fallingdotseq fam family familydefault fancyplain fang fbaselineskip fbox fboxrule fboxsep fencoding ffamily fig figurename figureplace filbreak filedate filename fileversion fill filltype finalhyphendemerits firsthline firstmark fiverm flalign flalign* flat float floatingpenalty floatname floatpagefraction floatplacement floatsep flq flqq flushbottom flushcolumns flushleft flushright fminilength fmtname fmtversion fnsymbol folio font fontdimen fontencoding fontfamily fontname fontseries fontshape fontsize fontsubfuzz footheight footins footline footnote footnotemark footnoterule footnotesep footnotesize footnotetext footrule footrulewidth footskip for forall frac fracwithdelims frak frakfamily frame framebox frenchhyphenation frenchlayout frenchmacros frenchspacing frenchtranslation frenchtypography from fromname frontmatter frown frq frqq fshape fsize fullhsize fullline fussy futurelet futurenonspacelet gamma gather gathered gcd gdef ge generateFile geq geqq geqslant getfactor gets ggg gimel global globaldefs glossary glossaryentry glq glqq gnapprox gneq gneqq gnsim goodbreak gothfamily graphpaper grave grid grq grqq gtrapprox gtrdot gtreqless gtreqqless gtrless guillemotleft guillemotright guilsinglleft guilsinglright gvertneqq halign hang hangafter hangindent hat hbadness hbar hbox hdotsfor headheight headline headpagename headrule headrulewidth headsep headtoname headwidth heartpar heartsuit hei height help hfil hfill hfilneg hfuzz hglue hhline hideskip hidewidth hline hlinefill hlineon hodiau hodiaun hoffset holdinginserts hom hookleftarrow hookrightarrow hphantom hrule hrulefill hsize hskip hslash hspace hspace* hss ht huge hyphenation hyphenchar hyphenpenalty ialign icolorbox idotsint idxitem if ifcase ifcat ifdim ifeof iff iffalse ifhbox ifhmode ifinner iflanguage ifmmode ifmode ifnextchar ifnum ifodd ifstar ifthenelse iftrue ifundefined ifvbox ifvmode ifvoid ifx ignorespaces iiiint iiint iint imath immediate in inaccessible include includegraphics includegraphics* includeonly includeversion indent index indexentry indexname indexproofstyle indexspace inf infty init initfloatingfigs input inputlineno insert insertpenalties int intercal interdisplaylinepenalty interfootnotelinepenalty interlinepenalty intertext intextsep invisible iota iseries isodd isucaption it itdefault item itemindent itemize itemsep iterate itfam itshape jmath jobname joinrel jot jput kappa keepsilent ker kern kill label labelenumi labelenumii labelenumiii labelenumiv labelitemi labelitemii labelitemiii labelitemiv labelnum labelsep labelwidth label{key} lambda land landscape langle language large lastbox lasthline lastkern lastpenalty lastskip latexerr layout lbrace lccode lceil lcfrac ldotp ldots le leaders leadsto leaf leavevmode left leftarrow leftarrowfill leftarrowtail lefteqn leftharpoondown leftharpoonup lefthyphenmin leftleftarrows leftline leftmargin leftmargini leftmarginii leftmarginiii leftmarginiv leftmarginv leftmarginvi leftmark leftnode leftrightaquigarrow leftrightarrow leftrightarrows leftrightharpoons leftroot leftskip leftthreetimes legend lengthtest leq leqalignno leqno leqq leqslant lessapprox lessdot lesseqgtr lesseqqgtr lessgtr lesssim let letterspace levelchar lfloor lfoot lg lgroup lhd lhead lhook li lim liminf limits limsup line linebreak linepenalty lineskip lineskiplimit lineskiplimits linethickness linewidth lisitablename list listfigurename listfiles listing listof listoffigures listoftables listparindent listtablename llap llcorner llstparindent lmoustache ln lnapprox lneq lneqq lnot load log long longindentation longleftarrow longleftrightarrow longmapsto longpage longrightarrow loop looparrowleft looparrowright looseness lor lower lowercase lozenge lrcorner ltimes lusim lvertneqq mag magnification magstep magstephalf main mainmatter maintoks makeatletter makeatother makebox makecaption makefigcaption makefnmark makefntext makefootline makeglossary makeheadline makeindex makelabel makelabels maketitle mapsto mapstochar margin marginlabel marginpar marginparpush marginparsep marginparwidth mark markboth markright match mathaccent mathafal mathalpha mathbb mathbf mathbin mathcal mathchar mathchardef mathchoice mathclose mathcode mathellipsis mathfrak mathgroup mathhexbox mathindent mathinner mathit mathnormal mathop mathopen mathord mathpalette mathpunct mathrel mathrm mathsf mathsterling mathstrut mathsurround mathtt mathunderscore mathversion matrix matrixput max maxdeadcycles maxdepth maxdimen maxovaldiam mbox mddefault mdseries meaning measuredangle medbreak medmuskip medskip medskipamount medspace medtype message meta mho mid midinsert min minitoc mit mkboth mkern mne mod models month moveleft moveright mp mskip mth mu multicolsep multicolumn multiframe multimake multimap multiply multiput multiputlist multirow multirowsetup multispan multlinegap muskip muskipdef nLeftarrow nLeftrightarrow nRightarrow nYDash nabla namedef names nameuse narrower natural naturalwidth ncong ne nearrow neg negmedspace negthickspace negthinspace neq newX newY newblock newboolean newbox newcolumntype newcommand newcommand* newcount newcounter newdimen newenvironment newfam newfloat newfont newhelp newif newindex newinsert newlabel newlanguage newlength newletter newline newlinechar newmuskip newpage newread newsavebox newsavebox{box} newskip newtheorem newtoks newwrite nexists next ngeq ngeqq ngeqslant ngtr ninepoint ninerm ninesl nintt nlefirightarrow nleftarrow nleq nleqq nleqslant nless nmid noalign noboundary nobreak nochangebars nocite nocorr nocorrlist noexpand noextraslang nofiglist nofiles nofrenchlayout nofrenchtypography noindent nointerlineskip nolimits nolinebreak nomarkersintext nonfrenchspacing nonscript nonstopmode nonumber nopagebreak nopagenumbers normalbaselines normalbaselineskip normalbottom normalcolor normalem normalfont normallineskip normallineskiplimit normalmarginpar normalsize not notablist notag notin nouppercase nparallel nprec npreceq nrightarrow nshortmid nshortparallel nsim nsubseteq nsucc nsucceq nsupseteq nsupseteqq ntriangleleft ntrianglelefteq ntriangleright ntrianglerighteq nu null nulldelimiterspace nullfont number numberline numberwithin nvDash nwarrow oalign obeycr obeylines obeyspaces oddfoot oddhead oddsidemargin odot offinterlineskip oint oldstyle oldstylenums omega omicron ominus omit onecolumn onlynotes onlypreamble ooalign openin openout openup operatorname operatornamewithlimits oplus options or oslash other otimes outer output outputpenalty oval ovalbox over overbrace overfullrule overleftarrow overline overrightarrow overset overwithdelims owns pacs padraft pagebody pagebreak pagecolor pagecontents pagedepth pagefilllstretch pagefillstretch pagefilstretch pagegoal pageinsert pagename pageno pagenumbering pageref pageshrink pagestretch pagestyle pagetotal paperheight paperwidth par paragraph paragraphmark parallel parbox parfillskip parindent parsep parshape parskip part part* partial partname partopsep path patterns pausing penalty penumi penumii penumiii penumiv perp phantom phi pi pitchfork plainfootrulewidth plainheadrulewidth plainoutput plus pm pmatrix pmb pmod pnt pnumwidth pod poptabs postamble postdisplaypenalty postmulticols pounds preamble prec precapprox preccurlyeq preceq precnapprox precnsim precsim predisplaypenalty predisplaysize prefacename preloaded premulticols prenwd preparefootins preprint pretolerance prevdepth prevgraf prime printindex proclaim prod proofmodetrue propto protect providecommand psboxit psfig psfigdriver psfull psi pt ptsize pushtabs put putbib putfile qbezier qquad quad quotation quotechar quotedblbase quotesinglbase radical raggedbottom raggedcenter raggedcolumns raggedleft raggedright raise raisebox rangle ratio rbrace rbrack rceil rcfrac rcomment read real ref reflectbox refname refstepcounter reftextafter reftextbefore reftextcurrent reftextfaceafter reftextfacebefore reftextfarawy reftextvario relax relbar relpenalty removelastskip renewcommand renewcommand* renewenvironment renewenvironment* renewindex repeat resizebox resizebox* restorecr restylefloat resume reversemarginpar rfloor rfoot rgroup rhd rhead rho rhook right rightarrow rightarrowfill rightarrowtail rightharpoondown rightharpoonup righthyphenmin rightleftarrowa rightleftharpoons rightline rightmargin rightmark rightnode rightrightarrows rightskip rightsquigarrow rightthreetimes risingdotseq rlap rm rmdefault rmfamily rmoustache roman romannumeral root rotatebox rotcaption rotdriver rq rtimes rule sAppendix samepage savebox sbox sboxrule sboxsep scalebox scaleput scdefault scriptfont scriptscriptfont scriptscriptstyle scriptsize scriptspace scriptstyle scrollmode scshape sdim searrow sec seccntformat secdef section section* sectionmark seename selectfont selectlanguage seriesdefault setboolean setbox setcounter setdepth sethapace setlanguage setlength setlinestyle setlongtables setmargins setmarginsrb setminus setnumberpos setpapersize setprecision setstretch setstyle settabs settodepth settoheight settowidth setupverbatim setwidth setxaxis setxname setxvaluetyp setyaxis setyname sevenrm sfcode sfdefault sffamily sfsize shabox shadowbox shadowsize shapedefault shapepar sharp shipout shortcite shortciteA shortciteN shortindexingoff shortindexingon shortmid shortparallel shortstack show showbox showboxbreadth showboxdepth showcols showhyphens showlists showprogress showthe sideset sigma signature signed sim simeq sin sinh skew skewchar skip skipdef sl slash sldefault slfam slfamily sloppy slshape small smallbreak smallfrown smallint smallsetminus smallskip smallskipamount smallsmile smalltype smash smile song space spacefactor spaceskip spadesuit span spbreve spcheck spdddot spddot spdot special sphat sphericalangle spline split splitbotmark splitfirstmark splitmaxdepth splittopskip sptilde sqcap sqcup sqrt sqsubset sqsubseteq sqsupset sqsupseteq square squarepar ssfsize stackrel star startsection starttoc stepcounter stop stretch string strut strutbox subfigcapakip subfigtopakip subfigure subitem subject subparagraph subparagraph* subparagraphmark subsection subsection* subset subseteq subseteqq subsetneq subsetneqq subsubitem subsubsection subsubsection*{title} subsubsection[short]{title} subsubsectionmark{code} subsubsection{title} succ succapprox succcurlyeq succeq succnapprox succnsim succsim sum sup supereject supertabular suppressfloats suppressfloats[placement] supset supsetaqq supseteq supsetneq supsetneqq surd swabfamily swarrow symbol symbol{n} syntaxonly tabalign tabbing tabbingsep tabcolsep table tablecaption tablefirsthead tablehead tablelasttail tableline tablename tablenote tablenotemark tablenotetext tableofcontents tableplace tabletail tabs tabskip tabularnewline tabularxcolumn tag tagcurve tan tanh tau tbinom tbranch telephone tempboxa tenex tenpoint tenrm tensl tensy texlmd text textasciicircum textasciitilde textasteriskcentered textbackslash textbar textbf textbraceleft textbraceright textbullet textcircled textcolor textcompwordmark textdagger textdaggerdbl textdollar textellipsis textemdash textendash textexclamdown textfloatsep textfont textfraction textfrak textgoth textgreater textheight textindent textit textless textmd textnormal textparagraph textperiodcentered textquestiondown textquotedbl textquotedblleft textquotedblright textquoteleft textquoteright textregistered textrm textsc textsection textsf textsl textsterling textstyle textsuperscript textswab texttrademark texttt textunderscore textup textvisiblespace textwidth tfrac tfsize thanks the theCodelineNo thechapter theendnotes theenumi theenumii theenumiii theenumiv theequation thefigure thefnmark thefootnote thefootnotemark thehours theminutes thempfn thempfootnote themptootnote theorembodyfont theoremheaderfont theorempostskipamount theorempreskipamount theoremstyle thepage theparagraph thepart therefore thesection thesubfigure thesubparagraph thesubsection thesubsubsection theta thetable thickapprox thicklines thickmuskip thicksim thickspace thinlines thinmuskip thinspace thispagestyle thispagestyle{option} tighten tightenlines tilde time times tiny title titlepage tocrmarg today toks toksdef tolerance top topcaption topfigrule topfraction topglue topins topinsert topmargin topmark topnum topnumber topsep topskip toptigrule totalheight totalnumber tracingall tracingcommands tracingfonts tracinglostchars tracingmacros tracingonline tracingoutput tracingpages tracingparagraphs tracingrestores tracingstats tracingtabularx triangle triangledown triangleleft trianglelefteq triangleq triangleright trianglerighteq tt ttdefault ttfam ttfamily ttglue ttraggedright turnbox twlrm twocolumn twoheadleftarrow twoheadrightarrow typein typeout uccode uchyph ulcorner uline unboldmath uncatcodespecials undefined underbar underbrace underleftarrow underleftrightarrow underline underrightarrow underset unhbox unhcopy unitlength unkern unlhd unpenalty unrhd unskip unvbox unvcopy up uparrow upbracefill updefault updownarrow upharpoonleft upharpoonright uplus uppercase uproot upshape upsilon upuparrows urcorner usage usebox usecounter usefont usepackage vDash vadjust valign value varaupaetneq varepsilon varinjlim varkappa varliminf varlimsup varnothing varphi varpi varprojlim varpropto varrho varsigma varsupsetneqq vartheta vartriangle vartriangleleft vartriangleright vbadness vbox vcenter vdash vdots vec vector vee veebar verb verb* verbatim verbatim* verbatimchar verbatiminput verbatimtabinput verse vert vfil vfill vfilll vfilneg vfootnote vfuzz vglue visible vline voffset voidbx vpageref vphantom vref vrule vsize vskip vspace vspace* vsplit vss vtop warning wedge whiledo widehat widetilde widowpenalty width wlog write xdef xi xleaders xout xspace xspaceskip xyzzy year you zeta zskip"
  return autocomplete_set
end

function latex.create_bakup(path)
  local latex_code = {
    "user_latex = {}\n",
    "\n",
    "require(\"eu_sci\")\n",
    "require(\"eu_core\")\n",
    "\n",
    "function user_latex.init_after_callback(p)\n",
    "  local pnode = eu_core.ffi.cast(\"void *\", p)\n",
    "  local res = eu_core.euapi.on_doc_init_after_scilexer(pnode, \"latex\")  -- enable latex lex\n",
    "  if (res == 0) then\n",
    "    eu_core.euapi.on_doc_enable_foldline(pnode)                         -- enable fold line\n",
    "  end\n",
    "  return res\n",
    "end\n",
    "\n",
    "function user_latex.get_comments()\n",
    "  -- 行注释与块注释, 注释头与注释尾用&&分开\n",
    "  local line_t = \"% \"\n",
    "  local block_t = \"\\\\begin{comment}&&\\\\end{comment}\"\n",
    "  return line_t, block_t\n",
    "end\n",
    "\n",
    "function user_latex.get_styles()\n",
    "  local style_t = {\n",
    "    [SCE_L_COMMENT] = 0xC0C0C0,\n",
    "    [SCE_L_COMMENT2] = 0xC0C0C0,\n",
    "    -- 给关键字加上粗体\n",
    "    [SCE_L_COMMAND] = 0x00B050 + SCE_BOLD_FONT,\n",
    "    [SCE_L_SHORTCMD] = 0x00B050,\n",
    "    [SCE_L_CMDOPT] = 0xBBBB00 + SCE_BOLD_FONT,\n",
    "    [SCE_L_TAG] = 0xC080FF,\n",
    "    [SCE_L_TAG2] = 0xC080FF,\n",
    "  }\n",
    "  return style_t\n",
    "end\n",
    "\n",
    "function user_latex.get_autocomplete()\n",
    "  local autocomplete_set = \"Alph Alpha AltMacroFont AmSTeX Appendix Arrowvert AtBeginDocument AtEndClass AtEndDocument AtEndOfClass AtEndOfPackage AtEndPackage Bbb Bbbk Beta BibTeX Big Box CJK CJK* CJKfamily Cap CharacterTable CheckCommand CheckCommand* CheckModules CheckSum ClassError ClassInfo ClassWarning ClassWarningNoLine CodelineFont CodelineIndex CodelineNumbered CurrentOption DeclareErrorFont DeclareFixedFont DeclareFontEncoding DeclareFontEncodingDefaults DeclareFontFamily DeclareFontShape DeclareFontSubstitution DeclareInputMath DeclareInputText DeclareMathAccent DeclareMathAlphabet DeclareMathSizes DeclareMathSymbol DeclareMathVersion DeclareOldFontCommand DeclareOption DeclareOption* DeclareRobustCommand DeclareRobustCommand* DeclareSymbolFont DeclareSymbolFontAlphabet DeclareTextAccent DeclareTextAccentDefault DeclareTextCommand DeclareTextCommandDefault DeclareTextCompositeCommand DeclareTextFontCommand DeclareTextSymbol DeclareTextSymbolDefault DeleteShortVerb Delta DescribeEnv DescribeEnvironment DescribeMacro Diamond DisableCrossrefs DoNotIndex DocInput DocstyleParms DontCheckModules Downarrow EnableCrossrefs Esper EuFrak EuScript ExecuteOptions Finale Finv GBK Game Gamma GapDepth GapWidth GetFileInfo GlossaryMin GlossaryParms GlossaryPrologue HUGE Huge IfFileExists Im IndexInput IndexMin IndexParms IndexPrologue InputIfFileExists Join LARGE LTcapuidth LTchunksize LTleft LTpost LTpre LTright LaTeX LaTeXe Lambda Large Leftarrow Leftrightarrow Lentrylabel Lleftarrow LoadClass Longleftarrow Longleftrightarrow Longrightarrow Lsh MacroFont MacroIndent MacrocodeTopsep MakeLowercase MakePrivateLetters MakeShortVerb MakeUppercase Mentry Mentrylabel Module Msgrigid NeedsTeXFormat{format} NouveauLangage Omega OnlyDescription OptionNotUsed Ovalbox PScommands PackageError PackageInfo PackageWarning PackageWarningNoLine PageIndex PassOptionsToClass PassOptionsToPackage Phi Pi Pifill Pifont Piline Pisymbol PreserveBackslash PrintChanges PrintDescribeEnv PrintDescribeMacro PrintIndex PrintMacroName ProcessOptions ProcessOptions* ProvideTextCommand ProvideTextCommandDefault ProvidesClass ProvidesFile ProvidesPackage Psi REVTeX Re RecordChanges Relbar RequirePackage Rightarrow Roman Rsh SS SetMathAlphabet SetSymbolFont Sigma SortIndex SortNoop SpecialEnvIndex SpecialEscapechar SpecialIndex SpecialMainIndex SpecialUsageIndex StopEventually Subset Supset TH TeX TheSbox Theta Thicklines ULforem UTF8 Uparrow Updownarrow Upsilon Vdash Vert Vvdeah WideMargins Xarea XeTeX Xi Xsize Yarea Ysize above abovecaptionskip abovedisplayshortskip abovedisplayskip abovewithdelims abstract abstractname abstractname{name} accent accentedsymbol acknowledgments active actualchar acute addcontentsline adddialect addlanguage addpenalty address addtime addto addtocontents addtocounter addtolength addtoreset addtoversion addvspace adjdemerits advance advancepageno afterassignment aftergroup afterpage aleph align align* alignat aligned allinethickness allocationnumber allowbreak allowdisplaybreaks allowhyphens alph alpha also amalg and angle annotations appendix appendixname approx approxeq arabic arc arccos arcsin arctan arg arraybackslash arraycolsep arrayrulewidth arraystretch arrowvert article ast astroncite asymp atop atopwithdelims author backepsilon backprime backsim backsimeq backslash badness bar barwedge baselineskip baselinestretch batchfile batchmode because begin beginchapter begindisplay begingroup beginsection begintt belowcaptionskip belowdisplayshortskip belowdisplayskip beta beth between bezier bf bfdefault bffam bfseries bgroup bibhang bibindent bibitem bibliography bibliographystyle bibliographyunit bibname bibpunct big bigbreak bigcap bigcirc bigcircle bigcup bigodot bigoplus bigotimes bigskip bigskipamount bigsqcup bigstar bigstrutjot bigtriangledown bigtriangleup bigtype biguplus bigvee bigwedge binom binoppenalty blacklozenge blacksquare blacktriangle blacktriangledown blacktriangleleft blacktriangleright bmit bmod body boldmath boldsymbol book boolean bordermatrix bot botfigrule botmark bottomcaption bottomfraction bottomnumber bowtie box boxdot boxed boxmaxdepth boxminus boxplus boxtimes brace braceld bracelu bracerd braceru bracevert brack branch branchlabels break breve brokenpenalty brush bslash buildrel bull bullet bumpeq bye cal cap caption captionwidth cases catcode cbend cbstart ccname cctart cctbook cdot cdotp cdots centerdot centering centerline cents cfoot cfrac changebarsep changebarwidth changes chapter chapter* chaptermark chaptername char chardef chead check chi choose chunk circ circeq circle circle* circlearrowleft circlearrowright circledS circledast circledcirc circleddash cite citeA citeN citeNP citen citeyear cleaders cleardoublepage clearemptydoublepage clearpage cleartabs cline closecurve closein closeout closing clubpenalty clubsuit colon color colorbox columns columnsep columnseprule columnwidth complement cong contentsline contentsname coprod copy copyright cornersize cos cosh cot coth count countdef cr csc csname cstok ctex ctexart ctexbook cup curlyeqprec curlyeqsucc curlyvee curlywedge curve curvearrowleft curvearrowright curvedashes curvesymbol cwfsu cwhbu cwku cwmu cwyu dag dagger daleth dash dashbox dashleftarrow dashline dashlinestretch dashrightarrow dashv date datelang day dbinom dblfigrule dblfloatpagefraction dblfloatsep dbltextfloatsep dbltopfraction dbltopnumber ddag ddagger ddddot dddot ddot ddots ddraft ddt deadcycles def defaulthyphenchar defaultscriptratio defaultscriptscriptratio defaultskewchar deffootnote definecounter deg delcode deletebarwidth delimiter delimiterfactor delimitershortfall delta depth description descriptionlabel det dfrac diagdown diagup diamond diamondpar diamondsuit digamma dim dimendef ding dingfill dingline discretionary displaybreak displayindent displaylimits displaylines displaymath displaystyle displaywidowpenalty displaywidth div divide divideontimes do docdate document documentclass documentstyle dominitoc dospecials dosupereject dot doteq doteqdot dotfill dotplus dots dotsb dotsc dotsep dotsi dotsm dottedline dottedtocline doublebarwedge doublebox doublehyphendemerits doublerulesep downarrow downbracefill downdownarrows downharpoonleft downharpoonright draw drawline drawlinestretch drawwith driver dummy dump edef egroup eightpoint eject ell ellipse else em emergencystretch emph empty emptyset encapchar encl enclname encodingdefault end endabstract endchapter endcsname enddisplay endfig endfoot endgraf endgroup endhead endinput endinsert endlastfoot endletter endline endlinechar endlist endnote endnotesize endpostamble endpreamble endquotation endtemplate endtt enlargethispage enlargethispage* enskip enspace ensuremath entrylabel epsf epsfbox epsfig epsfxsize epsfysize epsilon eqalign eqalignno eqcirc eqnarray eqref eqslantgtr eqslantless equal equation equiv errhelp errmessage errorcontextlines errorstopmode escapechar esper eta eth evenfoot evenhead evensidemargin everycr everydisplay everyhbox everyjob everymath everypar everyvbox excludeversion exercise exhyphenpenalty exists exp expandafter externaldocument extracolsep extralang extrarowheight extratabsurround extrealang faketableofcontents fallingdotseq fam family familydefault fancyplain fang fbaselineskip fbox fboxrule fboxsep fencoding ffamily fig figurename figureplace filbreak filedate filename fileversion fill filltype finalhyphendemerits firsthline firstmark fiverm flalign flalign* flat float floatingpenalty floatname floatpagefraction floatplacement floatsep flq flqq flushbottom flushcolumns flushleft flushright fminilength fmtname fmtversion fnsymbol folio font fontdimen fontencoding fontfamily fontname fontseries fontshape fontsize fontsubfuzz footheight footins footline footnote footnotemark footnoterule footnotesep footnotesize footnotetext footrule footrulewidth footskip for forall frac fracwithdelims frak frakfamily frame framebox frenchhyphenation frenchlayout frenchmacros frenchspacing frenchtranslation frenchtypography from fromname frontmatter frown frq frqq fshape fsize fullhsize fullline fussy futurelet futurenonspacelet gamma gather gathered gcd gdef ge generateFile geq geqq geqslant getfactor gets ggg gimel global globaldefs glossary glossaryentry glq glqq gnapprox gneq gneqq gnsim goodbreak gothfamily graphpaper grave grid grq grqq gtrapprox gtrdot gtreqless gtreqqless gtrless guillemotleft guillemotright guilsinglleft guilsinglright gvertneqq halign hang hangafter hangindent hat hbadness hbar hbox hdotsfor headheight headline headpagename headrule headrulewidth headsep headtoname headwidth heartpar heartsuit hei height help hfil hfill hfilneg hfuzz hglue hhline hideskip hidewidth hline hlinefill hlineon hodiau hodiaun hoffset holdinginserts hom hookleftarrow hookrightarrow hphantom hrule hrulefill hsize hskip hslash hspace hspace* hss ht huge hyphenation hyphenchar hyphenpenalty ialign icolorbox idotsint idxitem if ifcase ifcat ifdim ifeof iff iffalse ifhbox ifhmode ifinner iflanguage ifmmode ifmode ifnextchar ifnum ifodd ifstar ifthenelse iftrue ifundefined ifvbox ifvmode ifvoid ifx ignorespaces iiiint iiint iint imath immediate in inaccessible include includegraphics includegraphics* includeonly includeversion indent index indexentry indexname indexproofstyle indexspace inf infty init initfloatingfigs input inputlineno insert insertpenalties int intercal interdisplaylinepenalty interfootnotelinepenalty interlinepenalty intertext intextsep invisible iota iseries isodd isucaption it itdefault item itemindent itemize itemsep iterate itfam itshape jmath jobname joinrel jot jput kappa keepsilent ker kern kill label labelenumi labelenumii labelenumiii labelenumiv labelitemi labelitemii labelitemiii labelitemiv labelnum labelsep labelwidth label{key} lambda land landscape langle language large lastbox lasthline lastkern lastpenalty lastskip latexerr layout lbrace lccode lceil lcfrac ldotp ldots le leaders leadsto leaf leavevmode left leftarrow leftarrowfill leftarrowtail lefteqn leftharpoondown leftharpoonup lefthyphenmin leftleftarrows leftline leftmargin leftmargini leftmarginii leftmarginiii leftmarginiv leftmarginv leftmarginvi leftmark leftnode leftrightaquigarrow leftrightarrow leftrightarrows leftrightharpoons leftroot leftskip leftthreetimes legend lengthtest leq leqalignno leqno leqq leqslant lessapprox lessdot lesseqgtr lesseqqgtr lessgtr lesssim let letterspace levelchar lfloor lfoot lg lgroup lhd lhead lhook li lim liminf limits limsup line linebreak linepenalty lineskip lineskiplimit lineskiplimits linethickness linewidth lisitablename list listfigurename listfiles listing listof listoffigures listoftables listparindent listtablename llap llcorner llstparindent lmoustache ln lnapprox lneq lneqq lnot load log long longindentation longleftarrow longleftrightarrow longmapsto longpage longrightarrow loop looparrowleft looparrowright looseness lor lower lowercase lozenge lrcorner ltimes lusim lvertneqq mag magnification magstep magstephalf main mainmatter maintoks makeatletter makeatother makebox makecaption makefigcaption makefnmark makefntext makefootline makeglossary makeheadline makeindex makelabel makelabels maketitle mapsto mapstochar margin marginlabel marginpar marginparpush marginparsep marginparwidth mark markboth markright match mathaccent mathafal mathalpha mathbb mathbf mathbin mathcal mathchar mathchardef mathchoice mathclose mathcode mathellipsis mathfrak mathgroup mathhexbox mathindent mathinner mathit mathnormal mathop mathopen mathord mathpalette mathpunct mathrel mathrm mathsf mathsterling mathstrut mathsurround mathtt mathunderscore mathversion matrix matrixput max maxdeadcycles maxdepth maxdimen maxovaldiam mbox mddefault mdseries meaning measuredangle medbreak medmuskip medskip medskipamount medspace medtype message meta mho mid midinsert min minitoc mit mkboth mkern mne mod models month moveleft moveright mp mskip mth mu multicolsep multicolumn multiframe multimake multimap multiply multiput multiputlist multirow multirowsetup multispan multlinegap muskip muskipdef nLeftarrow nLeftrightarrow nRightarrow nYDash nabla namedef names nameuse narrower natural naturalwidth ncong ne nearrow neg negmedspace negthickspace negthinspace neq newX newY newblock newboolean newbox newcolumntype newcommand newcommand* newcount newcounter newdimen newenvironment newfam newfloat newfont newhelp newif newindex newinsert newlabel newlanguage newlength newletter newline newlinechar newmuskip newpage newread newsavebox newsavebox{box} newskip newtheorem newtoks newwrite nexists next ngeq ngeqq ngeqslant ngtr ninepoint ninerm ninesl nintt nlefirightarrow nleftarrow nleq nleqq nleqslant nless nmid noalign noboundary nobreak nochangebars nocite nocorr nocorrlist noexpand noextraslang nofiglist nofiles nofrenchlayout nofrenchtypography noindent nointerlineskip nolimits nolinebreak nomarkersintext nonfrenchspacing nonscript nonstopmode nonumber nopagebreak nopagenumbers normalbaselines normalbaselineskip normalbottom normalcolor normalem normalfont normallineskip normallineskiplimit normalmarginpar normalsize not notablist notag notin nouppercase nparallel nprec npreceq nrightarrow nshortmid nshortparallel nsim nsubseteq nsucc nsucceq nsupseteq nsupseteqq ntriangleleft ntrianglelefteq ntriangleright ntrianglerighteq nu null nulldelimiterspace nullfont number numberline numberwithin nvDash nwarrow oalign obeycr obeylines obeyspaces oddfoot oddhead oddsidemargin odot offinterlineskip oint oldstyle oldstylenums omega omicron ominus omit onecolumn onlynotes onlypreamble ooalign openin openout openup operatorname operatornamewithlimits oplus options or oslash other otimes outer output outputpenalty oval ovalbox over overbrace overfullrule overleftarrow overline overrightarrow overset overwithdelims owns pacs padraft pagebody pagebreak pagecolor pagecontents pagedepth pagefilllstretch pagefillstretch pagefilstretch pagegoal pageinsert pagename pageno pagenumbering pageref pageshrink pagestretch pagestyle pagetotal paperheight paperwidth par paragraph paragraphmark parallel parbox parfillskip parindent parsep parshape parskip part part* partial partname partopsep path patterns pausing penalty penumi penumii penumiii penumiv perp phantom phi pi pitchfork plainfootrulewidth plainheadrulewidth plainoutput plus pm pmatrix pmb pmod pnt pnumwidth pod poptabs postamble postdisplaypenalty postmulticols pounds preamble prec precapprox preccurlyeq preceq precnapprox precnsim precsim predisplaypenalty predisplaysize prefacename preloaded premulticols prenwd preparefootins preprint pretolerance prevdepth prevgraf prime printindex proclaim prod proofmodetrue propto protect providecommand psboxit psfig psfigdriver psfull psi pt ptsize pushtabs put putbib putfile qbezier qquad quad quotation quotechar quotedblbase quotesinglbase radical raggedbottom raggedcenter raggedcolumns raggedleft raggedright raise raisebox rangle ratio rbrace rbrack rceil rcfrac rcomment read real ref reflectbox refname refstepcounter reftextafter reftextbefore reftextcurrent reftextfaceafter reftextfacebefore reftextfarawy reftextvario relax relbar relpenalty removelastskip renewcommand renewcommand* renewenvironment renewenvironment* renewindex repeat resizebox resizebox* restorecr restylefloat resume reversemarginpar rfloor rfoot rgroup rhd rhead rho rhook right rightarrow rightarrowfill rightarrowtail rightharpoondown rightharpoonup righthyphenmin rightleftarrowa rightleftharpoons rightline rightmargin rightmark rightnode rightrightarrows rightskip rightsquigarrow rightthreetimes risingdotseq rlap rm rmdefault rmfamily rmoustache roman romannumeral root rotatebox rotcaption rotdriver rq rtimes rule sAppendix samepage savebox sbox sboxrule sboxsep scalebox scaleput scdefault scriptfont scriptscriptfont scriptscriptstyle scriptsize scriptspace scriptstyle scrollmode scshape sdim searrow sec seccntformat secdef section section* sectionmark seename selectfont selectlanguage seriesdefault setboolean setbox setcounter setdepth sethapace setlanguage setlength setlinestyle setlongtables setmargins setmarginsrb setminus setnumberpos setpapersize setprecision setstretch setstyle settabs settodepth settoheight settowidth setupverbatim setwidth setxaxis setxname setxvaluetyp setyaxis setyname sevenrm sfcode sfdefault sffamily sfsize shabox shadowbox shadowsize shapedefault shapepar sharp shipout shortcite shortciteA shortciteN shortindexingoff shortindexingon shortmid shortparallel shortstack show showbox showboxbreadth showboxdepth showcols showhyphens showlists showprogress showthe sideset sigma signature signed sim simeq sin sinh skew skewchar skip skipdef sl slash sldefault slfam slfamily sloppy slshape small smallbreak smallfrown smallint smallsetminus smallskip smallskipamount smallsmile smalltype smash smile song space spacefactor spaceskip spadesuit span spbreve spcheck spdddot spddot spdot special sphat sphericalangle spline split splitbotmark splitfirstmark splitmaxdepth splittopskip sptilde sqcap sqcup sqrt sqsubset sqsubseteq sqsupset sqsupseteq square squarepar ssfsize stackrel star startsection starttoc stepcounter stop stretch string strut strutbox subfigcapakip subfigtopakip subfigure subitem subject subparagraph subparagraph* subparagraphmark subsection subsection* subset subseteq subseteqq subsetneq subsetneqq subsubitem subsubsection subsubsection*{title} subsubsection[short]{title} subsubsectionmark{code} subsubsection{title} succ succapprox succcurlyeq succeq succnapprox succnsim succsim sum sup supereject supertabular suppressfloats suppressfloats[placement] supset supsetaqq supseteq supsetneq supsetneqq surd swabfamily swarrow symbol symbol{n} syntaxonly tabalign tabbing tabbingsep tabcolsep table tablecaption tablefirsthead tablehead tablelasttail tableline tablename tablenote tablenotemark tablenotetext tableofcontents tableplace tabletail tabs tabskip tabularnewline tabularxcolumn tag tagcurve tan tanh tau tbinom tbranch telephone tempboxa tenex tenpoint tenrm tensl tensy texlmd text textasciicircum textasciitilde textasteriskcentered textbackslash textbar textbf textbraceleft textbraceright textbullet textcircled textcolor textcompwordmark textdagger textdaggerdbl textdollar textellipsis textemdash textendash textexclamdown textfloatsep textfont textfraction textfrak textgoth textgreater textheight textindent textit textless textmd textnormal textparagraph textperiodcentered textquestiondown textquotedbl textquotedblleft textquotedblright textquoteleft textquoteright textregistered textrm textsc textsection textsf textsl textsterling textstyle textsuperscript textswab texttrademark texttt textunderscore textup textvisiblespace textwidth tfrac tfsize thanks the theCodelineNo thechapter theendnotes theenumi theenumii theenumiii theenumiv theequation thefigure thefnmark thefootnote thefootnotemark thehours theminutes thempfn thempfootnote themptootnote theorembodyfont theoremheaderfont theorempostskipamount theorempreskipamount theoremstyle thepage theparagraph thepart therefore thesection thesubfigure thesubparagraph thesubsection thesubsubsection theta thetable thickapprox thicklines thickmuskip thicksim thickspace thinlines thinmuskip thinspace thispagestyle thispagestyle{option} tighten tightenlines tilde time times tiny title titlepage tocrmarg today toks toksdef tolerance top topcaption topfigrule topfraction topglue topins topinsert topmargin topmark topnum topnumber topsep topskip toptigrule totalheight totalnumber tracingall tracingcommands tracingfonts tracinglostchars tracingmacros tracingonline tracingoutput tracingpages tracingparagraphs tracingrestores tracingstats tracingtabularx triangle triangledown triangleleft trianglelefteq triangleq triangleright trianglerighteq tt ttdefault ttfam ttfamily ttglue ttraggedright turnbox twlrm twocolumn twoheadleftarrow twoheadrightarrow typein typeout uccode uchyph ulcorner uline unboldmath uncatcodespecials undefined underbar underbrace underleftarrow underleftrightarrow underline underrightarrow underset unhbox unhcopy unitlength unkern unlhd unpenalty unrhd unskip unvbox unvcopy up uparrow upbracefill updefault updownarrow upharpoonleft upharpoonright uplus uppercase uproot upshape upsilon upuparrows urcorner usage usebox usecounter usefont usepackage vDash vadjust valign value varaupaetneq varepsilon varinjlim varkappa varliminf varlimsup varnothing varphi varpi varprojlim varpropto varrho varsigma varsupsetneqq vartheta vartriangle vartriangleleft vartriangleright vbadness vbox vcenter vdash vdots vec vector vee veebar verb verb* verbatim verbatim* verbatimchar verbatiminput verbatimtabinput verse vert vfil vfill vfilll vfilneg vfootnote vfuzz vglue visible vline voffset voidbx vpageref vphantom vref vrule vsize vskip vspace vspace* vsplit vss vtop warning wedge whiledo widehat widetilde widowpenalty width wlog write xdef xi xleaders xout xspace xspaceskip xyzzy year you zeta zskip\"\n",
    "  return autocomplete_set\n",
    "end\n",
    "\n",
    "return user_latex",
  }
  local shell_code = table.concat(latex_code)
  eu_core.save_file(path, shell_code)
  shell_code = nil
  latex_code = nil
end

return latex