0

I have a FunnelWeb file whose @{...@} code blocks are tangled into 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 use 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, formats the code buffer with prettier and outputs the resulting lines, followed by the current line.

The problem is that the contents of the @{...@} code block in the code buffer typically do 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 ClassName {...}
    

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) { into function /*m*/ method(args) { before prettier formatting and converts it back afterwards
  • converts an unindented static method(args) { into function /*static*/ method(args) { before prettier formatting and converts it back afterwards
  • converts an unindented get property() { into function /*get*/ property() { before prettier formatting and converts it back afterwards
  • converts an unindented set property(value) { into function /*set*/ property(value) { before prettier formatting and converts it back afterwards.

The after-prettier processing thus performs

code = code
  .replace(/function \/\*(static|get|set)\*\//g, "$1")
  .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 code blocks that cannot be formatted are mostly one-liners like

@$@<Exports@>+=@{
ClassName,
@}

Again my question: Has anyone else tried this and found a better approach?

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.