julia = {}

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

function julia.init_after_callback(p)
  local pnode = eu_core.ffi.cast("void *", p)
  local res = eu_core.euapi.on_doc_init_after_scilexer(pnode, "julia")
  if (res ~= 1) then
    eu_core.euapi.on_doc_enable_foldline(pnode)                                               -- enable fold line
    eu_core.euapi.on_doc_keyword_light(pnode, SCE_JULIA_KEYWORD1, 0, 0)                       -- 3, SCE_JULIA_KEYWORD1, keywords0
    eu_core.euapi.on_doc_keyword_light(pnode, SCE_JULIA_KEYWORD2, 1, 0x0080FF)                -- 4, SCE_JULIA_KEYWORD2, keywords1
    eu_core.euapi.on_doc_keyword_light(pnode, SCE_JULIA_KEYWORD3, 2, 0x307300)                -- 5, SCE_JULIA_KEYWORD3, keywords2
    eu_core.euapi.on_doc_keyword_light(pnode, SCE_JULIA_KEYWORD4, 3, 0)                       -- 20, SCE_JULIA_KEYWORD4, keywords3
    eu_core.euapi.on_doc_marcro_light(pnode, SCE_JULIA_MACRO, 4, 0xFF8000)
    eu_core.euapi.on_doc_comment_light(pnode, SCE_JULIA_COMMENT, 0)
    eu_core.euapi.on_doc_string_light(pnode, SCE_JULIA_DOCSTRING, 0x008080)
    eu_core.euapi.on_doc_string_light(pnode, SCE_JULIA_STRING, 0x008000)
  end
  return res
end

