verilog = {}

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

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

function verilog.get_styles()
  local style_t = {
    [SCE_V_COMMENT] = 0xC0C0C0,
    [SCE_V_COMMENTLINE] = 0xC0C0C0,
    [SCE_V_COMMENTLINEBANG] = 0xC0C0C0,
    -- 给关键字加上粗体
    [SCE_V_WORD] = 0x00B050 + SCE_BOLD_FONT,
    [SCE_V_WORD2] = 0x00B050 + SCE_BOLD_FONT,
    [SCE_V_WORD3] = 0xBBBB00 + SCE_BOLD_FONT,
    [SCE_V_STRING] = 0xC080FF,
  }
  return style_t
end

function verilog.get_keywords()
  local keywords0_set = "accept_on alias always always_comb always_ff always_latch assert assign assume automatic before bind bins binsof break cell const constraint context continue cover coverpoint cross deassign default defparam design disable dist do edge else enum eventually expect export extends extern final first_match for force foreach forever forkjoin genvar global highz0 highz1 if iff ifnone ignore_bins illegal_bins implements implies import incdir include initial inout input inside instance interconnect intersect large let liblist library local localparam matches medium modport negedge nettype new nexttime noshowcancelled null output packed parameter posedge priority protected pull0 pull1 pulldown pullup pulsestyle_ondetect pulsestyle_onevent pure rand randc ref reject_on release repeat restrict return s_always s_eventually s_nexttime s_until s_until_with scalared showcancelled small soft solve specparam static strong strong0 strong1 struct super sync_accept_on sync_reject_on tagged this throughout timeprecision timeunit type typedef union unique unique0 until until_with untyped use var vectored virtual wait wait_order weak weak0 weak1 while wildcard with within begin case casex casez checker class clocking config covergroup end endcase endchecker endclass endclocking endconfig endfunction endgenerate endgroup endinterface endmodule endpackage endprimitive endprogram endproperty endsequence endspecify endtable endtask fork function generate interface join join_any join_none macromodule module package primitive program property randcase randsequence sequence specify table task"
  local keywords1_set = "and bit buf bufif0 bufif1 byte chandle cmos event int integer logic longint nand nmos nor not notif0 notif1 or pmos rcmos real realtime reg rnmos rpmos rtran rtranif0 rtranif1 shortint shortreal signed string supply0 supply1 time tran tranif0 tranif1 tri tri0 tri1 triand trior trireg unsigned uwire void wand wire wor xnor xor __FILE__ __LINE__ begin_keywords celldefine default_decay_time default_nettype default_trireg_strength define delay_mode_distributed delay_mode_path delay_mode_unit delay_mode_zero else elsif end_keywords endcelldefine endif ifdef ifndef include line nounconnected_drive pragma resetall timescale unconnected_drive undef undefineall"
  local keywords2_set = "acos acosh asin asinh assertcontrol assertfailoff assertfailon assertkill assertnonvacuouson assertoff asserton assertpassoff assertpasson assertvacuousoff async$and$array async$and$plane async$nand$array async$nand$plane async$nor$array async$nor$plane async$or$array async$or$plane atan atan2 atanh bits bitstoreal bitstoshortreal cast ceil changed changed_gclk changing_gclk clog2 comment cos cosh countbits countdrivers countones coverage_control coverage_get coverage_get_max coverage_merge coverage_save date dimensions display displayb displayh displayo dist_chi_square dist_erlang dist_exponential dist_normal dist_poisson dist_t dist_uniform dumpall dumpfile dumpflush dumplimit dumpoff dumpon dumpports dumpportsall dumpportsflush dumpportslimit dumpportsoff dumpportson dumpvars dumpvars end enddefinitions error exit exp falling_gclk fatal fclose fdisplay fdisplayb fdisplayh fdisplayo fell fell_gclk feof ferror fflush fgetc fgets finish floor fmonitor fmonitorb fmonitorh fmonitoro fopen fread fscanf fseek fstrobe fstrobeb fstrobeh fstrobeo ftell fullskew future_gclk fwrite fwriteb fwriteh fwriteo get_coverage getpattern high hold hypot increment incsave info input isunbounded isunknown itor key left list ln load_coverage_db log log10 low monitor monitorb monitorh monitoro monitoroff monitoron nochange nokey nolog onehot onehot0 past past_gclk period pow printtimescale q_add q_exam q_full q_initialize q_remove random random readmemb readmemh realtime realtobits recovery recrem removal reset reset_count reset_value restart rewind right rising_gclk rose rose_gclk rtoi sampled save scale scope scope sdf_annotate set_coverage_db_name setup setuphold sformat sformatf shortrealtobits showscopes showvars signed sin sinh size skew sqrt sreadmemb sreadmemh sscanf stable stable_gclk steady_gclk stime stop strobe strobeb strobeh strobeo swrite swriteb swriteh swriteo sync$and$array sync$and$plane sync$nand$array sync$nand$plane sync$nor$array sync$nor$plane sync$or$array sync$or$plane system tan tanh test$plusargs time timeformat timescale timeskew typename ungetc unpacked_dimensions unsigned upscope urandom urandom urandom_range value$plusargs var vcdclose version warning width write writeb writeh writememb writememh writeo PATHPULSE$ STDERR STDIN STDOUT accept_on and assert assume atobin atohex atoi atooct atoreal await bintoa compare constraint_mode cover delete exists expect find find_first find_first_index find_index find_last find_last_index first first_match get get_coverage get_inst_coverage get_randstate getc hextoa icompare index insert itoa kill last len mailbox max min name new next num octtoa or peek pop_back pop_front post_randomize pre_randomize prev process product property push_back push_front put putc rand_mode randomize realtoa reject_on resume reverse rsort sample self semaphore sequence set_inst_name set_randstate shuffle size sort srandom start status std stop substr sum suspend sync_accept_on sync_reject_on tolower toupper try_get try_peek try_put unique unique_index wait_order"
  return keywords0_set,keywords1_set,keywords2_set
