CodeMirror 6 + prettier?

Hi, I’m hoping to use prettier to format code in Codemirror 6. I’m not tied to Prettier specifically; I just need to format the editor’s code automatically on load and save. Could someone point me in the right direction?

Find a pretty-printer that you can run in the browser (or set it up as an HTTP service), take code from editor (view.state.doc.toString()), run it through the pretty-printer, and then either update the entire document if something changed (easy, but crude), or find the precise changes (through diffing or maybe the pretty-printing library will tell you) and apply those via view.dispatch({changes: ....}).

1 Like

Does the crude update-whole-document method keep the cursor position as close as possible?

some pretty-print algorithms will take the cursor position as input and tell you where to place it afterwards. Ours didn’t, so I wrote a heuristic that’s worked fine enough for our needs so far:

1/ count the number of non-whitespace, non-parentheses characters before the old cursor position. Also separately count the number of parentheses.
2/ With the new text, seek until you’ve hit the same number of non-whitespace, non-parentheses characters. Then greedily consume any parentheses to a maximum of your earlier count.

Ignoring the parentheses logic for a second, the intuition is that if your pretty-print mostly changes whitespace then just put the cursor after the same number of non-whitespace characters. In our case the pretty print could also affect parentheses so I tacked that into the heuristic.

It won’t be as good as the formatter handling this itself, but it’s worked fine for us so far.