git/intake/main
scripts/gen-diacritics.py
59 lines2 KB last change raw · history
#!/usr/bin/env python3
"""Regenerate internal/tui/diacritics.go from kitty's rowcolumn-diacritics table.

Usage: scripts/gen-diacritics.py [table.txt]
"""
import sys
import urllib.request

URL = ("https://raw.githubusercontent.com/kovidgoyal/kitty/master/"
       "gen/rowcolumn-diacritics.txt")

OUT = "internal/tui/diacritics.go"


def load(path):
    if path:
        return open(path).read()
    return urllib.request.urlopen(URL, timeout=30).read().decode()


def main():
    text = load(sys.argv[1] if len(sys.argv) > 1 else None)
    marks = [int(l.split(";")[0], 16) for l in text.splitlines()
             if l.strip() and not l.startswith("#")]
    if len(marks) != 297:
        sys.exit(f"expected 297 marks, read {len(marks)}")

    lines = [
        "// Code generated by scripts/gen-diacritics.py; DO NOT EDIT.",
        "",
        "package tui",
        "",
        "// charmbracelet/x/ansi/kitty only ships the first six of these and returns",
        "// the first mark for anything past five, which quietly mis-addresses every",
        "// cell past column six. this is kitty's full table.",
        "var placeholderDiacritics = [...]rune{",
    ]
    for i in range(0, len(marks), 8):
        chunk = marks[i:i + 8]
        lines.append("\t" + " ".join(f"0x{m:04X}," for m in chunk))
    lines += [
        "}",
        "",
        "func diacriticAt(i int) rune {",
        "\tif i < 0 || i >= len(placeholderDiacritics) {",
        "\t\treturn placeholderDiacritics[0]",
        "\t}",
        "\treturn placeholderDiacritics[i]",
        "}",
        "",
    ]
    with open(OUT, "w") as f:
        f.write("\n".join(lines))
    print(f"wrote {OUT}: {len(marks)} marks")


if __name__ == "__main__":
    main()