Have you considered something like in attached patch instead of introducing %S format? I think it's much more robust and I hope it will be possible to remove all hacks/special handling this way (probably except of end of templates case (> >)).
The general idea is to introduce OPTIONAL_WS that is used to insert space in all the places where it's optional. The space is added only if first string ends with OPTIONAL_WS and second starts with OPTIONAL_WS. The attached patch was not really tested, it's just a quick WIP version to demonstrate the idea.
[tmp.diff](/uploads/399b0a804f25b1c9adb6e820ba309429/tmp.diff)