function julia.get_keywords()
  -- 1, reserved keywords
  local keywords0_set = "abstract baremodule begin break catch const continue do else elseif end export finally for function global if import in isa let local macro module mutable primitive quote return struct try type using var where while baremodule begin do for function if let macro module quote struct try type while"
  -- 2, type
  local keywords1_set = "AbstractArray AbstractArrayStyle AbstractChannel AbstractChar AbstractDict AbstractDisplay AbstractFloat AbstractIrrational AbstractLock AbstractLogger AbstractMatrix AbstractRNG AbstractRange AbstractSet AbstractSparseArray AbstractSparseMatrix AbstractSparseVector AbstractString AbstractUnitRange AbstractVecOrMat AbstractVector AbstractWorkerPool Adjoint Anonymous Any ArgumentError Array ArrayStyle AssertionError AsyncCondition Atomic Base64DecodePipe Base64EncodePipe Bidiagonal BigFloat BigInt BitArray BitMatrix BitSet BitVector Bool BoundsError BroadcastStyle CFunction CapturedException CartesianIndex CartesianIndices Cchar Cdouble Cfloat Channel Char Cint Cintmax_t Clong Clonglong ClusterManager Cmd Colon Complex ComplexF16 ComplexF32 ComplexF64 CompositeException CompoundPeriod Condition ConsoleLogger Cptrdiff_t Cshort Csize_t Cssize_t Cstring Cuchar Cuint Cuintmax_t Culong Culonglong Cushort Cwchar_t Cwstring DataType Date DateFormat DateTime Day DefaultArrayStyle DenseArray DenseMatrix DenseVecOrMat DenseVector Diagonal Dict DimensionMismatch Dims DivideError DomainError EOFError Enum EnvDict ErrorException Event Exception ExponentialBackOff Expr Float16 Float32 Float64 Function Future Givens GlobalRef Hermitian Hour IO IOBuffer IOContext IOStream IPAddr IPv4 IPv6 IdDict ImmutableDict IndexCartesian IndexLinear IndexStyle InexactError InitError Instant Int Int128 Int16 Int32 Int64 Int8 Integer InterruptException InvalidStateException Irrational IteratorEltype IteratorSize KeyError LinRange LineNumberNode LinearIndices LoadError LogLevel LowerTriangular MIME Matrix MersenneTwister Method MethodError Microsecond Millisecond Minute Missing MissingException Module Month Mutex NTuple NamedTuple Nanosecond Nothing NullLogger Number OneTo OrdinalRange OutOfMemoryError OverflowError Pair Pairs PartialQuickSort Period PermutedDimsArray Pipe PipeBuffer PosDefException ProcessFailedException Ptr QR QRCompactWY QRPivoted QuoteNode Random RandomDevice Rational RawFD ReadOnlyMemoryError Real ReentrantLock Ref Regex RegexMatch RemoteChannel RemoteException RoundingMode Second SegmentationFault Semaphore Serialization Set SharedArray SharedMatrix SharedVector Signed SimpleLogger SingularException Some SparseMatrixCSC SparseVector SpinLock StackFrame StackOverflowError StackTrace Stateful StepRange StepRangeLen StridedArray StridedMatrix StridedVecOrMat StridedVector String StringIndexError SubArray SubString SubstitutionString SymTridiagonal Symbol Symmetric SystemError TCPSocket Task TextDisplay Time TimeType Timer TmStruct Transpose Tridiagonal Tuple Type TypeError TypeVar UDPSocket UInt UInt128 UInt16 UInt32 UInt64 UInt8 UTInstant UndefInitializer UndefKeywordError UndefRefError UndefVarError UniformScaling Union UnionAll UnitLowerTriangular UnitRange UnitUpperTriangular Unsigned UpperTriangular Val Vararg VecElement VecOrMat Vector VersionNumber WeakKeyDict WeakRef Week WorkerConfig WorkerPool Year"
  -- 3, constant
  local keywords2_set = "ARCH ARGS BINDIR CPU_THREADS C_NULL Cvoid DEPOT_PATH ENDIAN_BOM ENV Inf Inf16 Inf32 Inf64 InsertionSort KERNEL LOAD_PATH MACHINE MergeSort NaN NaN16 NaN32 NaN64 PROGRAM_FILE QuickSort RoundDown RoundFromZero RoundNearest RoundNearestTiesAway RoundNearestTiesUp RoundToZero RoundUp VERSION WORD_SIZE ans catalan devnull eulergamma false golden im missing nothing pi stderr stdin stdout true undef"
  -- 4, module and function
  local keywords3_set = "Base Base64 Broadcast CRC32c Checked Core CoreLogging Dates DelimitedFiles Distributed Docs FastMath FileWatching Filesystem GC Grisu Intrinsics Iterators IteratorsMD Libc LinearAlgebra MPFR Main Math MathConstants Meta Mmap Multimedia Printf Profile Rounding SharedArrays Sockets Sort SparseArrays StackTraces Statistics Sys Test Threads UUIDs Unicode abs2 abspath accept acos acosd acosh acot acotd acoth acsc acscd acsch Ac_ldiv_B Ac_ldiv_Bc Ac_mul_B Ac_mul_Bc Ac_rdiv_B Ac_rdiv_Bc addprocs airy airyai airyaiprime airybi airybiprime airyprime airyx all all! angle any any! append! applicable ArgumentError Array ascii asec asecd asech asin asind asinh assert AssertionError atan atan2 atand atanh atexit atreplinit At_ldiv_B At_ldiv_Bt At_mul_B At_mul_Bt At_rdiv_B At_rdiv_Bt A_ldiv_Bc A_ldiv_Bt A_mul_B! A_mul_Bc A_mul_Bt A_rdiv_Bc A_rdiv_Bt backtrace base base64decode Base64DecodePipe base64encode Base64EncodePipe basename besselh besseli besselix besselj besselj0 besselj1 besseljx besselk besselkx bessely bessely0 bessely1 besselyx beta Bidiagonal big BigFloat BigInt bin bind binomial bitbroadcast bitpack bitrand bits bitunpack bkfact bkfact! BoundsError broadcast broadcast! broadcast!_function broadcast_function broadcast_getindex broadcast_setindex! bswap bytes2hex bytestring call cat catch_backtrace cbrt cconvert cd ceil cell cfunction cglobal Channel charwidth checkbounds chmod cholfact cholfact! chomp chop chr2ind circshift cis clamp cld clipboard close cmp code_llvm code_lowered code_native code_typed code_warntype combinations compilecache complement complement! complex cond Condition condskeel conj conj! connect consume contains conv conv2 convert copy copy! copysign cos cosc cosd cosh cospi cot cotd coth count countfrom countlines count_ones count_zeros cp cross csc cscd csch ctime ctranspose ctranspose! cummax cummin cumprod cumprod! cumsum cumsum! cumsum_kbn current_module cycle dawson dec deconv deepcopy deg2rad delete! deleteat! den deserialize det detach diag diagind diagm Dict diff digamma digits digits! DimensionMismatch dirname disable_sigint display displayable div DivideError divrem DomainError done dot download drop dump eachindex eachline eachmatch edit eig eigfact eigfact! eigmax eigmin eigvals eigvecs eltype empty! endof endswith enumerate EnvHash eof EOFError eps erf erfc erfcinv erfcx erfi erfinv error ErrorException esc escape_string eta eval evalfile exit exp exp10 exp2 expand expanduser expm expm1 exponent extrema eye factor factorial factorize falses fd fdio fetch fieldnames fieldoffsets fieldtype filemode filesize fill fill! filt filt! filter filter! finalize finalizer find findfirst findin findlast findmax findmin findn findnext findnz findprev first fld fldmod flipbits! flipdim flipsign float Float32 Float64 floor flush fma foldl foldr frexp full fullname functionloc function_module function_name gamma gc gcd gcdx gc_enable gensym get get! getaddrinfo getfield gethostname getindex getipaddr getkey getpid getsockname get_bigfloat_precision get_rounding get_zero_subnormals gperm gradient graphemes hankelh1 hankelh1x hankelh2 hankelh2x hash haskey hcat hessfact hessfact! hex hex2bytes hex2num hist hist! hist2d hist2d! histrange homedir htol hton hvcat hypot identity ifelse ignorestatus imag include_dependency include_string ind2chr ind2sub indexin indexpids indmax indmin InexactError inf info InitError init_worker insert! instances interrupt InterruptException intersect intersect! IntSet inv invdigamma invmod invoke invperm IOBuffer ipermute! ipermutedims IPv4 IPv6 is isa isabspath isalnum isalpha isapprox isascii isbits isblockdev ischardev iscntrl isconst isdefined isdiag isdigit isdir isdirpath iseltype isempty isequal iseven isexecutable isfifo isfile isfinite isgeneric isgraph ishermitian isimmutable isinf isinteger isinteractive isleaftype isless islink islower ismarked ismatch ismount isnan isnull isnumber isodd isopen ispath isperm isposdef isposdef! ispow2 isprime isprint ispunct isqrt isreadable isreadonly isready isreal issetgid issetuid issocket issorted isspace issticky issubnormal issubset issubtype issym istaskdone istaskstarted istext istril istriu isupper isvalid iswritable isxdigit is_assigned_char join joinpath KeyError keys keytype kill kron last launch lbeta lcfirst lcm ldexp leading_ones leading_zeros length less lexcmp lexless lfact lgamma linreg linspace listen listenany LoadError lock log log10 log1p log2 logabsdet logdet logspace lowercase lpad lstat lstrip ltoh lu lufact lufact! lyap macroexpand manage map map! mapfoldl mapfoldr mapreduce mapreducedim mapslices mark match matchall max maxabs maxabs! maximum maximum! maxintfloat mean mean! median median! merge merge! MersenneTwister MethodError methods methodswith method_exists midpoints mimewritable min minabs minabs! minimum minimum! minmax mkdir mkpath mktemp mktempdir mod mod1 mod2pi modf module_name module_parent mtime muladd mv myid name names nan nb_available ndigits ndims next nextfloat nextind nextpow nextpow2 nextprod nfields norm normalize_string normpath notify now nprocs nthperm nthperm! ntoh ntuple Nullable NullException nullspace num num2hex nworkers object_id oct oftype one ones open operm OutOfMemoryError OverflowError parent parentindexes parse ParseError parseip partitions peakflops permutations permute! permutedims permutedims! pinv PipeBuffer pipeline pmap pointer pointer_from_objref pointer_to_array poll_fd poll_file polygamma pop! popdisplay position powermod precision precompile prepend! prevfloat prevind prevpow prevpow2 prevprod primes primesmask print println print_escaped print_joined print_shortest print_unescaped print_with_color ProcessExitedException process_exited process_running procs prod prod! produce promote promote_rule promote_shape promote_type push! pushdisplay put! pwd qr qrfact qrfact! quadgk quantile! quit rad2deg rand rand! randcycle randexp randexp! randjump randn randn! RandomDevice randperm randstring randsubseq randsubseq! range rank rationalize read read! readall readandwrite readavailable readbytes readbytes! readchomp readcsv readdir readdlm readline readlines readlink ReadOnlyMemoryError readuntil real realmax realmin realpath recv recvfrom redirect_stderr redirect_stdin redirect_stdout redisplay reduce reducedim reenable_sigint ReentrantLock reim reinterpret relpath rem rem1 remotecall remotecall_fetch remotecall_wait RemoteRef repeat repeated replace repmat repr reprmime require reset reshape resize! rest rethrow reverse reverse! reverseind rm rmprocs rol rol! ror ror! rot180 rotl90 rotr90 round rpad rsearch rsearchindex rsplit rstrip run runtests scale scale! schedule sdata search searchindex searchsorted searchsortedfirst searchsortedlast sec secd sech seek seekend seekstart select select! selectperm selectperm! send serialize Set setdiff setdiff! setenv setfield! setindex! setopt set_bigfloat_precision set_rounding set_zero_subnormals SharedArray shift! show showall showcompact showerror shuffle shuffle! sign signbit signed signif significand similar sin sinc sind sinh sinpi size sizehint! sizeof skip skipchars sleep slice slicedim sort sort! sortcols sortperm sortperm! sortrows spawn splice! split splitdir splitdrive splitext sprint sqrt sqrtm squeeze srand StackOverflowError start startswith stat std stdm step stride strides string stringmime strip strwidth sub sub2ind subtypes success sum sum! sumabs sumabs! sumabs2 sumabs2! summary sum_kbn super svd svdfact svdfact! svds svdvals svdvals! sylvester symbol symdiff symlink SymTridiagonal SystemError take take! takebuf_array takebuf_string tan tand tanh Task task_local_storage tempdir tempname TextDisplay throw tic time timedwait Timer time_ns toc toq touch trace trailing_ones trailing_zeros transpose transpose! Tridiagonal trigamma tril tril! triu triu! trues trunc truncate tryparse tuple TypeError typeintersect typejoin typemax typemin typeof ucfirst UndefRefError UndefVarError unescape_string union union! unlock unmark unsafe_convert unsafe_copy! unsafe_load unsafe_pointer_to_objref unsafe_store! unsafe_trunc unshift! unsigned uperm uppercase utf16 utf32 utf8 Val valtype values var varm vcat vec vecdot vecnorm versioninfo wait warn watch_file which widemul widen withenv with_bigfloat_precision with_rounding workers workspace write writecsv writedlm writemime wstring xcorr xdump yield yieldto zero zeros zeta zip"
  -- 5, macro
  local keywords4_set = "allocated assert async boundscheck cfunction debug deprecate distributed dump elapsed enum error eval evalpoly everywhere fastmath fetch generated gensym goto inbounds inferred info inline isdefined label logmsg lower macroexpand macroexpand1 noinline nospecialize polly preserve printf profile propagate_inbounds pure show spawn spawnat specialize sprintf static sync task test test_broken test_deprecated test_logs test_nowarn test_skip test_throws test_warn testset threads time timed timev view views warn"
  return keywords0_set,keywords1_set,keywords2_set,keywords3_set,keywords4_set
