Skip to content

Options and keymaps ​

tsx
import { Switch } from '@adecore/ui';
import { useEffect, useState } from 'react';
import { EditorFrame } from '../shared/editor-frame.tsx';
import { SAMPLE, useEditor } from '../shared/editor.ts';

const OPTIONS = { text: SAMPLE, language: 'typescript', theme: 'demo', rightMargin: 60 } as const;

export default function EditorOptionsDemo() {
    const { host, editor } = useEditor(OPTIONS);
    const [wrap, setWrap] = useState(false);
    const [guides, setGuides] = useState(true);
    const [whitespace, setWhitespace] = useState(false);
    const [readOnly, setReadOnly] = useState(false);

    useEffect(() => editor?.setWrap(wrap), [editor, wrap]);
    useEffect(() => editor?.setGuides(guides), [editor, guides]);
    useEffect(() => editor?.setWhitespace(whitespace), [editor, whitespace]);
    useEffect(() => editor?.setReadOnly(readOnly, 'This demo is read-only.'), [editor, readOnly]);

    const toggle = (label: string, checked: boolean, onChange: (checked: boolean) => void) => (
        <label className="flex items-center gap-2 px-1 text-xs text-text">
            <Switch label={label} checked={checked} onCheckedChange={onChange} />
            {label}
        </label>
    );

    return (
        <EditorFrame
            host={host}
            className="h-64"
            toolbar={
                <>
                    {toggle('Wrap', wrap, setWrap)}
                    {toggle('Guides', guides, setGuides)}
                    {toggle('Whitespace', whitespace, setWhitespace)}
                    {toggle('Read-only', readOnly, setReadOnly)}
                </>
            }
        />
    );
}

Mount options ​

engine.mount(element, options) takes EditorOptions. Most options have a setter that changes them without a remount.

OptionDefaultSetterMeaning
textrequiredsetTextThe document
themerequiredsetThemeThe syntax theme id, an EditorTheme string, handed to the tokenizer
languageplain textThe language id, for the tokenizer and the editing commands
pathThe file's path or name, for a language service to read a dialect off
handBack[]Extra host chords for this mount, combined with the engine shortcuts
readOnlyfalsesetReadOnlyWith readOnlyReason, what a person is told when typing into it
wrapfalsesetWrapWrap long lines
indentation4, spacessetIndentationAn EditorIndentation, { tabSize, insertSpaces }
smartKeysDEFAULT_SMART_KEYSsetSmartKeysWhat happens as a person types; see below
guidestruesetGuidesA line at each indentation level
stickyScrolltruesetStickyScrollKeep the headers of the blocks scrolled out of sight pinned on top
whitespacefalsesetWhitespaceSpaces as dots and tabs as arrows
rightMarginnonesetRightMarginA column to draw a line at; null removes it
foldOutline'hover'setFoldOutlineWhen the fold arrows show in the gutter, an EditorFoldOutline of 'off', 'hover' or 'always'
messagesnonesetMessagesA partial EditorMessages, { noMoreOccurrences, fold, unfold }. The editor says the first when select next occurrence finds no more, and nothing without it; the others name the fold controls with {start} and {end} placeholders
labelCode editorsetLabelThe accessible name of the editor, such as Commit message, in the app's language
foldsFolds kept from the last time; see folding
foldDefaultsFold roles to collapse when a file opens without kept folds
line, columnOne-based, where the caret starts
scrollTopIn pixels, where the view starts; without it the caret's line is in view
todoWordsDEFAULT_TODO_WORDSsetTodoWordsThe words that mark a TODO comment; see below
fontSizethe page'ssetFontSizeIn pixels, a zoomed size the host kept; see zoom
zoom12 to 90, wheel onEditorZoom: { min, max, wheel }, the zoom range and whether the wheel zooms
foldingtruefalse disables all folding, for a projected document whose rows must stay visible. foldOutline: 'off' only hides the arrows

setReadOnly blocks typing, commands and applyEdits. setText still works, for a reload from disk.

TODO comments ​

The editor draws a comment containing one of the todoWords (TODO and FIXME by default, whole words in any case) in --editor-todo italics from the word to the end of the comment's line, with a tick in the scroll track. Words in strings or code do not count. An empty list turns it off. findTodos(text, language, options?) returns the same TodoMatches for a host that lists them.

Zoom ​

