#####
##### Generate the file julia-mode-latexsubs.el. Invoke from the shell as
#####
##### julia make-julia-latexsubs.jl
#####

@assert VERSION ≥ v"1"          # use a recent Julia version

import REPL.REPLCompletions: latex_symbols, emoji_symbols

"""
Write Emacs lisp code that populates the hash table named `varname` to `dest`, using
key-value pairs from `src`.
"""
function write_latexsubs_tables(io, src, hashvar, abbrevvar)
    for (k, v) in sort!(collect(src), by = last)
        ks = escape_string(k)
        vs = escape_string(v)
        if occursin(r"^\\U[0-9A-Fa-f]+$", vs)
            # codepoints outside the BMP can be problematic in older Emacsen
            cp = vs[3:end]
            println(io, "    (let ((c (decode-char 'ucs #x$cp)))")
            println(io, "      (if c (progn")
            println(io, "        (puthash \"$ks\" (char-to-string c) $(hashvar))")
            println(io, "        (define-abbrev $(abbrevvar) \"$ks\" \"$vs\" nil :system t))))")
        else
            println(io, "    (puthash \"$ks\" \"$vs\" $(hashvar))")
            println(io, "    (define-abbrev $(abbrevvar) \"$ks\" \"$vs\" nil :system t)")
        end
    end
end

open("julia-mode-latexsubs.el", "w") do io
    println(io, ";;; julia-mode-latexsubs.el --- Generated variables for Julia mode -*- lexical-binding: t; -*-")
    println(io, ";; This file is automatically generated. Do not edit by hand.")

    println(io)
    println(io, "(define-abbrev-table 'julia-latexsub-abbrev-table ()")
    println(io, "  \"Abbrev table for Julia LaTeX substitution.\"")
    println(io, "  :regexp \"\\\\(\\\\\\\\[[:graph:]]+\\\\)\")")

    println(io)
    println(io, "(defconst julia-mode-latexsubs")
    println(io, "  (let ((table (make-hash-table :test 'equal)))")
    write_latexsubs_tables(io, merge(latex_symbols, emoji_symbols), "table", "julia-latexsub-abbrev-table")
    println(io, "    table))")

    println(io)
    println(io, "(provide 'julia-mode-latexsubs)")
end

@info "generated latex substitutions"