end

function julia.get_autocomplete()
  local autocomplete_set = "abs2 abspath accept acos acosd acosh acot acotd acoth acsc acscd acsch Ac_ldiv_B Ac_ldiv_Bc Ac_mul_B Ac_mul_Bc Ac_rdiv_B Ac_rdiv_Bc addprocs airy airyai airyaiprime airybi airybiprime airyprime airyx all all! angle any any! append! applicable ArgumentError Array ascii asec asecd asech asin asind asinh assert AssertionError atan atan2 atand atanh atexit atreplinit At_ldiv_B At_ldiv_Bt At_mul_B At_mul_Bt At_rdiv_B At_rdiv_Bt A_ldiv_Bc A_ldiv_Bt A_mul_B! A_mul_Bc A_mul_Bt A_rdiv_Bc A_rdiv_Bt backtrace base base64decode base64encode Base64EncodePipe basename besselh besseli besselix besselj besselj0 besselj1 besseljx besselk besselkx bessely bessely0 bessely1 besselyx beta Bidiagonal big BigFloat BigInt bin bind binomial bitbroadcast bitpack bitrand bits bitunpack bkfact bkfact! BoundsError broadcast broadcast! broadcast!_function broadcast_function broadcast_getindex broadcast_setindex! bswap bytes2hex bytestring call cat catch_backtrace cbrt cconvert cd ceil cell cfunction cglobal Channel charwidth checkbounds chmod cholfact cholfact! chomp chop chr2ind circshift cis clamp cld clipboard close cmp code_llvm code_lowered code_native code_typed code_warntype combinations compilecache complement complement! complex cond Condition condskeel conj conj! connect consume contains conv conv2 convert copy copy! copysign cos cosc cosd cosh cospi cot cotd coth count countfrom countlines count_ones count_zeros cp cross csc cscd csch ctime ctranspose ctranspose! cummax cummin cumprod cumprod! cumsum cumsum! cumsum_kbn current_module cycle dawson dec deconv deepcopy deg2rad delete! deleteat! den deserialize det detach diag diagind diagm Dict diff digamma digits digits! DimensionMismatch dirname disable_sigint display displayable div DivideError divrem DomainError done dot download drop dump eachindex eachline eachmatch edit eig eigfact eigfact! eigmax eigmin eigvals eigvecs eltype empty! endof endswith enumerate EnvHash eof EOFError eps erf erfc erfcinv erfcx erfi erfinv error ErrorException esc escape_string eta eval evalfile exit exp exp10 exp2 expand expanduser expm expm1 exponent extrema eye factor factorial factorize falses fd fdio fetch fieldnames fieldoffsets fieldtype filemode filesize fill fill! filt filt! filter filter! finalize finalizer find findfirst findin findlast findmax findmin findn findnext findnz findprev first fld fldmod flipbits! flipdim flipsign float Float32 Float64 floor flush fma foldl foldr frexp full fullname functionloc function_module function_name gamma gc gcd gcdx gc_enable gensym get get! getaddrinfo getfield gethostname getindex getipaddr getkey getpid getsockname get_bigfloat_precision get_rounding get_zero_subnormals gperm gradient graphemes hankelh1 hankelh1x hankelh2 hankelh2x hash haskey hcat hessfact hessfact! hex hex2bytes hex2num hist hist! hist2d hist2d! histrange homedir htol hton hvcat hypot identity ifelse ignorestatus imag include_dependency include_string ind2chr ind2sub indexin indexpids indmax indmin InexactError inf info InitError init_worker insert! instances interrupt InterruptException intersect intersect! IntSet inv invdigamma invmod invoke invperm IOBuffer ipermute! ipermutedims IPv4 IPv6 is isa isabspath isalnum isalpha isapprox isascii isbits isblockdev ischardev iscntrl isconst isdefined isdiag isdigit isdir isdirpath iseltype isempty isequal iseven isexecutable isfifo isfile isfinite isgeneric isgraph ishermitian isimmutable isinf isinteger isinteractive isleaftype isless islink islower ismarked ismatch ismount isnan isnull isnumber isodd isopen ispath isperm isposdef isposdef! ispow2 isprime isprint ispunct isqrt isreadable isreadonly isready isreal issetgid issetuid issocket issorted isspace issticky issubnormal issubset issubtype issym istaskdone istaskstarted istext istril istriu isupper isvalid iswritable isxdigit is_assigned_char join joinpath KeyError keys keytype kill kron last launch lbeta lcfirst lcm ldexp leading_ones leading_zeros length less lexcmp lexless lfact lgamma linreg linspace listen listenany LoadError lock log log10 log1p log2 logabsdet logdet logspace lowercase lpad lstat lstrip ltoh lu lufact lufact! lyap macroexpand manage map map! mapfoldl mapfoldr mapreduce mapreducedim mapslices mark match matchall max maxabs maxabs! maximum maximum! maxintfloat mean mean! median median! merge merge! MersenneTwister MethodError methods methodswith method_exists midpoints mimewritable min minabs minabs! minimum minimum! minmax mkdir mkpath mktemp mktempdir mod mod1 mod2pi modf module_name module_parent mtime muladd mv myid name names nan nb_available ndigits ndims next nextfloat nextind nextpow nextpow2 nextprod nfields norm normalize_string normpath notify now nprocs nthperm nthperm! ntoh ntuple Nullable NullException nullspace num num2hex nworkers object_id oct oftype one ones open operm OutOfMemoryError OverflowError parent parentindexes parse ParseError parseip partitions peakflops permutations permute! permutedims permutedims! pinv PipeBuffer pipeline pmap pointer pointer_from_objref pointer_to_array poll_fd poll_file polygamma pop! popdisplay position powermod precision precompile prepend! prevfloat prevind prevpow prevpow2 prevprod primes primesmask print println print_escaped print_joined print_shortest print_unescaped print_with_color ProcessExitedException process_exited process_running procs prod prod! produce promote promote_rule promote_shape promote_type push! pushdisplay put! pwd qr qrfact qrfact! quadgk quantile! quit rad2deg rand rand! randcycle randexp randexp! randjump randn randn! RandomDevice randperm randstring randsubseq randsubseq! range rank rationalize read read! readall readandwrite readavailable readbytes readbytes! readchomp readcsv readdir readdlm readline readlines readlink ReadOnlyMemoryError readuntil real realmax realmin realpath recv recvfrom redirect_stderr redirect_stdin redirect_stdout redisplay reduce reducedim reenable_sigint ReentrantLock reim reinterpret relpath rem rem1 remotecall remotecall_fetch remotecall_wait RemoteRef repeat repeated replace repmat repr reprmime require reset reshape resize! rest rethrow reverse reverse! reverseind rm rmprocs rol rol! ror ror! rot180 rotl90 rotr90 round rpad rsearch rsearchindex rsplit rstrip run runtests scale scale! schedule sdata search searchindex searchsorted searchsortedfirst searchsortedlast sec secd sech seek seekend seekstart select select! selectperm selectperm! send serialize Set setdiff setdiff! setenv setfield! setindex! setopt set_bigfloat_precision set_rounding set_zero_subnormals SharedArray shift! show showall showcompact showerror shuffle shuffle! sign signbit signed signif significand similar sin sinc sind sinh sinpi size sizehint! sizeof skip skipchars sleep slice slicedim sort sort! sortcols sortperm sortperm! sortrows spawn splice! split splitdir splitdrive splitext sprint sqrt sqrtm squeeze srand StackOverflowError start startswith stat std stdm step stride strides string stringmime strip strwidth sub sub2ind subtypes success sum sum! sumabs sumabs! sumabs2 sumabs2! summary sum_kbn super svd svdfact svdfact! svds svdvals svdvals! sylvester symbol symdiff symlink SymTridiagonal SystemError take take! takebuf_array takebuf_string tan tand tanh Task task_local_storage tempdir tempname TextDisplay throw tic time timedwait Timer time_ns toc toq touch trace trailing_ones trailing_zeros transpose transpose! Tridiagonal trigamma tril tril! triu triu! trues trunc truncate tryparse tuple TypeError typeintersect typejoin typemax typemin typeof ucfirst UndefRefError UndefVarError unescape_string union union! unlock unmark unsafe_convert unsafe_copy! unsafe_load unsafe_pointer_to_objref unsafe_store! unsafe_trunc unshift! unsigned uperm uppercase utf16 utf32 utf8 Val valtype values var varm vcat vec vecdot vecnorm versioninfo wait warn watch_file which widemul widen withenv with_bigfloat_precision with_rounding workers workspace write writecsv writedlm writemime wstring xcorr xdump yield yieldto zero zeros zeta zip"
  return autocomplete_set
