Vela, our next-generation charting platform, is live at vela.luxalgo.com.
LuxAlgo

Code editor

API reference for the Pine code editor handle, configuration options, diagnostics, and language dataset types.

View as Markdown

This page documents the Pine code editor APIs, including enabler configuration options, the programmatic CodeEditorHandle, diagnostics, draft persistence, and the language reference types exported from @luxalgo/vela-pro/editor.

Import symbols on this page from @luxalgo/vela-pro unless noted otherwise on the entry. Related guide: Pine code editor.

Feature enabler for this area (enableCodeEditor) is documented on Enablers and options.

Functions

codeEditor

The code editor of a shell: pass the widget or workspace when the page runs several (codeEditor(widget)); with exactly one, the bare call resolves it. Null when no editor is mounted (feature disabled, or the shell not built yet).

Also exported from @luxalgo/vela-pro/editor.

function codeEditor(host?: { root: HTMLElement }): CodeEditorHandle | null

See also: CodeEditorHandle.

Classes

DraftStore

Reads and writes the draft, debounced. Storage may be synchronous (localStorage) or asynchronous (REST, IndexedDB): writes are fire-and-forget either way, so the editor never waits on a backend, and a rejected write is reported once rather than thrown into the keystroke path.

Import from @luxalgo/vela-pro/editor.

class DraftStore {
    constructor(storage: VelaStorage, key?: string);
    load(): Promise<string | null>;
    save(source: string): void;
    flush(): void;
    destroy(): void;
}
MemberTypeDescription
constructor(storage: VelaStorage, key?: string)Default: key = DRAFT_KEY.
load()() => Promise<string | null>The stored draft, or null.
save()(source: string) => voidQueue a write. Successive calls within the debounce window collapse to one.
flush()() => voidWrite immediately whatever is queued: called on panel close and on destroy.
destroy()() => void

From @luxalgo/vela/widget: VelaStorage.

Interfaces and types

BeforeReplaceDocumentHook

Return (or resolve) false to keep the current document; anything else lets it go.

Also exported from @luxalgo/vela-pro/editor.

type BeforeReplaceDocumentHook = (event: ReplaceDocumentEvent) => boolean | void | Promise<boolean | void>;

See also: ReplaceDocumentEvent.

CodeEditorHandle

The programmatic handle on a shell's code editor: everything the panel's UI can do, callable from host code. Works with the panel CLOSED: the code lives as a string and run() goes through chart.runIndicator, so nothing here forces Monaco to load (only opening the panel does).

Also exported from @luxalgo/vela-pro/editor.

