# Pine code editor (/vela-pro/indicators/pine/code-editor)



Vela Pro includes an integrated Pine Script® code editor panel where users can author scripts, run them on the active chart, and update live indicator instances in place. The editor is enabled by default when you call `enableVelaPro()`, and `codeEditor()` returns a programmatic controller handle for building custom save, history, and validation workflows. The example below adds a Save button and keyboard shortcut backed by an HTTP endpoint:

```ts
import { VelaWorkspace } from '@luxalgo/vela/workspace';
import { BinanceProvider } from '@luxalgo/vela/providers/binance';
import { registerIcon } from '@luxalgo/vela/plugin';
import { codeEditor, enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro({ codeEditor: { persist: false } }); // Persist scripts on the server rather than localStorage
registerIcon('acme-save', '<svg viewBox="0 0 16 16" width="1em" height="1em" fill="none" stroke="currentColor" stroke-width="1.3"><path d="M3 2.5h8l2 2v9H3z"/><path d="M5.5 2.5v4h5v-4"/></svg>');

const workspace = new VelaWorkspace('#chart', {
    layout: false,
    symbol: 'BTCUSDT',
    providers: { binance: () => new BinanceProvider() },
});

const editor = codeEditor(workspace);
if (editor) {
    let saved = await (await fetch('/api/scripts/current')).text();
    await editor.setCode(saved);

    const save = async (): Promise<void> => {
        const source = editor.getCode();
        editor.setStatusLine('Saving…');
        const response = await fetch('/api/scripts/current', { method: 'PUT', body: source });
        if (response.ok) saved = source;
        editor.setStatusLine(response.ok ? 'Saved' : `Not saved (HTTP ${response.status})`);
    };

    editor.addHeaderButton({ id: 'acme.save', icon: 'acme-save', label: 'Save', onClick: () => void save() });
    editor.addAction({ id: 'acme.save', label: 'Save script', keys: 'mod+s', run: () => void save() });
    editor.onDidChangeCode((source) => editor.setStatusLine(source === saved ? 'Saved' : 'Unsaved changes'));
    editor.setBeforeReplaceDocument(({ current }) => current === saved || window.confirm('Discard your unsaved changes?'));
}
```

The controller handle is available as soon as `VelaWorkspace` is constructed, and all handle methods work even while the panel is closed. To keep initial page loads fast, the editor loads lazily in two stages. First, the lightweight panel shell and Pine Script® language reference load when the panel is first opened or when a mutating handle method (such as `setCode` or `addHeaderButton`) is called. Second, the underlying text editor bundle loads only when the user actually opens the panel.

## Features [#features]

Users open the editor from the code button in the workspace sidebar rail or by clicking **Edit code** on any Pine Script® legend row. By default, the panel floats as an 800 px overlay on the right side of the workspace so the chart width does not shrink. Users can click the header pin to dock the panel as a layout column or click Maximize to expand it across the chart area.

The editor provides:

