Rhai Language Support for VS Code
VS Code extension dedicated to the Rhai scripting language, providing comprehensive syntax highlighting, file outline/structure, code formatting and snippets for optimal productivity.
🐛 Known Limitations
- Syntax highlighting is basic and could be improved
- Autocompletion is limited to snippets
- Code formatter is rudimentary
- Some third-party extensions may cause hover documentation to display twice — disable conflicting extensions to resolve the issue
⚙️ Recommended Configuration (VS Code native)
For Ctrl+Click to work as navigation (Go to Definition) instead of multi-cursor:
"editor.multiCursorModifier": "alt"
This allows:
- Ctrl+Click = Go to Definition
- Alt+Click = Multi-cursor
Author
jhenriot alias lemeran81
Features
🎨 Syntax Highlighting
Full Rhai syntax support:
- Keywords:
fn, const, let, if, else, for, in, while, switch, import, as, export, private, break, continue, return, throw, try, catch
- Types: integers, floats, hexadecimal, binary, octal numbers
- Operators:
and, or, not, is, is_empty, is_undefined
- Functions: definitions
fn name() and calls name()
- Objects: maps
#{}, closures |...| {}
- Strings: interpolation
${...} in double-quoted "" and template literals `...`
- Comments:
//, /* */, documentation /// and //!
- Constants:
true, false, ()
📋 Structure / Outline
The outline displays in the sidebar:
- Functions (
fn) — with name and parameters (e.g. create_weapon(name, description))
- Constants (
const) — in uppercase
- Imports (
import "module" as alias) — with alias and source module
- Regions (
// region: Name) — collapsible, with hierarchy
🔗 Go to Definition (Ctrl+Click)
Navigate quickly through your Rhai code, even across files:
- Ctrl+Click (or F12) on a function name → jumps to its definition
fn name()
- Ctrl+Click on a constant → jumps to its definition
const NAME
- Ctrl+Click on
module::function (e.g. p::get_equipment) → opens the imported file and jumps to the definition
- Ctrl+Click on an import alias (e.g.
p in import "character" as p;) → opens the module file
- Ctrl+Click on a used alias (e.g.
p:: in code) → opens the module file
- Ctrl+Click on a name not found in the current file → searches every
.rhai file of the workspace
- Supports imports via
import "file" as alias
- Module and definition lookups also search the workspace sub-directories (disable with
rhai.navigation.searchSubdirectories)
Example:
import "character" as p;
// Ctrl+Click on p → opens character.rhai
// Ctrl+Click on get_equipment → opens character.rhai at the definition
let equipment = p::get_equipment(character);
🔧 Host-Provided Functions
Functions registered by a host application (engine.register_fn, #[export_module], packages) do not exist in any .rhai file. The extension reads two artefacts generated by the host to document and navigate them:
| Artefact |
Default glob |
Used for |
api.json |
**/rhai-defs/api.json |
Hover (signatures, arguments, return type, doc comments) |
api.d.rhai |
**/rhai-defs/api.d.rhai |
Ctrl+Click / F12 (jumps to the declaration line) |
Hover on a host function shows a 🔧 card with every overload:
🔧 greet()
fn greet(name: string) -> string
**Arguments**
• `name` : Name of the person to greet.
**Returns**
A greeting message.
Resolution order — host documentation wins over the generic built-in card:
- Import alias (📦)
module::function (🟢)
- Function defined in the current file (🟢)
- Host-provided function (🔧)
- Generic built-in Rhai function (🔷)
Contract: api.json must expose functions[] entries with name, type, access, numParams and signature. Run Rhai: Validate host contract to list the artefacts, their modification date and any mismatch with api.d.rhai in the "Rhai" output channel. When several hosts provide the same function and arity, rhai.navigation.nativeApiPriority decides which one wins; rhai.host.regenerateCommand powers the regeneration command.
Script definitions always take precedence over host ones with the same name. Changes to the artefacts are picked up immediately (file watcher), no window reload needed.
Generating the artefacts (host side, metadata + internals features):
engine
.definitions()
.include_standard_packages(false)
.write_to_file("rhai-defs/api.d.rhai")?;
std::fs::write("rhai-defs/api.json", engine.gen_fn_metadata_to_json(false)?)?;
🎨 Semantic Highlighting
On top of the TextMate grammar (kept as a fallback), the extension classifies tokens semantically:
| Tokens |
Examples |
function |
fn alpha (declaration), alpha(), u::beta() |
variable / parameter |
let y, const LIMITE (readonly), fn f(x) |
property / namespace |
objet.cle, import "utils" as u |
keyword / operator |
fn, let, if, +, ??, :: |
string / number / comment |
literals, /// and //! docs |
Multi-line comments and template strings are split per line, as required by the protocol.
🗺️ Workspace Symbols, Folding and Selection
- Go to Symbol in Workspace (
Ctrl+T): every function and constant of the project, filterable by name
- Folding: blocks,
// region: / // endregion: sections and consecutive import groups
- Selection ranges (
Shift+Alt+→): expression → statement → block → function
🔎 References, Highlights and Rename
- Find All References (
Shift+F12) on a function, a constant or an alias::name access, across the whole workspace
- Document highlights: every occurrence of the symbol under the cursor is highlighted in the current file
- Rename (
F2) rewrites every occurrence, in every file, including alias::name accesses. Refused for keywords, host-provided functions and names declared more than once
✍️ Signature Help
While typing a call, ( and , open the parameter list: the current parameter is highlighted, nested calls are handled, and host overloads are picked by arity. Works for local functions, methods (value.len(), imported modules (u::compute() and host functions.
💡 Completion
| Context |
Suggestions |
| Identifier |
Functions and constants of the file, host native functions (with signature), keywords |
alias:: |
Public functions and constants of the imported module |
#{ |
Map keys already used in the file |
Nothing is suggested inside comments or strings. : is a trigger character, so u: opens the module list directly.
🩺 Diagnostics
The extension parses your scripts and reports problems as you type (300 ms debounce):
| Severity |
Checks |
| Error |
Unterminated string, unbalanced delimiters, import without alias, syntax errors |
| Warning |
Unused import, unused constant, unused variable, unreachable code |
| Info |
Empty loop block, TODO / FIXME markers |
Quick fixes are offered for unused imports, missing import aliases and unclosed delimiters. Disable everything with rhai.diagnostics.enable.
📖 Hover Documentation
Hover over a function to see its documentation instantly with rich display:
Native Rhai functions: 🔷
- Hover on
type_of(), print(), debug(), len(), etc.
- Colorful display with emoji and link to official documentation
User-defined functions (local and imported): 🟢
- Hover on a function displays its formatted
/// documentation
- Local functions: documentation extracted from the current file
- Imported functions:
module::function() opens the imported file and displays its doc
Imported modules: 📦
- Hover on an import alias (e.g.
p) displays the module's //! documentation
- Module documentation extracted from
//! comments at the top of the file
Smart formatting:
- 📌 Headers (
# Arguments, # Returns) in bold — 📌 skipped if header already contains an emoji
- • Bullets for parameter lists (
* and -)
`Inline code` preserved
- Code blocks (
\```) preserved as-is (no formatting inside)
- Bold (
**text**) preserved in documentation
- Original file structure preserved (blank lines, line breaks)
Example:
// In character.rhai:
/// Calculates character hit points
///
/// # Arguments
/// * `constitution` - Constitution value (8-18)
/// * `level` - Character level (1-20)
///
/// # Returns
/// Calculated hit points
fn calculate_hp(constitution, level) {
return constitution * 2 + level * 5
}
// In another file:
import "character" as p;
// Hovering p::calculate_hp() shows:
// 🟢 calculate_hp()
// Calculates character hit points
// ...
// 🔗 Imported from character
let hp = p::calculate_hp(12, 3);
🧩 Snippets
| Snippet |
Description |
fn |
Function with full RhaiDoc documentation |
const |
Constant declaration |
region |
Region markers with name |
import |
Module import with alias |
map |
Object map #{} |
closure |
Closure \|...\| {} |
for |
For loop |
if |
If/else condition |
Formats function signatures with one parameter per line:
Before:
fn create_weapon(name, description, impact_points) {
After (Shift+Alt+F):
fn create_weapon(
name,
description,
impact_points,
) {
Formatter rules:
- Each parameter on its own line with trailing comma
- Indentation respected (tabs or spaces per VS Code settings)
- Already well-formatted functions are not modified
- Functions without parameters remain
fn name() {
- Supports existing multi-line signatures
Configuration:
rhai.format.enable: Enable/disable the formatter (enabled by default)
rhai.inlayHints.enable: Show host function parameter names on calls (enabled by default)
Range formatting (Shift+Alt+F on a selection) and on-type formatting (on } and ;) re-indent blocks only — the output is idempotent and follows editor.insertSpaces / editor.tabSize.
rhai.navigation.searchSubdirectories: Search imported modules and definitions in workspace sub-directories (enabled by default)
🗂️ Language Configuration
- Comments:
// line, /* */ block
- Brackets:
{}, [], (), #{}
- Auto-closing: automatic character pairs
- Folding: regions
// region: / // endregion:
- Indentation: automatic on
{ and }
Installation
Method 1: Open VSX
The extension is published on Open VSX:
code --install-extension jhenriotaliaslemeran81.vscode-rhai-support
Or search for Rhai in the Extensions view (Ctrl+Shift+X) — works in VSCodium, Gitpod, Theia and any editor using the Open VSX registry.
Method 2: VSIX File
code --install-extension vscode-rhai-support-2026.4.9.vsix
Or via the UI:
- Open Extensions (Ctrl+Shift+X)
- Click
... (more actions)
- Install from VSIX...
- Select
vscode-rhai-support-2026.4.9.vsix
Method 3: Local Development
cd vscode-rhai
npm install
npm run compile
npm test # unit tests (node:test, no extra dependency)
# Press F5 to launch in VS Code
Usage
Automatic Highlighting
.rhai files are automatically recognized with dedicated syntax highlighting.
Outline
- Open a
.rhai file
- The structure appears in the Explorer sidebar → Outline section
- Click an element to navigate
Snippets
Start typing the snippet name, then Tab to insert:
fn [Tab] → Generates a function with documentation
Colored Code Example
//! Character management module
// region: Types
const WARRIOR_CLASS = #{
"name": "Warrior",
"base_hp": 10
};
// endregion: Types
/// Creates a new character
///
/// # Arguments
///
/// * `name` - Character name
/// * `class` - Class key
fn create_character(
name,
class,
) {
let char = #{
"name": name,
"class": WARRIOR_CLASS,
"inventory": []
};
for item in char.inventory {
if item.key == "sword" {
print("Sword found!");
}
}
char
}
import "utilities" as u;
Troubleshooting
The extension never updates in my editor. The extension is published on Open VSX. Some VS Code derivatives use their own curated gallery: if your editor only indexes its own catalogue, it will keep the installed version forever. Install the latest VSIX from the repository releases, or point your editor at the Open VSX gallery.
The extension is flagged as incompatible. Compare engines.vscode with your editor version (Help > About). The extension targets VS Code 1.126 or newer.
Host functions do not appear. Run Rhai: Validate host contract and read the "Rhai" output channel: it lists the artefacts found, their date and any mismatch between api.json and api.d.rhai.
The parameter hints popup is narrower than the hover. That popup is VS Code's own parameter-hints-widget: its width is capped, it cannot be resized, and no extension API can change it (see microsoft/vscode#124008, closed without implementation). The documentation it displays is byte-identical to the hover card. To align both, install Custom UI Style and add this setting, then restart the editor:
"custom-ui-style.stylesheet": {
".parameter-hints-widget .phwrapper": { "max-width": "900px !important" },
".parameter-hints-widget .docs": { "font-size": "var(--vscode-editor-font-size) !important" }
}
be5invis.vscode-custom-css is not published on Open VSX, so it cannot be installed from the default gallery of VS Code derivatives.
License
MIT — jhenriot alias lemeran81
Links