# http://json5.org
# ‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾

# Detection
# ‾‾‾‾‾‾‾‾‾

hook global BufCreate .*[.](json5) %{
    set-option buffer filetype json5
}

# Initialization
# ‾‾‾‾‾‾‾‾‾‾‾‾‾‾

hook global WinSetOption filetype=json5 %{
    require-module json5

    hook window ModeChange pop:insert:.* -group json5-trim-indent json5-trim-indent
    hook window InsertChar \n -group json5-insert json5-insert-on-new-line
    hook window InsertChar \n -group json5-indent json5-indent-on-new-line
    hook window InsertChar .* -group json5-indent json5-indent-on-char

    hook -once -always window WinSetOption filetype=.* %{ remove-hooks window json5-.+ }
}

hook -group json5-highlight global WinSetOption filetype=json5 %{
    add-highlighter window/json5 ref json5
    hook -once -always window WinSetOption filetype=.* %{ remove-highlighter window/json5 }
}


provide-module json5 %(

# Highlighters
# ‾‾‾‾‾‾‾‾‾‾‾‾

add-highlighter shared/json5 regions
add-highlighter shared/json5/code default-region group
add-highlighter shared/json5/string region '"' (?<!\\)(\\\\)*" fill string
add-highlighter shared/json5/string2 region "'" (?<!\\)(\\\\)*' fill string
add-highlighter shared/json5/comment region '//' '$' fill comment
add-highlighter shared/json5/multiline_comment region /\* \*/ fill comment

add-highlighter shared/json5/code/ regex \b(true|false|null|\d+(?:\.\d+)?(?:[eE][+-]?\d*)?|0x[\da-fA-F]+)\b 0:value

# Commands
# ‾‾‾‾‾‾‾‾

define-command -hidden json5-insert-on-new-line %[
    # copy // comments prefix and following white spaces
    try %{ execute-keys -draft <semicolon><c-s>kx s ^\h*\K/{2,}\h* <ret> y<c-o>P<esc> }
]

define-command -hidden json5-trim-indent %{
    # remove trailing white spaces
    try %{ execute-keys -draft -itersel x s \h+$ <ret> d }
}

define-command -hidden json5-indent-on-char %<
    evaluate-commands -draft -itersel %<
        # align closer token to its opener when alone on a line
        try %< execute-keys -draft <a-h> <a-k> ^\h+[\]}]$ <ret> m <a-S> 1<a-&> >
    >
>

define-command -hidden json5-indent-on-new-line %<
    evaluate-commands -draft -itersel %<
        # preserve previous line indent
        try %{ execute-keys -draft <semicolon> K <a-&> }
        # filter previous line
        try %{ execute-keys -draft k : json5-trim-indent <ret> }
        # indent after lines ending with opener token
        try %< execute-keys -draft k x <a-k> [[{]\h*$ <ret> j <a-gt> >
        # deindent closer token(s) when after cursor
        try %< execute-keys -draft x <a-k> ^\h*[}\]] <ret> gh / [}\]] <ret> m <a-S> 1<a-&> >
    >
>

)