runCommand('increaseFontSize') and runCommand('decreaseFontSize') change the code size by one pixel, and runCommand('resetFontSize') returns to the page's --code-font-size. Ctrl or Cmd with the wheel, or a pinch, does the same unless zoom.wheel is false. The size stays in whole pixels between zoom.min and zoom.max, never below 12. Line height scales with it.

Each zoom step goes to onFontSizeChange with the new size, or null after a reset. The host can store it and pass it back as fontSize, or apply it to other editors with setFontSize, which does not fire onFontSizeChange. getFontSize() returns the current size. The commands have no default chord, since other editors' zoom chords are fold keys here.

refreshFont() measures the code font again. Call it after changing --font-mono, --code-font-size or --code-line-height, or after a web font loads.

Smart keys ​

EditorSmartKeys turns each typing behavior of the model on or off. All are on except camelHumps. setSmartKeys takes a partial object.

KeyWhat it does
autoPairBracketsA typed bracket brings its closer, and typing the closer steps over
autoPairQuotesThe same for quotes
surroundSelectionA bracket or quote typed over a selection wraps it
tabOutOfClosersTab steps over a closer the editor added
smartIndentOnEnterEnter indents, continues comments and closes braces
indentOnPasteA pasted block takes the indentation of the line it lands on
smartSemicolonA ; typed inside a call goes to the end of the statement
smartArrowIn PHP a - after a variable, a member, ) or ] becomes ->
templateLiteralsIn JavaScript and TypeScript, ${ typed in a quoted string makes it a template literal; one undo restores the quotes
camelHumpsWord moves also stop inside camelCase and snake_case words

Keymaps ​

@adecore/editor/keymap holds one table of every editor and language command, with a chord for macOS and one for other platforms. Mod is Cmd on a Mac and Ctrl elsewhere. Ctrl and Meta are the physical keys. A null chord means no key, as for the fold levels, saveAsLiveTemplate, wrapWithAbbreviation and the AI commands selectionToChat, inlineEdit, suggestInline and acceptGhostWord. The template commands follow IntelliJ: insertLiveTemplate is Mod+J, surroundWith is Mod+Alt+T, surroundWithLiveTemplate is Mod+Alt+J and unwrap is Mod+Shift+Delete (forward delete on a Mac). See the breaking change for wrapWithAbbreviation.

Resolve the table once with the app's overrides, and pass the same table to the engine, to ProjectLanguage and to menus that print keys:

ts
import { chordOf, parseChord, resolveKeymap } from '@adecore/editor/keymap';

const keymap = resolveKeymap({
    duplicateLine: { mac: 'Mod+Shift+D', other: 'Ctrl+Shift+D' },
    goToSymbol: { mac: null, other: null }
});

const engine = createSmartEditorEngine({
    tokenizer,
    keymap,
    apple,
    handBack: [parseChord('Mod+Shift+P')]
});

chordOf('duplicateLine', apple, keymap); // 'Mod+Shift+D'

resolveKeymap takes KeymapOverrides and fills every id they leave out from KEYMAP, returning a full Keymap. A KeymapId names a command of the table, and KEYMAP_IDS lists them all, for a settings screen. Commands added after the first table are OptionalKeymapIds, so a Keymap written before them stays valid. parseChord throws on a chord it cannot read, so validate stored chords first. A KeyBinding may carry takenMac or takenOther, a TakenKey ({ platform, by }), to record that a platform also uses the chord. The editor ignores it.

typesInsteadOfChord(event, apple) tells whether a Ctrl+Alt press off macOS types a character, as AltGr+Q types @ on many layouts. Such a press does not match a chord. Keys that type nothing, such as arrows, always match. A host that matches its own chords uses it to leave typing alone.

A person who rebinds a key does not reload the editors that are open. Pass keymap and handBack as functions, and the editor asks again on every key press:

ts
let keymap = resolveKeymap(overrides);

const engine = createSmartEditorEngine({
    tokenizer,
    keymap: () => keymap,
    handBack: () => handedBack
});

// After a rebind, the open editors follow with the next key.
keymap = resolveKeymap(newOverrides);

handBack in the options of one mount takes a function too. Return the same object while nothing changed; the editor calls the function for every key.

Two hooks let the app take keys:

  • handBack chords pass through the editor untouched, so the app's global shortcuts work while the editor has focus.
  • editor.onKeyDown(handler) sees every other key first. Returning true takes the key; the editor prevents its default and ignores it.

A key table id is not always a command name: collapse runs the view command collapseRegion. To run a command from a menu, pass an EditorRunCommand to runCommand; see Text and events.

Licenses and third-party notices are listed in each package.