title: We Used a Textarea as a Code Editor. It Worked Great Until Line 3,000.
We Used a Textarea as a Code Editor. It Worked Great Until Line 3,000. The textarea was a great choice. I'll fight anyone who says otherwise, and I'll lose, because the textarea has been winning arguments since 1997. Our old editor was two elements stacked on top of each other: a <pre> showing colored text, and a <textarea> on top with transparent text and a visible caret. A scroll handler kept…
We used a textarea as a code editor and it worked well until line 3,000. The textarea was a popular choice, having been in use since 1997. Our previous editor consisted of a pre element displaying colored text and a textarea on top, with a scroll handler keeping them aligned. The browser handled selection, drag, copy-paste, find, undo, and more, all for free.
The candidate strip, found characters, and cursor all appeared effortlessly. We wrote about 600 lines of JavaScript to create a minimap, syntax highlighting for six languages, find and replace, and a dark theme. Everything worked smoothly for around 3,000 lines, but line 3,000 caused issues. The pre and textarea elements had to agree on various aspects like font, size, line height, and more.
Any disagreement would cause the caret to drift, leading to significant problems in a 3,000-line file. Some of the findings included tabs rendering differently across browsers, emoji and CJK characters falling back to different system fonts, soft wrap inconsistencies, and problems with line wrapping. Fixing the issues on one browser often broke it on another, and the CPU usage increased significantly due to the tokenizer, DOM churn, and frequent DOM node creation and destruction.
The canvas was then used to draw everything, with each line being a fillText() call. The caret was drawn at a specific position based on the column and character width, avoiding the caret drift issue. Additional features like multiple cursors, sticky scroll, folding, inline diagnostics, and a command palette became practical. The canvas approach had its challenges, such as handling IME input, pasting, and keyboard shortcuts.
While the old editor was 600 lines, the new one consisted of about 2,900 lines of code. Despite the initial investment, the canvas approach proved to be worth it for the team, as they would have encountered the same issues eventually. However, they also recognized that using an existing library like CodeMirror would have been a better choice for most developers.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.