Why?
I write a lot of formulas in Google Sheets. Sometimes they get so long and complicated that formatting becomes a real problem. So I made this to help with that, but the feature set is a little lacking so it's honestly not that useful in real situations. But it's cool.
How?
It's complicated...
The input is a basic textarea
element, but the text is transparent. We add an overlay of div
elements that displays each line of the input, so that styling can be added to the text (which isn't possible inside the textarea
. The leading equals sign that defines the formula is inserted in this overlay, not in the actual text.
The overlay is built using a CSS grid layout, so that long lines that wrap will properly cause the line numbers to shift down, similar to actual code editors.
After every change to the input, the text is parsed into tokens, such as strings, identifiers, ranges, or literals. These tokens are sent through a parser that provides additional syntax semantics, such as unclosed parentheses or unexpected tokens.
Formatting follows an algorithm described in the paper
"A prettier printer" by Philip Wadler. This algorithm is also used by the popular opinionated formatter
Prettier, though this project comes nothing close to the power and scope of Prettier. The actual implementation followed
this article.
More?
There could be more plans for this project, most notably linting features. Some ideas I had were highlighting bracket pairs, a bit of "known formula" hints (e.g., wrong number of arguments, capitalize known formula names, etc.), and smarter formatting (e.g., grouping pairs of arguments on the same line, collapsing closing parentheses, etc.). If you have any ideas, feel free to
open an issue on the Github repo.