end

function verilog.get_autocomplete()
  local autocomplete_set = "__FILE__ __LINE__ accept_on acos and asin asinh assertcontrol assertfailon acosh assertfailoff assertkill assertnonvacuouson assertoff asserton assertpassoff assertpasson assertvacuousoff async$and$array async$and$plane async$nand$array async$nand$plane async$nor$array async$nor$plane async$or$array async$or$plane atan atan2 atanh begin_keywords bit bits bitstoreal bitstoshortreal buf bufif0 bufif1 byte case casex casez cast ceil celldefine chandle changed alias always always_comb always_ff always_latch assert assign assume before bind automatic bins binsof break cell PATHPULSE$ STDERR STDIN STDOUT atobin atohex atoi atooct atoreal await bintoa begin changed_gclk changing_gclk checker class clocking clog2 cmos comment compare config const constraint constraint_mode context continue cos cosh countbits countdrivers countones cover coverage_control coverage_get coverage_get_max coverage_merge coverage_save covergroup coverpoint cross date deassign default default_decay_time default_nettype default_trireg_strength define defparam delay_mode_distributed delay_mode_path delay_mode_unit delay_mode_zero delete design dimensions disable display displayb displayh displayo dist dist_chi_square dist_erlang dist_exponential dist_normal dist_poisson dist_t dist_uniform do dumpall dumpfile dumpflush dumplimit dumpoff dumpon dumpports dumpportsall dumpportsflush dumpportslimit dumpportsoff dumpportson dumpvars edge else elsif end end_keywords endcase endcelldefine endchecker endclass endclocking endconfig enddefinitions endfunction endgenerate endgroup endif endinterface endmodule endpackage endprimitive endprogram endproperty endsequence endspecify endtable endtask enum error event eventually exists exit exp expect export extends extern falling_gclk fatal fclose fdisplay fdisplayb fdisplayh fdisplayo fell fell_gclk feof ferror fflush fgetc fgets final find find_first find_first_index find_index find_last find_last_index finish first first_match floor fmonitor fmonitorb fmonitorh fmonitoro fopen for force foreach forever fork forkjoin fread fscanf fseek fstrobe fstrobeb fstrobeh fstrobeo ftell fullskew function future_gclk fwrite fwriteb fwriteh fwriteo generate genvar get get_coverage get_inst_coverage get_randstate getc getpattern global hextoa high highz0 highz1 hold hypot icompare if ifdef iff ifndef ifnone ignore_bins illegal_bins implements implies import incdir include increment incsave index info initial inout input insert inside instance int integer interconnect interface intersect isunbounded isunknown itoa itor join join_any join_none key kill large last left len let liblist library line list ln load_coverage_db local localparam log log10 logic longint low macromodule mailbox matches max medium min modport module monitor monitorb monitorh monitoro monitoroff monitoron name nand negedge nettype new next nexttime nmos nochange nokey nolog nor noshowcancelled not notif0 notif1 nounconnected_drive null num octtoa onehot onehot0 or output package packed parameter past past_gclk peek period pmos pop_back pop_front posedge post_randomize pow pragma pre_randomize prev primitive printtimescale priority process product program property protected pull0 pull1 pulldown pullup pulsestyle_ondetect pulsestyle_onevent pure push_back push_front put putc q_add q_exam q_full q_initialize q_remove rand rand_mode randc randcase random randomize randsequence rcmos readmemb readmemh real realtime realtoa realtobits recovery recrem ref reg reject_on release removal repeat reset reset_count reset_value resetall restart restrict resume return reverse rewind right rising_gclk rnmos rose rose_gclk rpmos rsort rtoi rtran rtranif0 rtranif1 s_always s_eventually s_nexttime s_until s_until_with sample sampled save scalared scale scope sdf_annotate self semaphore sequence set_coverage_db_name set_inst_name set_randstate setup setuphold sformat sformatf shortint shortreal shortrealtobits showcancelled showscopes showvars shuffle signed sin sinh size skew small soft solve sort specify specparam sqrt srandom sreadmemb sreadmemh sscanf stable stable_gclk start static status std steady_gclk stime stop string strobe strobeb strobeh strobeo strong strong0 strong1 struct substr sum super supply0 supply1 suspend swrite swriteb swriteh swriteo sync$and$array sync$and$plane sync$nand$array sync$nand$plane sync$nor$array sync$nor$plane sync$or$array sync$or$plane sync_accept_on sync_reject_on system table tagged tan tanh task test$plusargs this throughout time timeformat timeprecision timescale timeskew timeunit tolower toupper tran tranif0 tranif1 tri tri0 tri1 triand trior trireg try_get try_peek try_put type typedef typename unconnected_drive undef undefineall ungetc union unique unique0 unpacked_dimensions unsigned until until_with untyped upscope urandom urandom_range use uwire value$plusargs var vcdclose vectored version virtual void wait wait_order wand warning weak weak0 weak1 while width wildcard wire with within wor write writeb writeh writememb writememh writeo xnor xor unique_index"
  return autocomplete_set