end

function julia.get_reqular()
  local symbol_reqular_exp = "[ \\t]*function[ \\t]+([_a-zA-Z]+[_a-zA-Z0-9]*)\\("
  return symbol_reqular_exp
end

function julia.create_bakup(path)
  local julia_code = {
    "user_julia = {}\n",
    "\n",
    "require(\"eu_sci\")\n",
    "require(\"eu_core\")\n",
    "\n",
    "function user_julia.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, \"julia\")\n",
    "  if (res ~= 1) then\n",
    "    eu_core.euapi.on_doc_enable_foldline(pnode)                                               -- enable fold line\n",
    "    eu_core.euapi.on_doc_keyword_light(pnode, SCE_JULIA_KEYWORD1, 0, 0)                       -- 3, SCE_JULIA_KEYWORD1, keywords0\n",
    "    eu_core.euapi.on_doc_keyword_light(pnode, SCE_JULIA_KEYWORD2, 1, 0x0080FF)                -- 4, SCE_JULIA_KEYWORD2, keywords1\n",
    "    eu_core.euapi.on_doc_keyword_light(pnode, SCE_JULIA_KEYWORD3, 2, 0x307300)                -- 5, SCE_JULIA_KEYWORD3, keywords2\n",
    "    eu_core.euapi.on_doc_keyword_light(pnode, SCE_JULIA_KEYWORD4, 3, 0)                       -- 20, SCE_JULIA_KEYWORD4, keywords3\n",
    "    eu_core.euapi.on_doc_marcro_light(pnode, SCE_JULIA_MACRO, 4, 0xFF8000)\n",
    "    eu_core.euapi.on_doc_comment_light(pnode, SCE_JULIA_COMMENT, 0)\n",
    "    eu_core.euapi.on_doc_string_light(pnode, SCE_JULIA_DOCSTRING, 0x008080)\n",
    "    eu_core.euapi.on_doc_string_light(pnode, SCE_JULIA_STRING, 0x008000)\n",
    "  end\n",
    "  return res\n",
    "end\n",
    "\n",
    "function user_julia.get_keywords()\n",
    "  -- 1, reserved keywords\n",
    "  local keywords0_set = \"abstract baremodule begin break catch const continue do else elseif end export finally for function global if import in isa let local macro module mutable primitive quote return struct try type using var where while baremodule begin do for function if let macro module quote struct try type while\"\n",
    "  -- 2, type\n",
    "  local keywords1_set = \"AbstractArray AbstractArrayStyle AbstractChannel AbstractChar AbstractDict AbstractDisplay AbstractFloat AbstractIrrational AbstractLock AbstractLogger AbstractMatrix AbstractRNG AbstractRange AbstractSet AbstractSparseArray AbstractSparseMatrix AbstractSparseVector AbstractString AbstractUnitRange AbstractVecOrMat AbstractVector AbstractWorkerPool Adjoint Anonymous Any ArgumentError Array ArrayStyle AssertionError AsyncCondition Atomic Base64DecodePipe Base64EncodePipe Bidiagonal BigFloat BigInt BitArray BitMatrix BitSet BitVector Bool BoundsError BroadcastStyle CFunction CapturedException CartesianIndex CartesianIndices Cchar Cdouble Cfloat Channel Char Cint Cintmax_t Clong Clonglong ClusterManager Cmd Colon Complex ComplexF16 ComplexF32 ComplexF64 CompositeException CompoundPeriod Condition ConsoleLogger Cptrdiff_t Cshort Csize_t Cssize_t Cstring Cuchar Cuint Cuintmax_t Culong Culonglong Cushort Cwchar_t Cwstring DataType Date DateFormat DateTime Day DefaultArrayStyle DenseArray DenseMatrix DenseVecOrMat DenseVector Diagonal Dict DimensionMismatch Dims DivideError DomainError EOFError Enum EnvDict ErrorException Event Exception ExponentialBackOff Expr Float16 Float32 Float64 Function Future Givens GlobalRef Hermitian Hour IO IOBuffer IOContext IOStream IPAddr IPv4 IPv6 IdDict ImmutableDict IndexCartesian IndexLinear IndexStyle InexactError InitError Instant Int Int128 Int16 Int32 Int64 Int8 Integer InterruptException InvalidStateException Irrational IteratorEltype IteratorSize KeyError LinRange LineNumberNode LinearIndices LoadError LogLevel LowerTriangular MIME Matrix MersenneTwister Method MethodError Microsecond Millisecond Minute Missing MissingException Module Month Mutex NTuple NamedTuple Nanosecond Nothing NullLogger Number OneTo OrdinalRange OutOfMemoryError OverflowError Pair Pairs PartialQuickSort Period PermutedDimsArray Pipe PipeBuffer PosDefException ProcessFailedException Ptr QR QRCompactWY QRPivoted QuoteNode Random RandomDevice Rational RawFD ReadOnlyMemoryError Real ReentrantLock Ref Regex RegexMatch RemoteChannel RemoteException RoundingMode Second SegmentationFault Semaphore Serialization Set SharedArray SharedMatrix SharedVector Signed SimpleLogger SingularException Some SparseMatrixCSC SparseVector SpinLock StackFrame StackOverflowError StackTrace Stateful StepRange StepRangeLen StridedArray StridedMatrix StridedVecOrMat StridedVector String StringIndexError SubArray SubString SubstitutionString SymTridiagonal Symbol Symmetric SystemError TCPSocket Task TextDisplay Time TimeType Timer TmStruct Transpose Tridiagonal Tuple Type TypeError TypeVar UDPSocket UInt UInt128 UInt16 UInt32 UInt64 UInt8 UTInstant UndefInitializer UndefKeywordError UndefRefError UndefVarError UniformScaling Union UnionAll UnitLowerTriangular UnitRange UnitUpperTriangular Unsigned UpperTriangular Val Vararg VecElement VecOrMat Vector VersionNumber WeakKeyDict WeakRef Week WorkerConfig WorkerPool Year\"\n",
    "  -- 3, constant\n",
    "  local keywords2_set = \"ARCH ARGS BINDIR CPU_THREADS C_NULL Cvoid DEPOT_PATH ENDIAN_BOM ENV Inf Inf16 Inf32 Inf64 InsertionSort KERNEL LOAD_PATH MACHINE MergeSort NaN NaN16 NaN32 NaN64 PROGRAM_FILE QuickSort RoundDown RoundFromZero RoundNearest RoundNearestTiesAway RoundNearestTiesUp RoundToZero RoundUp VERSION WORD_SIZE ans catalan devnull eulergamma false golden im missing nothing pi stderr stdin stdout true undef\"\n",
    "  -- 4, module and function\n",
    "  local keywords3_set = \"Base Base64 Broadcast CRC32c Checked Core CoreLogging Dates DelimitedFiles Distributed Docs FastMath FileWatching Filesystem GC Grisu Intrinsics Iterators IteratorsMD Libc LinearAlgebra MPFR Main Math MathConstants Meta Mmap Multimedia Printf Profile Rounding SharedArrays Sockets Sort SparseArrays StackTraces Statistics Sys Test Threads UUIDs Unicode abs2 abspath accept acos acosd acosh acot acotd acoth acsc acscd acsch Ac_ldiv_B Ac_ldiv_Bc Ac_mul_B Ac_mul_Bc Ac_rdiv_B Ac_rdiv_Bc addprocs airy airyai airyaiprime airybi airybiprime airyprime airyx all all! angle any any! append! applicable ArgumentError Array ascii asec asecd asech asin asind asinh assert AssertionError atan atan2 atand atanh atexit atreplinit At_ldiv_B At_ldiv_Bt At_mul_B At_mul_Bt At_rdiv_B At_rdiv_Bt A_ldiv_Bc A_ldiv_Bt A_mul_B! A_mul_Bc A_mul_Bt A_rdiv_Bc A_rdiv_Bt backtrace base base64decode Base64DecodePipe base64encode Base64EncodePipe basename besselh besseli besselix besselj besselj0 besselj1 besseljx besselk besselkx bessely bessely0 bessely1 besselyx beta Bidiagonal big BigFloat BigInt bin bind binomial bitbroadcast bitpack bitrand bits bitunpack bkfact bkfact! BoundsError broadcast broadcast! broadcast!_function broadcast_function broadcast_getindex broadcast_setindex! bswap bytes2hex bytestring call cat catch_backtrace cbrt cconvert cd ceil cell cfunction cglobal Channel charwidth checkbounds chmod cholfact cholfact! chomp chop chr2ind circshift cis clamp cld clipboard close cmp code_llvm code_lowered code_native code_typed code_warntype combinations compilecache complement complement! complex cond Condition condskeel conj conj! connect consume contains conv conv2 convert copy copy! copysign cos cosc cosd cosh cospi cot cotd coth count countfrom countlines count_ones count_zeros cp cross csc cscd csch ctime ctranspose ctranspose! cummax cummin cumprod cumprod! cumsum cumsum! cumsum_kbn current_module cycle dawson dec deconv deepcopy deg2rad delete! deleteat! den deserialize det detach diag diagind diagm Dict diff digamma digits digits! DimensionMismatch dirname disable_sigint display displayable div DivideError divrem DomainError done dot download drop dump eachindex eachline eachmatch edit eig eigfact eigfact! eigmax eigmin eigvals eigvecs eltype empty! endof endswith enumerate EnvHash eof EOFError eps erf erfc erfcinv erfcx erfi erfinv error ErrorException esc escape_string eta eval evalfile exit exp exp10 exp2 expand expanduser expm expm1 exponent extrema eye factor factorial factorize falses fd fdio fetch fieldnames fieldoffsets fieldtype filemode filesize fill fill! filt filt! filter filter! finalize finalizer find findfirst findin findlast findmax findmin findn findnext findnz findprev first fld fldmod flipbits! flipdim flipsign float Float32 Float64 floor flush fma foldl foldr frexp full fullname functionloc function_module function_name gamma gc gcd gcdx gc_enable gensym get get! getaddrinfo getfield gethostname getindex getipaddr getkey getpid getsockname get_bigfloat_precision get_rounding get_zero_subnormals gperm gradient graphemes hankelh1 hankelh1x hankelh2 hankelh2x hash haskey hcat hessfact hessfact! hex hex2bytes hex2num hist hist! hist2d hist2d! histrange homedir htol hton hvcat hypot identity ifelse ignorestatus imag include_dependency include_string ind2chr ind2sub indexin indexpids indmax indmin InexactError inf info InitError init_worker insert! instances interrupt InterruptException intersect intersect! IntSet inv invdigamma invmod invoke invperm IOBuffer ipermute! ipermutedims IPv4 IPv6 is isa isabspath isalnum isalpha isapprox isascii isbits isblockdev ischardev iscntrl isconst isdefined isdiag isdigit isdir isdirpath iseltype isempty isequal iseven isexecutable isfifo isfile isfinite isgeneric isgraph ishermitian isimmutable isinf isinteger isinteractive isleaftype isless islink islower ismarked ismatch ismount isnan isnull isnumber isodd isopen ispath isperm isposdef isposdef! ispow2 isprime isprint ispunct isqrt isreadable isreadonly isready isreal issetgid issetuid issocket issorted isspace issticky issubnormal issubset issubtype issym istaskdone istaskstarted istext istril istriu isupper isvalid iswritable isxdigit is_assigned_char join joinpath KeyError keys keytype kill kron last launch lbeta lcfirst lcm ldexp leading_ones leading_zeros length less lexcmp lexless lfact lgamma linreg linspace listen listenany LoadError lock log log10 log1p log2 logabsdet logdet logspace lowercase lpad lstat lstrip ltoh lu lufact lufact! lyap macroexpand manage map map! mapfoldl mapfoldr mapreduce mapreducedim mapslices mark match matchall max maxabs maxabs! maximum maximum! maxintfloat mean mean! median median! merge merge! MersenneTwister MethodError methods methodswith method_exists midpoints mimewritable min minabs minabs! minimum minimum! minmax mkdir mkpath mktemp mktempdir mod mod1 mod2pi modf module_name module_parent mtime muladd mv myid name names nan nb_available ndigits ndims next nextfloat nextind nextpow nextpow2 nextprod nfields norm normalize_string normpath notify now nprocs nthperm nthperm! ntoh ntuple Nullable NullException nullspace num num2hex nworkers object_id oct oftype one ones open operm OutOfMemoryError OverflowError parent parentindexes parse ParseError parseip partitions peakflops permutations permute! permutedims permutedims! pinv PipeBuffer pipeline pmap pointer pointer_from_objref pointer_to_array poll_fd poll_file polygamma pop! popdisplay position powermod precision precompile prepend! prevfloat prevind prevpow prevpow2 prevprod primes primesmask print println print_escaped print_joined print_shortest print_unescaped print_with_color ProcessExitedException process_exited process_running procs prod prod! produce promote promote_rule promote_shape promote_type push! pushdisplay put! pwd qr qrfact qrfact! quadgk quantile! quit rad2deg rand rand! randcycle randexp randexp! randjump randn randn! RandomDevice randperm randstring randsubseq randsubseq! range rank rationalize read read! readall readandwrite readavailable readbytes readbytes! readchomp readcsv readdir readdlm readline readlines readlink ReadOnlyMemoryError readuntil real realmax realmin realpath recv recvfrom redirect_stderr redirect_stdin redirect_stdout redisplay reduce reducedim reenable_sigint ReentrantLock reim reinterpret relpath rem rem1 remotecall remotecall_fetch remotecall_wait RemoteRef repeat repeated replace repmat repr reprmime require reset reshape resize! rest rethrow reverse reverse! reverseind rm rmprocs rol rol! ror ror! rot180 rotl90 rotr90 round rpad rsearch rsearchindex rsplit rstrip run runtests scale scale! schedule sdata search searchindex searchsorted searchsortedfirst searchsortedlast sec secd sech seek seekend seekstart select select! selectperm selectperm! send serialize Set setdiff setdiff! setenv setfield! setindex! setopt set_bigfloat_precision set_rounding set_zero_subnormals SharedArray shift! show showall showcompact showerror shuffle shuffle! sign signbit signed signif significand similar sin sinc sind sinh sinpi size sizehint! sizeof skip skipchars sleep slice slicedim sort sort! sortcols sortperm sortperm! sortrows spawn splice! split splitdir splitdrive splitext sprint sqrt sqrtm squeeze srand StackOverflowError start startswith stat std stdm step stride strides string stringmime strip strwidth sub sub2ind subtypes success sum sum! sumabs sumabs! sumabs2 sumabs2! summary sum_kbn super svd svdfact svdfact! svds svdvals svdvals! sylvester symbol symdiff symlink SymTridiagonal SystemError take take! takebuf_array takebuf_string tan tand tanh Task task_local_storage tempdir tempname TextDisplay throw tic time timedwait Timer time_ns toc toq touch trace trailing_ones trailing_zeros transpose transpose! Tridiagonal trigamma tril tril! triu triu! trues trunc truncate tryparse tuple TypeError typeintersect typejoin typemax typemin typeof ucfirst UndefRefError UndefVarError unescape_string union union! unlock unmark unsafe_convert unsafe_copy! unsafe_load unsafe_pointer_to_objref unsafe_store! unsafe_trunc unshift! unsigned uperm uppercase utf16 utf32 utf8 Val valtype values var varm vcat vec vecdot vecnorm versioninfo wait warn watch_file which widemul widen withenv with_bigfloat_precision with_rounding workers workspace write writecsv writedlm writemime wstring xcorr xdump yield yieldto zero zeros zeta zip\"\n",
    "  -- 5, macro\n",
    "  local keywords4_set = \"allocated assert async boundscheck cfunction debug deprecate distributed dump elapsed enum error eval evalpoly everywhere fastmath fetch generated gensym goto inbounds inferred info inline isdefined label logmsg lower macroexpand macroexpand1 noinline nospecialize polly preserve printf profile propagate_inbounds pure show spawn spawnat specialize sprintf static sync task test test_broken test_deprecated test_logs test_nowarn test_skip test_throws test_warn testset threads time timed timev view views warn\"\n",
    "  return keywords0_set,keywords1_set,keywords2_set,keywords3_set,keywords4_set\n",
    "end\n",
    "\n",
    "function user_julia.get_autocomplete()\n",
    "  local autocomplete_set = \"abs2 abspath accept acos acosd acosh acot acotd acoth acsc acscd acsch Ac_ldiv_B Ac_ldiv_Bc Ac_mul_B Ac_mul_Bc Ac_rdiv_B Ac_rdiv_Bc addprocs airy airyai airyaiprime airybi airybiprime airyprime airyx all all! angle any any! append! applicable ArgumentError Array ascii asec asecd asech asin asind asinh assert AssertionError atan atan2 atand atanh atexit atreplinit At_ldiv_B At_ldiv_Bt At_mul_B At_mul_Bt At_rdiv_B At_rdiv_Bt A_ldiv_Bc A_ldiv_Bt A_mul_B! A_mul_Bc A_mul_Bt A_rdiv_Bc A_rdiv_Bt backtrace base base64decode base64encode Base64EncodePipe basename besselh besseli besselix besselj besselj0 besselj1 besseljx besselk besselkx bessely bessely0 bessely1 besselyx beta Bidiagonal big BigFloat BigInt bin bind binomial bitbroadcast bitpack bitrand bits bitunpack bkfact bkfact! BoundsError broadcast broadcast! broadcast!_function broadcast_function broadcast_getindex broadcast_setindex! bswap bytes2hex bytestring call cat catch_backtrace cbrt cconvert cd ceil cell cfunction cglobal Channel charwidth checkbounds chmod cholfact cholfact! chomp chop chr2ind circshift cis clamp cld clipboard close cmp code_llvm code_lowered code_native code_typed code_warntype combinations compilecache complement complement! complex cond Condition condskeel conj conj! connect consume contains conv conv2 convert copy copy! copysign cos cosc cosd cosh cospi cot cotd coth count countfrom countlines count_ones count_zeros cp cross csc cscd csch ctime ctranspose ctranspose! cummax cummin cumprod cumprod! cumsum cumsum! cumsum_kbn current_module cycle dawson dec deconv deepcopy deg2rad delete! deleteat! den deserialize det detach diag diagind diagm Dict diff digamma digits digits! DimensionMismatch dirname disable_sigint display displayable div DivideError divrem DomainError done dot download drop dump eachindex eachline eachmatch edit eig eigfact eigfact! eigmax eigmin eigvals eigvecs eltype empty! endof endswith enumerate EnvHash eof EOFError eps erf erfc erfcinv erfcx erfi erfinv error ErrorException esc escape_string eta eval evalfile exit exp exp10 exp2 expand expanduser expm expm1 exponent extrema eye factor factorial factorize falses fd fdio fetch fieldnames fieldoffsets fieldtype filemode filesize fill fill! filt filt! filter filter! finalize finalizer find findfirst findin findlast findmax findmin findn findnext findnz findprev first fld fldmod flipbits! flipdim flipsign float Float32 Float64 floor flush fma foldl foldr frexp full fullname functionloc function_module function_name gamma gc gcd gcdx gc_enable gensym get get! getaddrinfo getfield gethostname getindex getipaddr getkey getpid getsockname get_bigfloat_precision get_rounding get_zero_subnormals gperm gradient graphemes hankelh1 hankelh1x hankelh2 hankelh2x hash haskey hcat hessfact hessfact! hex hex2bytes hex2num hist hist! hist2d hist2d! histrange homedir htol hton hvcat hypot identity ifelse ignorestatus imag include_dependency include_string ind2chr ind2sub indexin indexpids indmax indmin InexactError inf info InitError init_worker insert! instances interrupt InterruptException intersect intersect! IntSet inv invdigamma invmod invoke invperm IOBuffer ipermute! ipermutedims IPv4 IPv6 is isa isabspath isalnum isalpha isapprox isascii isbits isblockdev ischardev iscntrl isconst isdefined isdiag isdigit isdir isdirpath iseltype isempty isequal iseven isexecutable isfifo isfile isfinite isgeneric isgraph ishermitian isimmutable isinf isinteger isinteractive isleaftype isless islink islower ismarked ismatch ismount isnan isnull isnumber isodd isopen ispath isperm isposdef isposdef! ispow2 isprime isprint ispunct isqrt isreadable isreadonly isready isreal issetgid issetuid issocket issorted isspace issticky issubnormal issubset issubtype issym istaskdone istaskstarted istext istril istriu isupper isvalid iswritable isxdigit is_assigned_char join joinpath KeyError keys keytype kill kron last launch lbeta lcfirst lcm ldexp leading_ones leading_zeros length less lexcmp lexless lfact lgamma linreg linspace listen listenany LoadError lock log log10 log1p log2 logabsdet logdet logspace lowercase lpad lstat lstrip ltoh lu lufact lufact! lyap macroexpand manage map map! mapfoldl mapfoldr mapreduce mapreducedim mapslices mark match matchall max maxabs maxabs! maximum maximum! maxintfloat mean mean! median median! merge merge! MersenneTwister MethodError methods methodswith method_exists midpoints mimewritable min minabs minabs! minimum minimum! minmax mkdir mkpath mktemp mktempdir mod mod1 mod2pi modf module_name module_parent mtime muladd mv myid name names nan nb_available ndigits ndims next nextfloat nextind nextpow nextpow2 nextprod nfields norm normalize_string normpath notify now nprocs nthperm nthperm! ntoh ntuple Nullable NullException nullspace num num2hex nworkers object_id oct oftype one ones open operm OutOfMemoryError OverflowError parent parentindexes parse ParseError parseip partitions peakflops permutations permute! permutedims permutedims! pinv PipeBuffer pipeline pmap pointer pointer_from_objref pointer_to_array poll_fd poll_file polygamma pop! popdisplay position powermod precision precompile prepend! prevfloat prevind prevpow prevpow2 prevprod primes primesmask print println print_escaped print_joined print_shortest print_unescaped print_with_color ProcessExitedException process_exited process_running procs prod prod! produce promote promote_rule promote_shape promote_type push! pushdisplay put! pwd qr qrfact qrfact! quadgk quantile! quit rad2deg rand rand! randcycle randexp randexp! randjump randn randn! RandomDevice randperm randstring randsubseq randsubseq! range rank rationalize read read! readall readandwrite readavailable readbytes readbytes! readchomp readcsv readdir readdlm readline readlines readlink ReadOnlyMemoryError readuntil real realmax realmin realpath recv recvfrom redirect_stderr redirect_stdin redirect_stdout redisplay reduce reducedim reenable_sigint ReentrantLock reim reinterpret relpath rem rem1 remotecall remotecall_fetch remotecall_wait RemoteRef repeat repeated replace repmat repr reprmime require reset reshape resize! rest rethrow reverse reverse! reverseind rm rmprocs rol rol! ror ror! rot180 rotl90 rotr90 round rpad rsearch rsearchindex rsplit rstrip run runtests scale scale! schedule sdata search searchindex searchsorted searchsortedfirst searchsortedlast sec secd sech seek seekend seekstart select select! selectperm selectperm! send serialize Set setdiff setdiff! setenv setfield! setindex! setopt set_bigfloat_precision set_rounding set_zero_subnormals SharedArray shift! show showall showcompact showerror shuffle shuffle! sign signbit signed signif significand similar sin sinc sind sinh sinpi size sizehint! sizeof skip skipchars sleep slice slicedim sort sort! sortcols sortperm sortperm! sortrows spawn splice! split splitdir splitdrive splitext sprint sqrt sqrtm squeeze srand StackOverflowError start startswith stat std stdm step stride strides string stringmime strip strwidth sub sub2ind subtypes success sum sum! sumabs sumabs! sumabs2 sumabs2! summary sum_kbn super svd svdfact svdfact! svds svdvals svdvals! sylvester symbol symdiff symlink SymTridiagonal SystemError take take! takebuf_array takebuf_string tan tand tanh Task task_local_storage tempdir tempname TextDisplay throw tic time timedwait Timer time_ns toc toq touch trace trailing_ones trailing_zeros transpose transpose! Tridiagonal trigamma tril tril! triu triu! trues trunc truncate tryparse tuple TypeError typeintersect typejoin typemax typemin typeof ucfirst UndefRefError UndefVarError unescape_string union union! unlock unmark unsafe_convert unsafe_copy! unsafe_load unsafe_pointer_to_objref unsafe_store! unsafe_trunc unshift! unsigned uperm uppercase utf16 utf32 utf8 Val valtype values var varm vcat vec vecdot vecnorm versioninfo wait warn watch_file which widemul widen withenv with_bigfloat_precision with_rounding workers workspace write writecsv writedlm writemime wstring xcorr xdump yield yieldto zero zeros zeta zip\"\n",
    "  return autocomplete_set\n",
    "end\n",
    "\n",
    "function user_julia.get_reqular()\n",
    "  local symbol_reqular_exp = \"[ \\\\t]*function[ \\\\t]+([_a-zA-Z]+[_a-zA-Z0-9]*)\\\\(\"\n",
    "  return symbol_reqular_exp\n",
    "end\n",
    "return user_julia",
  }
  local shell_code = table.concat(julia_code)
  eu_core.save_file(path, shell_code)
  shell_code = nil
  julia_code = nil
end

return julia