v0.3.2 · MIT · by Kore Org

A code editor,
in about 32 KB

Caret is a tiny code editor engine for the web. Built on the EditContext API, with Highlight.js, undo/redo, themes and read-only mode. The engine behind Lexius.

$npm install @pfmcodes/caret
~32 KBtotal JavaScript
~25 msload time in Chrome
~650lines of code
MITfree and open source

Live demo

Type in it

In Chrome or Edge this is the real editor running on the page. Try Tab, Shift+Tab, Ctrl+Z and the arrow keys. Other browsers show a static preview.

loading…

Why Caret

Small on purpose

Most web code editors ship megabytes. Caret lets the browser handle input through EditContext and does the rest in a few hundred lines.

⌁

EditContext input

Keyboard, IME and clipboard come from the browser's own EditContext API, not a hidden textarea.

{ }

Syntax highlighting

Live highlighting through Highlight.js, with dark and light themes to pick from.

↶

Undo and redo

Full history with the cursor restored to where you were. Ctrl+Z, Ctrl+Y, Ctrl+Shift+Z.

▌

Custom caret

A caret drawn with the Range API, so you can colour it and give it a focus glow.

⇥

Editing basics

Line numbers, Tab and Shift+Tab indent, column-preserving arrow keys, plain-text paste.

⚿

Read-only mode

Set lock: true to display code without letting anyone change it.

How it compares

EditorSizeNotes
Caret~32 KBEditContext + Highlight.js. Chromium only for now.
CodeMirror 6~400 KBModular, works in all browsers.
Monaco~5 MBThe VS Code editor. Feature-rich and heavy.

Sizes are the author's rough figures from the launch write-up, not independent benchmarks.

Usage

Up and running in a few lines

Caret is ES modules only. Install it, give createEditor an element, some starting text and options.

API

Options and methods

createEditor(parent, content, options)

OptionDefaultWhat it does
idrequiredUnique id per editor
languageplaintextHighlight.js language
hlThemehybridHighlight theme name
dark—Dark or light editor
lockfalseRead-only mode
theme—Custom colours, { dark, light }
font—Font loaded from a URL
focusColor, shadow, shadowColor—Focus glow styling

Instance methods

MethodPurpose
getValue() / setValue(text)Read or replace the content
getCursor() / setCursor(pos)Cursor position
undo() / redo()History
onChange(fn)Content changed
onCursorMove(fn)Cursor moved
setLanguage(name)Switch highlighting
isFocused()Is the editor focused
delete()Tear the editor down

Check the README for the exact createEditor argument order, since the docs and examples differ on where id goes.

Themes

Pick any Highlight.js theme with hlTheme.

Compatibility

Browser support

Chromium only for now. Chrome and Edge work today. Firefox and Safari don't support the EditContext API yet, so Caret shows an error message there instead of breaking silently.

About

Built for Lexius

Caret started because Monaco felt slow and heavy for a small editor. It is the editor engine of Lexius, and it's open source under the MIT license, maintained by Kore Org.