* Pine Script® syntax highlighting, autocomplete, hover documentation, signature help, and inline color swatches synchronized with the workspace's light or dark theme.
* Real-time static diagnostics as the user types, plus inline error markers when a script fails to compile or execute.
* A collapsible logs pane below the editor displaying diagnostics (with line and column numbers) alongside custom messages pushed via `editor.log()`. Failed runs automatically reopen the logs pane.
* A header favorites star synchronized with [Indicator menu](/vela-pro/indicators/library#favorites), plus a script switcher menu at the start of the header listing starred source snapshots.
* Automatic local draft persistence so unsaved edits survive browser reloads.

The editor maintains a single active document at a time. Selecting **New script** (or pressing `Ctrl`/`⌘` + `K`, then `I`) replaces the document with a starter template as a single undo step, so pressing `Ctrl`/`⌘` + `Z` restores the previous code.

### Running and updating scripts [#running-and-updating-scripts]

The editor tracks an optional *target* representing the mounted chart indicator bound to the current document:

1. **No target bound**: The primary header button reads **Run** (`Ctrl`/`⌘` + `Enter`). Clicking it executes the script and binds the newly added chart instance as the active target. If compilation or initial execution fails, no indicator row is left on the chart and the failure appears in the logs pane.
2. **Target bound**: The button reads **Update** and updates the bound indicator in place via `handle.updateCode()`, preserving its legend row, pane assignment, and input values. If the updated code fails, Vela rolls back so the previous version continues running.
3. **Up to date**: Whenever the editor buffer matches the bound target's active code, the **Update** button is disabled.

Clicking **Edit code** on a legend row loads that indicator's source and binds it as the target. Starting a new script, opening a favorite snapshot, removing the target indicator from the chart, or switching active charts in a multi-chart workspace releases the target binding so the next Run creates a new instance.

The editor exclusively supports Pine Script® (`pine` language key) and never opens or binds scripts executed by another engine; see [Custom runtimes](/vela-pro/indicators/runtimes/engines#code-editor-and-strategy-tester).

## Options [#options]

Pass configuration options via `enableVelaPro({ codeEditor: { ... } })`, or call `enableCodeEditor()` when enabling features individually. Pass `codeEditor: false` to disable the editor panel completely.

| Option                          | Default               | Description                                                                                                                                                       |
| ------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `overlay`                       | `true`                | Floats the panel over the chart with a header pin to dock it. Pass `false` to dock it permanently as a column without a pin.                                      |
| `width`, `minWidth`, `maxWidth` | `800`, `320`, `1100`  | Initial panel width in pixels and resize handle bounds.                                                                                                           |
| `maximizable`                   | `true`                | Displays the Maximize toggle button in the panel header.                                                                                                          |
| `persist`                       | `true`                | Persists the active draft across reloads. Pass a string to customize the storage key (defaults to `'vela-pro-editor'`) or `false` to disable draft persistence.   |
| `storage`                       | `localStorage`        | Custom key-value storage adapter (`get(key)` and `set(key, value)`, synchronous or asynchronous), matching the workspace `storage` contract.                      |
| `initialSource`                 | Built-in EMA template | Starter Pine Script® code shown when opening a fresh editor with no saved draft.                                                                                  |
| `diagnostics`                   | `true`                | Enables built-in static analysis and runtime error markers. Custom diagnostics pushed via `setDiagnostics()` still display when `false`.                          |
| `legendAction`                  | `true`                | Displays the **Edit code** button on Pine Script® indicator legend rows.                                                                                          |
| `colors`                        | `undefined`           | Custom syntax token and editor UI colors; see [Syntax and UI colors](#syntax-and-ui-colors).                                                                      |
| `order`                         | `30`                  | Sort order of the editor icon in the workspace sidebar rail.                                                                                                      |
| `workerUrl`                     | `undefined`           | External URL used to spawn the editor's language worker instead of a Blob URL, for environments with a strict Content-Security-Policy lacking `worker-src blob:`. |

Draft persistence saves only the text inside the editor buffer, not the indicators mounted on the chart; see [Indicator persistence](/vela-pro/persistence/stores/indicators).

### Syntax and UI colors [#syntax-and-ui-colors]

The `colors` option accepts per-token overrides for `comment`, `string`, `number`, `keyword`, `declaration`, `constant`, `builtin`, `type`, `function`, `parameter`, `identifier`, `operator`, and `library`. Each key accepts either a hex color string or a `{ color, bold, italic }` style object. In addition, `background` and `foreground` override the editor surface and base text colors, while `ui` forwards raw theme keys for editor chrome such as the cursor or selection highlight:

```ts
import { enableVelaPro } from '@luxalgo/vela-pro';

enableVelaPro({
    codeEditor: {
        colors: {
            keyword: '#c586c0',
            function: { color: '#dcdcaa', bold: true },
            ui: { 'editorCursor.foreground': '#ffcc00' },
        },
    },
});
```

Any omitted token key retains its built-in theme default. Setting an explicit `background` locks the editor surface to that color instead of switching automatically between light and dark workspace themes.

## Programmatic control [#programmatic-control]

`codeEditor(workspace)` returns the controller handle for that workspace's editor, or `null` if the code editor is disabled. When only a single workspace exists on the page, `codeEditor()` can be called with no arguments; if multiple workspaces are mounted, calling `codeEditor()` without an explicit workspace throws an error. Method calls made before the panel finishes mounting are queued and replayed in call order.

| Capability           | Handle methods                                                                                               | Typical integration                                                                                                                                                       |
| -------------------- | ------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Document buffer      | `getCode()`, `setCode(source, { run })`, `newScript(source?)`, `onDidChangeCode(cb)`                         | Load scripts from your backend, read buffer contents, and track edits.                                                                                                    |
| Unsaved-change guard | `setBeforeReplaceDocument(hook)`                                                                             | Prompt before New script, Edit code, favorite selection, or `setCode()` overwrites unsaved edits; return `false` to cancel.                                               |
| Target binding       | `target()`, `bind(id)`, `edit(id)`, `remove()`, `onDidChangeTarget(cb)`                                      | Associate a saved script record with its live chart instance. `bind(id)` sets the target without changing editor text, while `edit(id)` also loads that indicator's code. |
| Execution lifecycle  | `run()`, `onDidStartRun(cb)`, `onDidEndRun(cb)`                                                              | Record version history or audit logs; run events report `mode` (`'run'` or `'update'`), `ok`, and `error`.                                                                |
| Diagnostics and logs | `setDiagnostics(list)`, `log(message, severity?)`, `logs()`, `clearLogs()`, `onDidChangeLogs(cb)`            | Surface custom linter or server-side validation messages in the editor margin and logs strip.                                                                             |
| Header extensions    | `addHeaderButton(button)`, `addMenuItem(item)`, `setStatusLine(text)`, `setDisplayName(name)`                | Add toolbar actions, overflow menu items (`⋮`), save-state text, and custom script titles.                                                                                |
| Cursor and viewport  | `cursor()`, `onDidChangeCursor(cb)`, `revealPosition(line, column?)`, `setEditorOptions(options)`, `focus()` | Jump to error locations, display cursor coordinates, and configure font size, word wrap, minimap, or line numbers.                                                        |
| Keyboard commands    | `addAction({ id, label, keys, run })`                                                                        | Register editor-scoped keybindings that also appear in the command palette (`F1`).                                                                                        |
| Panel visibility     | `open()`, `close()`, `maximize(on?)`, `maximized()`                                                          | Open, close, or maximize the editor from external UI controls.                                                                                                            |

Every `add*` method returns a cleanup function that removes the registered item, and every `onDid*` listener returns an unsubscribe function. Registering a button, menu item, or action with an existing `id` replaces the previous entry in place.

`run()` mirrors the header Run/Update button and never rejects. It resolves to `{ ok, mode, title, error, upToDate }`, where `upToDate: true` indicates execution was skipped because the buffer already matched the target indicator's code.

`bind(id)` and `edit(id)` return `false` when given an indicator ID that the editor cannot manage (such as a native indicator or a script running on a custom engine).

The example below runs server-side static analysis after every successful script run and jumps to the first reported issue:

```ts
import { codeEditor, type EditorDiagnostic } from '@luxalgo/vela-pro';

declare function reviewOnServer(source: string): Promise<EditorDiagnostic[]>;

const editor = codeEditor();
if (editor) {
    editor.onDidEndRun(async ({ ok }) => {
        if (!ok) return;
        const problems = await reviewOnServer(editor.getCode());
        editor.setDiagnostics(problems); // Passing [] clears previous diagnostics
        const first = problems[0];
        if (first) editor.revealPosition(first.line, first.column);
    });
}
```

For complete method and type definitions, see [Code editor](/vela-pro/api/code-editor) in the API reference.

## Related [#related]

* [Pine Script® with PineTS](/vela-pro/indicators/pine/runtime)
* [Indicator menu](/vela-pro/indicators/library)
* [Strategy tester](/vela-pro/indicators/backtesting/strategy-tester)