interface CodeEditorHandle {
    getCode(): string;
    setCode(source: string, opts?: { run?: boolean }): Promise<boolean>;
    run(): Promise<RunOutcome>;
    remove(): void;
    bind(handleId: string | null): boolean;
    target(): string | null;
    onDidChangeTarget(cb: (handleId: string | null) => void): () => void;
    edit(handleId: string): Promise<boolean>;
    onDidStartRun(cb: (event: { mode: RunMode }) => void): () => void;
    onDidEndRun(cb: (event: EditorRunEnd) => void): () => void;
    setDiagnostics(diagnostics: readonly EditorDiagnostic[]): void;
    setBeforeReplaceDocument(hook: BeforeReplaceDocumentHook | null): void;
    addHeaderButton(button: EditorHeaderButton): () => void;
    addMenuItem(item: EditorMenuItem): () => void;
    setStatusLine(text: string | null): void;
    setDisplayName(name: string | null): void;
    newScript(source?: string): Promise<boolean>;
    cursor(): EditorPosition;
    onDidChangeCursor(cb: (position: EditorPosition) => void): () => void;
    revealPosition(line: number, column?: number): void;
    setEditorOptions(options: EditorViewOptions): void;
    addAction(action: EditorAction): () => void;
    focus(): void;
    maximize(on?: boolean): void;
    maximized(): boolean;
    open(): void;
    close(): void;
    logs(): readonly EditorLogEntry[];
    log(message: string, severity?: EditorLogEntry['severity']): void;
    clearLogs(): void;
    onDidChangeCode(cb: (source: string) => void): () => void;
    onDidChangeLogs(cb: () => void): () => void;
}
MemberTypeDescription
getCode()() => stringThe current script. Before the editor first builds, the source it will seed with.
setCode()(source: string, opts?: { run?: boolean }) => Promise<boolean>Replace the script (draft and diagnostics follow): after the setBeforeReplaceDocument hook agrees. The target is untouched: pair it with bind when the code belongs to another indicator, or to none. run: true runs it right after. Resolves whether the document was replaced.
run()() => Promise<RunOutcome>Run the current script on the bound chart. The Run button's exact path: with a target, an in-place update of it (a no-op resolving upToDate: true when the code already matches); without one, a new instance that becomes the target.
remove()() => voidTake the target off the chart.
bind()(handleId: string | null) => booleanMake the indicator handleId on the bound chart the editor's target (what Run then updates in place) or clear it with null. False (target unchanged) when the chart has no Pine script indicator with that id: a native, or a script another engine runs. The code is not touched; see edit.
target()() => string | nullThe target's indicator id, or null.
onDidChangeTarget()(cb: (handleId: string | null) => void) => () => voidThe target changed (null = cleared). Returns an unsubscriber.
edit()(handleId: string) => Promise<boolean>Open an indicator's CURRENT code in the editor and make it the target: the legend's Edit code path, hook included. Resolves false when there is no such Pine script indicator or the hook kept the current document.
onDidStartRun()(cb: (event: { mode: RunMode }) => void) => () => voidA run or update started. Returns an unsubscriber.
onDidEndRun()(cb: (event: EditorRunEnd) => void) => () => voidA run or update finished. Returns an unsubscriber.
setDiagnostics()(diagnostics: readonly EditorDiagnostic[]) => voidShow HOST-found problems as markers and logs entries; [] clears them. They stay until the host replaces them or the document is replaced.
setBeforeReplaceDocument()(hook: BeforeReplaceDocumentHook | null) => voidAsk before the document is replaced: by New script, the legend's Edit code, a favorite, or setCode. One hook per editor; null removes it.
addHeaderButton()(button: EditorHeaderButton) => () => voidAdd (or replace, by id) a header button. Returns its remover.
addMenuItem()(item: EditorMenuItem) => () => voidAdd (or replace, by id) an entry in the header's ⋮ menu. Returns its remover.
setStatusLine()(text: string | null) => voidA host-owned status text at the end of the header; null clears it.
setDisplayName()(name: string | null) => voidShow this name in the header instead of the script's declared title; null restores it.
newScript()(source?: string) => Promise<boolean>Start a new document (source, or the default template) exactly as the New script button does: the replace hook is asked (reason 'new'), the target is released, and the previous code is one undo away. Resolves whether the document was replaced.
cursor()() => EditorPositionThe cursor position (1:1 before the editor first opens).
onDidChangeCursor()(cb: (position: EditorPosition) => void) => () => voidThe cursor moved. Returns an unsubscriber.
revealPosition()(line: number, column?: number) => voidMove the cursor to a position, scroll it into view and focus the editor.
setEditorOptions()(options: EditorViewOptions) => voidApply view settings; omitted keys keep their current value.
addAction()(action: EditorAction) => () => voidAdd (or replace, by id) a host command. Returns its remover.
focus()() => voidFocus the code.
maximize()(on?: boolean) => voidMaximize the panel over the charts (true), restore it (false), or flip it (no argument): the header button's action. Maximizing opens a closed panel.
maximized()() => booleanWhether the panel is maximized right now.
open()() => voidOpen the panel column (loads Monaco on first open).
close()() => void
logs()() => readonly EditorLogEntry[]The logs strip content: diagnostics (check/run) plus host entries.
log()(message: string, severity?: EditorLogEntry['severity']) => voidAppend a host entry to the logs strip.
clearLogs()() => voidClear the HOST entries (diagnostics manage themselves).
onDidChangeCode()(cb: (source: string) => void) => () => voidThe script changed: typing (debounced) or setCode. Returns an unsubscriber.
onDidChangeLogs()(cb: () => void) => () => voidThe logs strip changed. Returns an unsubscriber.

See also: BeforeReplaceDocumentHook, EditorAction, EditorDiagnostic, EditorHeaderButton, EditorLogEntry, EditorMenuItem, EditorPosition, EditorRunEnd, EditorViewOptions, RunMode, RunOutcome.

Diagnostic

A problem to show. Lines and columns are 1-based, like Monaco's.

Import from @luxalgo/vela-pro/editor.

interface Diagnostic {
    severity: DiagnosticSeverity;
    message: string;
    startLine: number;
    startColumn: number;
    endLine: number;
    endColumn: number;
    approximate?: boolean;
}
MemberTypeDescription
severityDiagnosticSeverity
messagestring
startLinenumber
startColumnnumber
endLinenumber
endColumnnumber
approximate?booleanTrue when the position is a best guess rather than reported by the engine.

See also: DiagnosticSeverity.

DiagnosticSeverity

Import from @luxalgo/vela-pro/editor.

type DiagnosticSeverity = 'error' | 'warning' | 'info';

EditorAction

A host command in the editor: a key binding while the editor has focus, and an entry in its command palette (F1).

Also exported from @luxalgo/vela-pro/editor.

