Puzzled by something in markdown.kak

I’ve been reading some of the code in lib/kak/rc to develop more familiarity with typical idiom, and I’ve stumbled on a line in rc/filetype/markdown.kak with behaviour I don’t understand.

Line 96 of markdown.kak in current master reads

        execute-keys "%arg{1}s```\h*\{?[.=]?\K\w+<ret>" # }

My parsing of this is that it substitutes %arg{1} into the string, then runs the resulting string of keys, with # } just being a comment at the end of the line.

However, if I remove the comment, or change # } into # wibble, the file fails to load with

/lib/kak/autoload/filetype/markdown.kak:parse error: 39:27: unterminated string '%{...}'
Autoload: could not load /lib/kak/autoload/filetype/markdown.kak

in the debug buffer.

So I suppose I must be wrong in parsing this as a comment. Can anybody explain? I looked for another instance of anything like this in the Kakoune standard library that might shed some light, but didn’t find one.

1 Like

If I replace \{ with the equivalent \x7b in the regular expression, the trailing # } is no longer needed, so it’s a workaround for unbalanced braces in the provide-module… but it really feels like surprising behaviour!

I’m guessing the whole of the provide-module body is treated as a string at the point of reading the command, including embedded comments.

That’s exactly it, yes. In Kakoune, %{} is just another string syntax like "" or '', just with different quoting rules. %{} happens to be more suitable for deeply nested strings (such as most Kakoune plugins), so you’ll see it used most often, but there’s no reason other than maintainability you couldn’t do:

provide-module foo '
    define-command bar ''
        hook global NormalIdle .* ''''
             echo ''''''''Don''''''''''''''''t Let''''''''''''''''s Start''''''''
        ''''
    ''
'

As a matter of style, it’s preferable to use a different way to escape the grouping character if possible (like \x7b) or just use a different delimiter for all the containing strings (such as %§§ or even just %() or %[]) rather than a hack like putting } in a comment.

2 Likes

As a matter of style, it’s preferable to use a different way to escape the grouping character if possible (like \x7b ) or just use a different delimiter for all the containing strings (such as %§§ or even just %() or %[] ) rather than a hack like putting } in a comment.

Thanks! Yes, that does explain why this sort of thing doesn’t occur anywhere else in the standard library, when I looked for more examples.

There’s an interesting question here about what the more elegant/clear thing to do is in the situation markdown.kak’s author finds themselves, where the nesting from top level covers enough area you don’t really want to alter quote characters all the way out from a regex. \x7b works, as would \{?\}{0}, but neither is all that pretty!