end

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

function verilog.create_bakup(path)
  local verilog_code = {
    "user_verilog = {}\n",
    "\n",
    "require(\"eu_sci\")\n",
    "require(\"eu_core\")\n",
    "\n",
    "function user_verilog.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, \"verilog\")  -- enable verilog 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_verilog.get_styles()\n",
    "  local style_t = {\n",
    "    [SCE_V_COMMENT] = 0xC0C0C0,\n",
    "    [SCE_V_COMMENTLINE] = 0xC0C0C0,\n",
    "    [SCE_V_COMMENTLINEBANG] = 0xC0C0C0,\n",
    "    -- 给关键字加上粗体\n",
    "    [SCE_V_WORD] = 0x00B050 + SCE_BOLD_FONT,\n",
    "    [SCE_V_WORD2] = 0x00B050 + SCE_BOLD_FONT,\n",
    "    [SCE_V_WORD3] = 0xBBBB00 + SCE_BOLD_FONT,\n",
    "    [SCE_V_STRING] = 0xC080FF\n",
    "  }\n",
    "  return style_t\n",
    "end\n",
    "\n",
    "function user_verilog.get_keywords()\n",
    "  local keywords0_set = \"accept_on alias always always_comb always_ff always_latch assert assign assume automatic before bind bins binsof break cell const constraint context continue cover coverpoint cross deassign default defparam design disable dist do edge else enum eventually expect export extends extern final first_match for force foreach forever forkjoin genvar global highz0 highz1 if iff ifnone ignore_bins illegal_bins implements implies import incdir include initial inout input inside instance interconnect intersect large let liblist library local localparam matches medium modport negedge nettype new nexttime noshowcancelled null output packed parameter posedge priority protected pull0 pull1 pulldown pullup pulsestyle_ondetect pulsestyle_onevent pure rand randc ref reject_on release repeat restrict return s_always s_eventually s_nexttime s_until s_until_with scalared showcancelled small soft solve specparam static strong strong0 strong1 struct super sync_accept_on sync_reject_on tagged this throughout timeprecision timeunit type typedef union unique unique0 until until_with untyped use var vectored virtual wait wait_order weak weak0 weak1 while wildcard with within begin case casex casez checker class clocking config covergroup end endcase endchecker endclass endclocking endconfig endfunction endgenerate endgroup endinterface endmodule endpackage endprimitive endprogram endproperty endsequence endspecify endtable endtask fork function generate interface join join_any join_none macromodule module package primitive program property randcase randsequence sequence specify table task\"\n",
    "  local keywords1_set = \"and bit buf bufif0 bufif1 byte chandle cmos event int integer logic longint nand nmos nor not notif0 notif1 or pmos rcmos real realtime reg rnmos rpmos rtran rtranif0 rtranif1 shortint shortreal signed string supply0 supply1 time tran tranif0 tranif1 tri tri0 tri1 triand trior trireg unsigned uwire void wand wire wor xnor xor __FILE__ __LINE__ begin_keywords celldefine default_decay_time default_nettype default_trireg_strength define delay_mode_distributed delay_mode_path delay_mode_unit delay_mode_zero else elsif end_keywords endcelldefine endif ifdef ifndef include line nounconnected_drive pragma resetall timescale unconnected_drive undef undefineall\"\n",
    "  local keywords2_set = \"acos acosh asin asinh assertcontrol assertfailoff assertfailon assertkill assertnonvacuouson assertoff asserton assertpassoff assertpasson assertvacuousoff async$and$array async$and$plane async$nand$array async$nand$plane async$nor$array async$nor$plane async$or$array async$or$plane atan atan2 atanh bits bitstoreal bitstoshortreal cast ceil changed changed_gclk changing_gclk clog2 comment cos cosh countbits countdrivers countones coverage_control coverage_get coverage_get_max coverage_merge coverage_save date dimensions display displayb displayh displayo dist_chi_square dist_erlang dist_exponential dist_normal dist_poisson dist_t dist_uniform dumpall dumpfile dumpflush dumplimit dumpoff dumpon dumpports dumpportsall dumpportsflush dumpportslimit dumpportsoff dumpportson dumpvars dumpvars end enddefinitions error exit exp falling_gclk fatal fclose fdisplay fdisplayb fdisplayh fdisplayo fell fell_gclk feof ferror fflush fgetc fgets finish floor fmonitor fmonitorb fmonitorh fmonitoro fopen fread fscanf fseek fstrobe fstrobeb fstrobeh fstrobeo ftell fullskew future_gclk fwrite fwriteb fwriteh fwriteo get_coverage getpattern high hold hypot increment incsave info input isunbounded isunknown itor key left list ln load_coverage_db log log10 low monitor monitorb monitorh monitoro monitoroff monitoron nochange nokey nolog onehot onehot0 past past_gclk period pow printtimescale q_add q_exam q_full q_initialize q_remove random random readmemb readmemh realtime realtobits recovery recrem removal reset reset_count reset_value restart rewind right rising_gclk rose rose_gclk rtoi sampled save scale scope scope sdf_annotate set_coverage_db_name setup setuphold sformat sformatf shortrealtobits showscopes showvars signed sin sinh size skew sqrt sreadmemb sreadmemh sscanf stable stable_gclk steady_gclk stime stop strobe strobeb strobeh strobeo swrite swriteb swriteh swriteo sync$and$array sync$and$plane sync$nand$array sync$nand$plane sync$nor$array sync$nor$plane sync$or$array sync$or$plane system tan tanh test$plusargs time timeformat timescale timeskew typename ungetc unpacked_dimensions unsigned upscope urandom urandom urandom_range value$plusargs var vcdclose version warning width write writeb writeh writememb writememh writeo PATHPULSE$ STDERR STDIN STDOUT accept_on and assert assume atobin atohex atoi atooct atoreal await bintoa compare constraint_mode cover delete exists expect find find_first find_first_index find_index find_last find_last_index first first_match get get_coverage get_inst_coverage get_randstate getc hextoa icompare index insert itoa kill last len mailbox max min name new next num octtoa or peek pop_back pop_front post_randomize pre_randomize prev process product property push_back push_front put putc rand_mode randomize realtoa reject_on resume reverse rsort sample self semaphore sequence set_inst_name set_randstate shuffle size sort srandom start status std stop substr sum suspend sync_accept_on sync_reject_on tolower toupper try_get try_peek try_put unique unique_index wait_order\"\n",
    "  return keywords0_set,keywords1_set,keywords2_set\n",
    "end\n",
    "\n",
    "function user_verilog.get_autocomplete()\n",
    "  local autocomplete_set = \"__FILE__ __LINE__ accept_on acos and asin asinh assertcontrol assertfailon acosh assertfailoff assertkill assertnonvacuouson assertoff asserton assertpassoff assertpasson assertvacuousoff async$and$array async$and$plane async$nand$array async$nand$plane async$nor$array async$nor$plane async$or$array async$or$plane atan atan2 atanh begin_keywords bit bits bitstoreal bitstoshortreal buf bufif0 bufif1 byte case casex casez cast ceil celldefine chandle changed alias always always_comb always_ff always_latch assert assign assume before bind automatic bins binsof break cell PATHPULSE$ STDERR STDIN STDOUT atobin atohex atoi atooct atoreal await bintoa begin changed_gclk changing_gclk checker class clocking clog2 cmos comment compare config const constraint constraint_mode context continue cos cosh countbits countdrivers countones cover coverage_control coverage_get coverage_get_max coverage_merge coverage_save covergroup coverpoint cross date deassign default default_decay_time default_nettype default_trireg_strength define defparam delay_mode_distributed delay_mode_path delay_mode_unit delay_mode_zero delete design dimensions disable display displayb displayh displayo dist dist_chi_square dist_erlang dist_exponential dist_normal dist_poisson dist_t dist_uniform do dumpall dumpfile dumpflush dumplimit dumpoff dumpon dumpports dumpportsall dumpportsflush dumpportslimit dumpportsoff dumpportson dumpvars edge else elsif end end_keywords endcase endcelldefine endchecker endclass endclocking endconfig enddefinitions endfunction endgenerate endgroup endif endinterface endmodule endpackage endprimitive endprogram endproperty endsequence endspecify endtable endtask enum error event eventually exists exit exp expect export extends extern falling_gclk fatal fclose fdisplay fdisplayb fdisplayh fdisplayo fell fell_gclk feof ferror fflush fgetc fgets final find find_first find_first_index find_index find_last find_last_index finish first first_match floor fmonitor fmonitorb fmonitorh fmonitoro fopen for force foreach forever fork forkjoin fread fscanf fseek fstrobe fstrobeb fstrobeh fstrobeo ftell fullskew function future_gclk fwrite fwriteb fwriteh fwriteo generate genvar get get_coverage get_inst_coverage get_randstate getc getpattern global hextoa high highz0 highz1 hold hypot icompare if ifdef iff ifndef ifnone ignore_bins illegal_bins implements implies import incdir include increment incsave index info initial inout input insert inside instance int integer interconnect interface intersect isunbounded isunknown itoa itor join join_any join_none key kill large last left len let liblist library line list ln load_coverage_db local localparam log log10 logic longint low macromodule mailbox matches max medium min modport module monitor monitorb monitorh monitoro monitoroff monitoron name nand negedge nettype new next nexttime nmos nochange nokey nolog nor noshowcancelled not notif0 notif1 nounconnected_drive null num octtoa onehot onehot0 or output package packed parameter past past_gclk peek period pmos pop_back pop_front posedge post_randomize pow pragma pre_randomize prev primitive printtimescale priority process product program property protected pull0 pull1 pulldown pullup pulsestyle_ondetect pulsestyle_onevent pure push_back push_front put putc q_add q_exam q_full q_initialize q_remove rand rand_mode randc randcase random randomize randsequence rcmos readmemb readmemh real realtime realtoa realtobits recovery recrem ref reg reject_on release removal repeat reset reset_count reset_value resetall restart restrict resume return reverse rewind right rising_gclk rnmos rose rose_gclk rpmos rsort rtoi rtran rtranif0 rtranif1 s_always s_eventually s_nexttime s_until s_until_with sample sampled save scalared scale scope sdf_annotate self semaphore sequence set_coverage_db_name set_inst_name set_randstate setup setuphold sformat sformatf shortint shortreal shortrealtobits showcancelled showscopes showvars shuffle signed sin sinh size skew small soft solve sort specify specparam sqrt srandom sreadmemb sreadmemh sscanf stable stable_gclk start static status std steady_gclk stime stop string strobe strobeb strobeh strobeo strong strong0 strong1 struct substr sum super supply0 supply1 suspend swrite swriteb swriteh swriteo sync$and$array sync$and$plane sync$nand$array sync$nand$plane sync$nor$array sync$nor$plane sync$or$array sync$or$plane sync_accept_on sync_reject_on system table tagged tan tanh task test$plusargs this throughout time timeformat timeprecision timescale timeskew timeunit tolower toupper tran tranif0 tranif1 tri tri0 tri1 triand trior trireg try_get try_peek try_put type typedef typename unconnected_drive undef undefineall ungetc union unique unique0 unpacked_dimensions unsigned until until_with untyped upscope urandom urandom_range use uwire value$plusargs var vcdclose vectored version virtual void wait wait_order wand warning weak weak0 weak1 while width wildcard wire with within wor write writeb writeh writememb writememh writeo xnor xor unique_index\"\n",
    "  return autocomplete_set\n",
    "end\n",
    "\n",
    "function user_verilog.get_reqular()\n",
    "  local symbol_reqular_exp = \"[ \\\\t]*module[ \\\\t]+([_a-zA-Z]+[_a-zA-Z0-9]*)[ \\\\t]*\\\\(\"\n",
    "  return symbol_reqular_exp\n",
    "end\n",
    "return user_verilog",
  }
  local shell_code = table.concat(verilog_code)
  eu_core.save_file(path, shell_code)
  shell_code = nil
  verilog_code = nil
end

return verilog