interface EditorAction {
    id: string;
    label: string;
    keys?: string;
    run(): void;
}
MemberTypeDescription
idstringStable id: adding the same id again replaces the action.
labelstringPalette label.
keys?stringKey binding: modifiers then a key, +-joined ('mod+s', 'mod+shift+o', 'f2'). mod is Ctrl (Cmd on macOS); also ctrl, shift, alt. Keys: a letter, a digit, f1–f12, enter, escape, tab, space, backspace, delete, the arrows. Omitted: palette only.
run()() => void

EditorDiagnostic

A problem the HOST found in the script: shown as a marker in the code and a logs entry.

Also exported from @luxalgo/vela-pro/editor.

interface EditorDiagnostic {
    line: number;
    column?: number;
    endLine?: number;
    endColumn?: number;
    message: string;
    severity?: EditorLogEntry['severity'];
}
MemberTypeDescription
linenumber1-based.
column?number
endLine?number
endColumn?number
messagestring
severity?EditorLogEntry['severity']Default 'error'.

See also: EditorLogEntry.

EditorHeaderButton

A host button in the editor header, after the built-in ones.

Also exported from @luxalgo/vela-pro/editor.

interface EditorHeaderButton {
    id: string;
    icon: string;
    label: string;
    onClick(): void;
    order?: number;
}
MemberTypeDescription
idstringStable id: adding the same id again replaces the button.
iconstringIcon id from the vela/ui registry (registerIcon from @luxalgo/vela/plugin).
labelstringTooltip and accessible name.
onClick()() => void
order?numberSort key among the host buttons (ascending, default 0).

EditorLogEntry

One line of the logs strip.

Also exported from @luxalgo/vela-pro/editor.

interface EditorLogEntry {
    time: number;
    severity: 'info' | 'warning' | 'error';
    message: string;
    line?: number;
    column?: number;
    source: 'check' | 'run' | 'host';
}
MemberTypeDescription
timenumberEpoch ms. Diagnostics carry the time they were (re)computed.
severity'info' | 'warning' | 'error'
messagestring
line?number1-based position in the script, when the entry points at one.
column?number
source'check' | 'run' | 'host''check' = static diagnostic · 'run' = a run failure · 'host' = log() or setDiagnostics().

EditorMenuItem

A host entry in the header's ⋮ menu (the menu shows once it has an entry).

Also exported from @luxalgo/vela-pro/editor.

interface EditorMenuItem {
    id: string;
    label: string;
    onClick(): void;
    order?: number;
}
MemberTypeDescription
idstringStable id: adding the same id again replaces the entry.
labelstring
onClick()() => void
order?numberSort key (ascending, default 0).

EditorPosition

A position in the script, 1-based.

Also exported from @luxalgo/vela-pro/editor.

interface EditorPosition {
    line: number;
    column: number;
}

EditorRunEnd

A run or an update finished. error is null on success.

Also exported from @luxalgo/vela-pro/editor.

interface EditorRunEnd {
    mode: RunMode;
    ok: boolean;
    error: { message: string; method?: string } | null;
}

See also: RunMode.

EditorViewOptions

Editor view settings a host can expose (its own settings dialog).

Also exported from @luxalgo/vela-pro/editor.

interface EditorViewOptions {
    fontSize?: number;
    wordWrap?: boolean;
    minimap?: boolean;
    lineNumbers?: boolean;
}
MemberTypeDescription
fontSize?numberFont size in px (default 14).
wordWrap?booleanWrap long lines at the panel edge (default false).
minimap?booleanShow the minimap. Default: automatic (only on a panel wider than 600 px).
lineNumbers?booleanShow line numbers (default true).

PineDataset

Import from @luxalgo/vela-pro/editor.

interface PineDataset {
    version: PineVersion;
    root: PineData;
    functions: PineData;
    namespaces: Record<string, PineData>;
    support(path: string): PineSupport;
}

// Unexported supporting types referenced above
type PineData = Record<string, PineItem>;
type PineSupport = 'supported' | 'unsupported' | 'unknown';
MemberTypeDescription
versionPineVersion
rootPineDataGlobal scope: functions, variables, constants and types, merged.
functionsPineDataThe global FUNCTIONS alone: the reading of a call. root keeps one entry per name, and a name that is also a variable (time, na) resolves there to the variable.
namespacesRecord<string, PineData>Members by namespace name (the part before the dot).
support()(path: string) => PineSupportpath is 'ta.ema' or a bare global like 'plot'.

See also: PineItem, PineVersion.

PineEditorColors

Custom colours for the editor, one key per role the tokenizer distinguishes. Every key is optional: omitted roles keep the default palette. Passed as enableCodeEditor({ colors }) (or through enableVelaPro({ codeEditor: { colors } })).

Also exported from @luxalgo/vela-pro/editor.

