JavaScript API reference
Documentation index · Web quick start
Creation and conventions
For configuration, callback/event contracts and examples for registerTokens, registerSuggestions, setContextActions, configureReview, comments, proposals and getReviewPackage / loadReviewPackage, see Embedded content and editorial review. These APIs are part of the public editor instance. Their optional UI is included in the shared runtime assets.
const editor = CODEEditor.create(element, options);
// Equivalent after all scripts, in the asset manifest, have loaded:
const another = new CODEEditor.Editor(otherElement, otherOptions);
element is the editable surface container. Creation is synchronous; a ready event is queued as a microtask. Public operations are generally synchronous unless explicitly described as asynchronous. The WinForms bridge wraps them in asynchronous request/reply calls.
The read-only mode accessor reports source or rich. The accepted input alias visual means rich. Avoid assigning session, surface, or options internals directly to mutate a document; use the methods below. The internal helper methods visible on the JavaScript class are implementation details, not all separate host contracts.
Constructor options
| Option | Values/default | Purpose |
|---|---|---|
value |
String; empty default (rich-json also accepts its model form) | Initial document |
format |
markdown default; html, text, rich-json |
Storage representation |
mode |
source default; rich/visual |
Initial view; must fit format/policy |
language |
markdown default; html, text, sql, javascript, typescript, csharp, python, json, css |
Source decoration/comments |
readOnly |
false | Block editing |
wrap |
true | Source wrapping |
decorated |
true | Source syntax decoration |
lineNumbers |
true | Line-number display when a gutter is provided |
gutter |
Optional element | Separate measured line-number container |
tabWidth |
4; allowed 2, 4, 8 | Tab stops and fallback indentation width |
languageIndentation |
Empty object | Per-language widths (2, 4, 8); JSON, HTML/XML, YAML default to 2; e.g. { json: 4 } overrides JSON. |
snippetFormatActions |
null (four defaults) | Ordered { id, label, purpose? } menu items; [] hides them. Custom purpose is the default for configured entries. See code snippets. |
indentWithTabs |
false | Insert tabs instead of spaces |
tabIndents |
true | Tab indentation interaction |
typingRules |
true | Visual Markdown-like input rules |
label |
Optional string | Accessible label override |
placeholder |
Optional string | Empty-surface hint |
fontFamily |
Optional CSS font family | Surface display font |
fontSize |
Optional number; clamped to 10–48 | Surface CSS pixel size |
theme |
Light unless dark |
Editor presentation |
preview |
Optional iframe element | Preview destination |
editorPane |
Optional element, otherwise inferred | Pane beside the preview |
previewSync |
Enabled unless false | Editor-to-preview following |
previewSplit |
0.5; normally 0.2–0.8 | Editor share of split layout |
previewCss |
Empty unless supplied | Preview-only stylesheet text |
previewSyntaxHighlighting |
true | Code snippet coloring in generated previews; independent of decorated, configurable live. |
onPreviewRequest |
Optional function | Mutate/return preview request result; may return Promise |
preset |
full default; plain, basic, notes |
Starting feature policy |
features |
Optional object | Explicit rich-feature overrides |
allowEmbeddedHtml |
true | Supported HTML extension in Markdown |
allowSourceView |
true | Permit switching to Source |
unsupportedContent |
preserve default; reject, convert |
Import/policy behavior |
headingLevels |
[1,2,3,4,5,6] |
Allowed headings |
maxListDepth |
8, range 0–8 | Nesting policy |
allowRemoteImages |
false | Broad HTTP(S) image-display permission |
imageOrigins |
Empty additional allowlist | Exact allowed HTTP(S) origins |
imageTypes |
PNG/JPEG/GIF/WebP MIME strings | Allowed import file types |
maxImageBytes |
10 MiB | Per-file import limit |
externalImages |
Reference behavior by default; reference, reject, import |
Pasted external image treatment |
onImageImport |
Required for file imports | Async file-to-durable-URL callback |
onExternalImageImport |
Required for external import policy | Async external-URL replacement callback |
onEvent |
Optional function | Receive editor events alongside on subscribers |
Call setPreviewVisible(true) after creation to show the preview. A previewVisible value is a host-adapter option, not a general component constructor switch. Likewise findEnabled/replaceEnabled belong to the embedded control popup, not the bare JavaScript search API.
configure(options) supports presentation keys wrap, decorated, lineNumbers, tabIndents, tabWidth, indentWithTabs, typingRules, language, label, placeholder, fontFamily, fontSize, readOnly, theme; preview keys previewSync, previewSplit, previewCss, previewSyntaxHighlighting, onPreviewRequest; and policy keys preset, features, allowEmbeddedHtml, unsupportedContent, maxListDepth, headingLevels, allowSourceView. It does not load/convert formats or replace DOM elements. An empty label, fontFamily, or placeholder clears the previous display override. Omitted keys retain their values.
Document and lifecycle methods
| Method | Result/behavior |
|---|---|
getValue() |
Committed serialized string; refuses composition and pending/failed images; not full policy save validation |
getSnapshot() |
{ value, format, mode, language, sessionId, generation, revision, selection, dirty, policy }; validates saving |
setValue(value, options = {}) |
Load/reset; options can select format, mode, language and import policy |
setMode(mode) |
Switch Source/Visual; returns true on success; retains session/history subject to mapping |
convertFormat(format, options = {}) |
Markdown/HTML conversion; returns { value, report, historyReset: true } |
markSaved(revision, sessionId = currentId) |
Boolean acknowledgement of the current revision; false if stale or unsaveable |
configure(options) |
Apply supported options; can throw on invalid policy/configuration |
getCapabilities() |
Clone of effective policy, including features |
getDiagnostics() |
Policy diagnostic array; empty for plain-text format |
setReadOnly(value) |
Set read-only presentation/command behavior |
setTheme(theme) |
Apply light/dark editor presentation |
rebuild() |
Recreate surface adapter while retaining model/history/selection; returns true |
focus() |
Focus editing surface |
resize() |
Schedule measurement after layout changes |
on(callback) |
Subscribe; returns an unsubscribe function |
destroy() |
Dispose subscriptions, surface, preview and imports; active composition must first settle |
setValue(value, 'source') is a legacy view shorthand; prefer the explicit options object. No method implicitly persists to a database or marks a document saved after a network call.
Selection, search and changes
| Method | Contract |
|---|---|
getSelection() |
Source numeric endpoints or rich block-ID endpoints |
setSelection(selection) |
Set logical selection and focus |
getSelectedText() |
Plain selected model text, not markup |
captureBookmark() |
Return opaque token |
restoreBookmark(token) |
Restore/focus; boolean success |
releaseBookmark(token) |
Remove retained bookmark |
find(query, { caseSensitive, wholeWord } = {}) |
Literal matches as { from, to }[]; updates match decoration |
selectMatch(match) |
Select and reveal match |
replaceRange({ from, to }, text, expectedRevision?) |
Replace flat range; optional stale-result guard; rich restrictions apply |
applyTransaction({ sessionId, revision, edits, label }) |
Atomic source-only edits; each edit is { from, to, text } |
execute(name, args = {}) |
Invoke a command; result is command-dependent |
queryCommandState(name) |
{ enabled, active }; supported marks report bool or mixed state; other commands generally report false active |
Command-state enabled checks do not encode every structural/mode precondition. A command can be unavailable or reject even if the general enabled flag is true. Revision/session checks are detailed in the state guide.
Command names and arguments
| Name | Arguments | Notes |
|---|---|---|
undo, redo |
None | History |
indent, outdent |
None | Source lines or supported rich list context |
format |
{ mark, value? } |
Toggle boolean mark or set an explicit value |
heading |
{ type } |
Rich block style |
clearFormatting |
None | Remove supported inline formatting |
toggleTask |
None | Current task completion |
newline |
{ hard? } |
Context-sensitive newline/continuation |
toggleComment |
None | Uses SQL/JavaScript language in Source |
replaceSelection |
{ text } |
Literal host replacement |
goToLine |
{ line } |
One-based line navigation |
replaceAll |
{ query, replacement, caseSensitive?, wholeWord? } |
Source-only literal replacement |
insertTable |
{ rows?, columns? } |
Default 3×3 |
insertRow, insertColumn |
{ before? } |
Default after current row/column |
deleteRow, deleteColumn, deleteTable |
None | Current table context |
alignColumn |
{ align: 'left'/'center'/'right' } |
Current column |
restartNumbering |
{ start } |
Ordered list |
insertImage |
{ src, alt? } |
Durable reference in Visual mode |
removeImage, retryImage |
{ id } |
Image lifecycle |
exitStructure |
None | Exit current supported table/image context |
pasteTSV |
{ text } |
Visual tabular paste |
Boolean mark names: bold, italic, underline, strike, code, superscript, subscript. Superscript and subscript replace each other. Other marks: href with safe URL or null, font with serif/mono/null, color with blue/green/purple/red/null, background with yellow/lightblue/lightgreen/plum/pink/null, size with 16/20/24/30/null. Null clears the override. Rich block types are p, h1–h6, ul, ol, task, quote, code, hr. Policy can prohibit any corresponding feature. All listed text formats except href are available as Markdown Source formatting commands. Omit value for boolean marks to toggle, or pass true/false for explicit on/off. With a caret, Source inserts paired markers or a style span; selecting Default for a style is a no-op at a caret. Foreground/background, font, size, underline and scripts require embedded HTML in Markdown. Their feature names are textColor, backgroundColor, fontFamily, fontSize, underline, superscript, subscript.
Markdown stores scripts as <sup>2</sup> / <sub>2</sub> and styles as <span style="font-family:serif;font-size:24px;color:red;background-color:yellow">text</span>. These remain editable in Visual mode, including nested supported spans. The curated font, size, and color choices are content formats; the fontFamily/fontSize editor options change display defaults instead.
Selection formatting and host toolbars
getSelectionFormatting() returns one snapshot for both views. formats maps inline mark/style names to { enabled, active }; blocks does the same for p, h1–h6, ul, ol, task, quote, code and hr. Boolean active states are true, false or "mixed". Styles return their value, false for no override, or "mixed". Disabled/read-only formatting can still be active. blockType is a block name or "mixed"; headingLevel is 1–6 or null. listType is ul/ol/task, "mixed" or null, and listDepth is a uniform zero-based depth or null. canIndent, canOutdent, canUndo, canRedo and readOnly are booleans. Queries do not change the document or history. Source projections are cached between edits.
Subscribe to commandStateChange; its selectionFormatting payload contains the snapshot. Refresh after cursor/selection moves, formatting, typing (including automatic input rules, list exits and typing marks), paste, undo/redo, loads, mode switches and policy/read-only changes. selectionChange is also available when only the logical position matters. In WinForms, use CommandStateChanged with the cached SelectionFormatting property; GetSelectionFormattingAsync() explicitly queries the same snapshot. Reading status in that handler does not generate another notification unless state actually changes.
editor.CommandStateChanged += (_, _) =>
{
if (editor.SelectionFormatting is not { } state) return;
var bold = state.GetFormat(TextMark.Bold);
boldButton.Enabled = bold.Enabled;
boldButton.CheckState = bold.IsMixed ? CheckState.Indeterminate
: bold.IsActive ? CheckState.Checked : CheckState.Unchecked;
indentButton.Enabled = state.CanIndent;
outdentButton.Enabled = state.CanOutdent;
headingLabel.Text = state.HeadingLevel is { } level ? $"Heading {level}" : state.BlockType;
};
queryCommandState(name) supports inline formats/styles, block names and indent/outdent. WinForms overloads accept TextMark, BlockStyle or EditorCommand. Execute list indentation through execute('indent') / execute('outdent') or ExecuteAsync(EditorCommand.Indent) / ExecuteAsync(EditorCommand.Outdent). Both views indent selected list items and their descendants; a preceding list item and available nesting depth are required to indent. Outdenting a top-level item returns it to a paragraph. In Source prose/code and Visual code blocks these commands instead indent/outdent literal lines. Changing block style through heading remains a Visual-mode operation.
Images and clipboard methods
| Method | Contract |
|---|---|
clipboard() |
MIME-keyed object: text/plain, and in Visual also text/html |
pasteHTML(html) |
Supported HTML import into Visual; use text paste for Source |
replaceSelectionSource(source) |
Replace selection with native Markdown/HTML source without encoding it as text; preserves supplied source, supports undo and both views; Visual edits obey feature policy |
pasteContent({ html = '', text = '', files = [], source = 'paste' }) |
Rich import or source text insertion; file jobs can continue asynchronously |
importImage(file, source = 'picker', existingId = null) |
Async import; ordinary host callers omit internal retry ID; resolves image ID, which may identify a failed item |
pendingImages() |
Copies of non-ready image records, including failed ones |
retryImage(id) |
Retry using retained file/external callback; may throw if original unavailable |
removeImage(id) |
Remove image via model history; false if absent |
canLoadImage(src) |
Evaluate URL/display-origin policy |
pasteContent returning does not mean its images finished uploading. importImage handles an upload failure by leaving an error item; inspect image state rather than assuming resolution means ready. importExternalImage, cancelImports, and reconcileImages are lifecycle internals used by the import pipeline; prefer policy/callbacks and normal removal/loading to drive them.
Preview methods and hook
| Method | Contract |
|---|---|
setPreviewVisible(visible) |
Boolean; false if no iframe configured |
setPreviewSplit(value) |
Accepted ratio when controller available, otherwise false |
getPreviewSplit() |
Stored ratio (0.5 fallback) |
refreshPreview() |
Schedule a new render |
getPreviewHtml() |
Last accepted HTML or null |
onPreviewRequest(request) can mutate or return { markdown?, html?, handled? }, synchronously or through a Promise. The request includes signal, format and session/version metadata. Handled requires an HTML string. Changing only the callback should be followed by refreshPreview() if immediate rendering is desired. See the preview chapter for full examples and isolation rules.
Events
Every emitted event includes type, sessionId, generation and revision. Additional fields depend on the event:
| Type | Additional information / purpose |
|---|---|
ready |
version (currently 3) |
change |
origin, label, mode; includes document loads |
selectionChange |
Selection changed; query selection |
commandStateChange |
Re-query toolbar state |
dirtyChange |
dirty |
saved |
Save baseline acknowledged |
saveRequested |
Host should perform saving |
presentation |
Display/view/policy change |
status |
message, often an actionable rejection |
shortcut |
key such as f, h, g |
openLinkRequested |
url; host decides navigation |
previewResize |
split |
previewRendered |
custom indicates output without normal model anchors |
previewError |
message |
assetStateChange |
id, state, optional message for file import paths |
assetAbandoned |
Image/result metadata for an obsolete completion |
Events are not a transactional database log. External-image paths and file-image paths do not emit every lifecycle event identically; pendingImages and document state are authoritative. Unsubscribe handlers on host teardown and keep event handlers lightweight.
Image sizing/movement, toolbar placement, resource limits, review annotations and margin settings are described with examples in chapter 20.
UI styling: uiTheme / setUITheme(theme?) / getUITheme() provide instance-scoped CSS variables and stylesheet text; uiThemeChange signals a theme update. setCommentExpanded(id, expanded), toggleComment(id) and getCommentPresentation() control per-thread presentation without changing article state; commentPresentationChange carries id and expanded. Review options add singleOpen and commentMarkers. See the styling and bubble guide.
UI wording: uiStrings, setUIStrings(config?), getUIStrings() and getUIStringCatalog() configure per-instance text and accessibility labels. CODEEditor.getUIStringCatalog() is available before initialization; uiStringsChange reports updates. See UI wording and localization.
appearance, setAppearance(value = {}) and getAppearance() expose named host font, color and source spacing settings. See host appearance settings. Updates replace the overrides; an empty object restores theme defaults without document edits.
imageToolbar configures the Visual image toolbar at creation or with configure({ imageToolbar }); see image toolbar configuration and image selection colors.
Native spellcheck
Spellcheck defaults to enabled for prose in Visual mode and Markdown/plain-text Source mode. Fenced snippets and inline code are excluded; Source views of programming languages and raw HTML are not checked. No dictionaries or word lists are shipped or maintained by the editor.
const editor = CODEEditor.create(element, {
value: 'Write here',
spellCheck: true,
spellCheckLanguage: 'de-DE'
});
editor.configure({ spellCheck: false });
editor.configure({ spellCheck: true, spellCheckLanguage: 'es-ES' });
spellCheckLanguage is a language tag, independent of the language used for syntax highlighting. Examples: en-US, en-GB, de-DE, es-ES, fr-FR, it-IT, nl-NL, pt-PT. An empty string restores inherited language behavior. Language hints do not install dictionaries or override browser/OS proofing preferences. In particular, Chromium/WebView2 may ignore a changed HTML lang for spelling; configure browser/OS languages as needed. See WebView2 language limitation.
Right-click an underlined word to use the browser's native suggestions and dictionary/ignore actions, where provided by that browser/runtime. These actions and their wording are browser-owned; the editor does not provide a separate Ignore list or dictionary. Native spelling corrections enter the normal document history and change tracking. Websites should leave the native context menu enabled to retain this functionality.
Textblock preview and review switches
onTextblockPreviewRequest(request) expands registered token occurrences in preview; see textblock actions and preview for the request and native equivalent. reviewEnabled, commentsEnabled, and changeTrackingEnabled default to true and can change through configure; see disabling review features. language: 'xml' selects XML Source syntax independently of format.
Width options: maximumEditWidth: 900, maximumPreviewWidth: 900, restrictMaximumEditWidth: true, and restrictMaximumPreviewWidth: true. Widths are positive integer CSS pixels. Set either restriction to false to expand that pane. These options can also be changed through configure(); each pane centers its content independently.