I have a FunnelWeb file whose @{...@}
code blocks form a Javascript program. I want to use prettier to format these code blocks while leaving the non-code FunnelWeb source unchanged.
Here is my approach, my question is: are there better alternatives?
I have a Node.js program that processes the file line by line. Unless it is in “code block” state, it simply copies each line to the output. But:
- If a line starts with a code block definition
@$@<...@>@{
, it outputs that line, creates a new “code buffer” and switches to “code block” state. - If it is in code block state, it adds the line to the code buffer.
- If a line starts with
@}
, it leaves the “code block” state, processes the code buffer with prettier and outputs the resulting lines, followed by the current line.
The problem is that the @{...@}
code block in the code buffer typically does not contain a Javascript program considered error-free by prettier. This is because FunnelWeb works by pasting code blocks together and into other code blocks without any regard to the programming language that they contain. In particular
- a code block may contain
@<...@>
references to other code blocks - a code block often contains one method of a class and looks like
method(args) {...}
and prettier rejects this in the absence of the surrounding
class Class {...}
To circumvent these two problems, my Node.js program
- wraps
@<...@>
in comment syntax like/*@<...@>*/
before prettier formatting and unwraps them afterwards - converts an unindented
method(args) {
intofunction /*m*/ method(args) {
before prettier formatting and converts it back afterwards - converts an unindented
static method(args) {
intofunction /*s*/ method(args) {
before prettier formatting and converts it back afterwards.
The after-prettier processing thus performs
code = code
.replaceAll("function /*s*/", "static")
.replaceAll("function /*m*/ ", "")
.replace(//*|*//g, "");
And if a code block still cannot be formatted by prettier, the unformatted code is output.
With this approach my only code blocks that cannot be formatted are one-liners like
ModuleName,
Again my question: Has anyone else tried this and found a better approach?