JavaScript API reference
Documentation index · Web quick start
Creation and conventions
const editor = CODEEditor.create(element, options);
// Equivalent after all scripts, including advanced.js, 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 |
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/indent width |
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 |
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, onPreviewRequest; and policy keys preset, features, allowEmbeddedHtml, unsupportedContent, maxListDepth, headingLevels, allowSourceView. It does not load/convert formats or replace DOM elements. Some string overrides only apply when truthy, so clearing a previously set label/font/placeholder with an empty string is not uniformly implemented.
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. Other marks: href with safe URL or null, font with serif/mono/null, color with blue/green/purple/red/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. Markdown Source supports only bold/italic formatting toggles among these rich mark commands.
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 |
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.