interface PineEditorColors {
    background?: string;
    foreground?: string;
    comment?: TokenStyle;
    string?: TokenStyle;
    number?: TokenStyle;
    keyword?: TokenStyle;
    declaration?: TokenStyle;
    constant?: TokenStyle;
    builtin?: TokenStyle;
    type?: TokenStyle;
    function?: TokenStyle;
    parameter?: TokenStyle;
    identifier?: TokenStyle;
    operator?: TokenStyle;
    library?: TokenStyle;
    ui?: Record<string, string>;
}
MemberTypeDescription
background?stringThe editor's background: overrides the chart-theme surface the editor otherwise follows. A light value flips the whole base theme to light.
foreground?stringDefault text colour.
comment?TokenStyleComments.
string?TokenStyleString literals.
number?TokenStyleNumbers, hex colour literals included.
keyword?TokenStyleControl-flow keywords: if, for, and…
declaration?TokenStyleDeclaration keywords: var, varip, import, series…
constant?TokenStyleLanguage and library constants: true, na, color.red, plot.style_line…
builtin?TokenStyleThe chart's builtins: close, volume, bar_index, syminfo.tickerid…
type?TokenStyleType names: int, float, bool… and user-defined types.
function?TokenStyleFunction names: the standard library (plot(, ta.ema(, matched as whole dotted paths) and user functions/methods alike.
parameter?TokenStyleNamed-argument labels: overlay =, minval =.
identifier?TokenStyleUser variables and members.
operator?TokenStyleOperators and commas.
library?TokenStyleAn imported library's alias and the members reached through it: ta2.f(.
ui?Record<string, string>Raw Monaco UI colours, merged last: the escape hatch for everything beyond tokens ('editorCursor.foreground', 'editor.selectionBackground', …). Passed through to Monaco untouched.

See also: TokenStyle.

PineItem

Import from @luxalgo/vela-pro/editor.

interface PineItem {
    kind: PineKind;
    type?: string;
    description: string;
    signatures?: PineSignature[];
}

// Unexported supporting types referenced above
type PineKind = 'function' | 'variable' | 'constant' | 'type';
interface PineSignature {
    args: PineArgument[];
    returnType: string;
}
interface PineArgument {
    name: string;
    type: string;
    desc?: string;
    optional?: boolean;
}
MemberTypeDescription
kindPineKind
type?stringValue type for non-functions (series float, const string…).
descriptionstring
signatures?PineSignature[]Present for functions; absent otherwise.

PineVersion

The Pine language version a script is written against.

Import from @luxalgo/vela-pro/editor.

type PineVersion = 5 | 6;

ReplaceDocumentEvent

What a CodeEditorHandle.setBeforeReplaceDocument hook is asked about.

Also exported from @luxalgo/vela-pro/editor.

interface ReplaceDocumentEvent {
    reason: ReplaceDocumentReason;
    current: string;
    next: string;
}
MemberTypeDescription
reasonReplaceDocumentReason
currentstringThe code about to be replaced: the editor's live text.
nextstringThe code that would replace it.

See also: ReplaceDocumentReason.

ReplaceDocumentReason

Why the editor's document is about to be replaced.

Also exported from @luxalgo/vela-pro/editor.

type ReplaceDocumentReason = 'new' | 'edit-code' | 'set-code' | 'favorite';

RunMode

What a press of Run does: add a new instance, or update the target in place.

Also exported from @luxalgo/vela-pro/editor.

type RunMode = 'run' | 'update';

RunOutcome

What a Run produced. error.method is the Pine method that threw, when the engine named one.

Also exported from @luxalgo/vela-pro/editor.

interface RunOutcome {
    ok: boolean;
    mode: RunMode;
    title?: string;
    error?: { message: string; method?: string };
    upToDate?: boolean;
}
MemberTypeDescription
okboolean
modeRunMode
title?string
error?{ message: string; method?: string }
upToDate?booleanNothing ran: the editor already matched the target's code.

See also: RunMode.

TokenStyle

One token's style: a hex colour, or a colour with font styling.

Also exported from @luxalgo/vela-pro/editor.

type TokenStyle = string | { color?: string; italic?: boolean; bold?: boolean };

Constants

CODE_PANEL_ID

The panel id: also its button id and the key its width persists under.

Also exported from @luxalgo/vela-pro/editor.

const CODE_PANEL_ID: 'vela-pro.code';

DRAFT_KEY

Default key. Namespaced apart from vela-widget / vela-workspace.

Import from @luxalgo/vela-pro/editor.

const DRAFT_KEY: 'vela-pro-editor';

Re-exports

The following symbols are re-exported from the listed import path and documented on their primary reference page or in their upstream package.

ExportKindExported fromDocumented in
enableCodeEditorfunction@luxalgo/vela-pro/editorEnablers and options
EnableCodeEditorOptionsinterface@luxalgo/vela-pro/editorEnablers and options

On this page