docs: baked a lot of API docs

This commit is contained in:
Zef Hemel
2026-08-06 14:48:21 +02:00
parent 9b4de31ca3
commit 754e8525b9
36 changed files with 4888 additions and 49 deletions
+67 -1
View File
@@ -8,4 +8,70 @@ references:
The Asset API provides functions for reading and managing assets embedded in plugs.
${spacelua.renderApiDocumentation("asset")}
<!--#lua spacelua.renderApiDocumentation("asset") -->
## asset.getFileMeta
`asset.getFileMeta(plugName, name)`
Gets metadata for an asset embedded in a plug.
**Parameters:**
- `plugName` (`string`) — Plug name.
- `name` (`string`) — Asset path.
**Returns:**
- `table` — File metadata.
**Example:**
```lua
local meta = asset.getFileMeta("myplug", "data.txt")
print(meta.lastModified)
```
## asset.listFiles
`asset.listFiles(plugName)`
Lists the assets embedded in a plug.
**Parameters:**
- `plugName` (`string`) — Plug name.
**Returns:**
- `table` — List of file metadata.
**Example:**
```lua
for _, file in ipairs(asset.listFiles("myplug")) do
print(file.name)
end
```
## asset.readAsset
`asset.readAsset(plugName, name)`
Reads an asset embedded in a plug as a data URL.
**Parameters:**
- `plugName` (`string`) — Plug name.
- `name` (`string`) — Asset path.
**Returns:**
- `string` — Asset data URL.
**Example:**
```lua
local image = asset.readAsset("myplug", "image.png")
```
<!--/lua-->
+55 -1
View File
@@ -7,4 +7,58 @@ references:
The Client Store API provides a simple key-value store for client-specific states and preferences.
${spacelua.renderApiDocumentation("clientStore")}
<!--#lua spacelua.renderApiDocumentation("clientStore") -->
## clientStore.delete
`clientStore.delete(key)`
Deletes a client-specific value from the local key-value store.
**Parameters:**
- `key` (`string`) — Key to delete.
**Example:**
```lua
clientStore.delete("theme")
```
## clientStore.get
`clientStore.get(key)`
Gets a client-specific value from the local key-value store.
**Parameters:**
- `key` (`string`) — Key to read.
**Returns:**
- Value — Stored value, or nil when absent.
**Example:**
```lua
local theme = clientStore.get("theme")
```
## clientStore.set
`clientStore.set(key, value)`
Stores a client-specific value in the local key-value store.
**Parameters:**
- `key` (`string`) — Key to set.
- `value` — Value to store.
**Example:**
```lua
clientStore.set("theme", "dark")
```
<!--/lua-->
+38 -1
View File
@@ -9,4 +9,41 @@ references:
The Code Widget API provides functions for managing code widgets in the editor.
${spacelua.renderApiDocumentation("codeWidget")}
<!--#lua spacelua.renderApiDocumentation("codeWidget") -->
## codeWidget.define
`codeWidget.define(def)`
**Parameters:**
- `def`
## codeWidget.refreshAll
`codeWidget.refreshAll()`
Refreshes all code widgets on the current page that support refreshing.
**Example:**
```lua
codeWidget.refreshAll()
```
## codeWidget.render
`codeWidget.render(language, body, pageName)`
Renders code through the widget registered for a language.
**Parameters:**
- `language` (`string`) — Widget language.
- `body` (`string`) — Code block body.
- `pageName` (`string`) — Containing page name.
**Returns:**
- `table` — Rendered widget content, or nil.
<!--/lua-->
+154 -1
View File
@@ -9,7 +9,159 @@ references:
The Config API provides functions for managing configuration values, defining their JSON schemas, and exposing them in the [[Configuration Manager]] UI.
${spacelua.renderApiDocumentation("config")}
<!--#lua spacelua.renderApiDocumentation("config") -->
## config.define
`config.define(key, schema)`
Defines a JSON schema for a configuration key.
**Parameters:**
- `key` (`string`) — Configuration key.
- `schema` (`table`) — JSON Schema definition; default applies a missing value and ui annotations expose it in the Configuration Manager.
**Example:**
```lua
config.define("shortWikiLinks", {
description = "Render short wiki link labels",
type = "boolean",
default = true,
ui = {category = "Editor", label = "Short wiki links", priority = 1},
})
```
## config.defineCategory
`config.defineCategory(definition)`
Defines or updates a Configuration Manager UI category.
**Parameters:**
- `definition` (`table`) — Category name, description, and priority.
**Example:**
```lua
config.defineCategory {
name = "Editor",
description = "Page editor behavior.",
priority = 50,
}
```
## config.get
`config.get(path, defaultValue)`
Gets a configuration value by path, with dot notation support.
**Parameters:**
- `path` (`string`) — Configuration path.
- `defaultValue` — Value returned when the path is absent.
**Returns:**
- Value — Configured value or the supplied default.
**Example:**
```lua
local theme = config.get("theme", "light")
```
## config.getCategories
`config.getCategories()`
Gets all Configuration Manager UI categories.
**Returns:**
- `table` — Category definitions keyed by name.
## config.getSchemas
`config.getSchemas()`
Gets all defined configuration schemas.
**Returns:**
- `table` — Schemas keyed by configuration path.
## config.getValues
`config.getValues()`
Gets all configuration values as a single table.
**Returns:**
- `table` — All configuration values.
## config.has
`config.has(path)`
Checks whether a configuration path exists.
**Parameters:**
- `path` (`string`) — Configuration path.
**Returns:**
- `boolean` — Whether the path exists.
## config.insert
`config.insert(path, value)`
Appends a value to the configuration array at a path.
**Parameters:**
- `path` — Configuration path.
- `value` — Value to append.
## config.set
`config.set(path, value)`
`config.set(values)`
Sets one configuration value or multiple values at once.
**Parameters:**
- `pathOrValues` — Configuration path or table of values.
- `value?` — Value to set when a path is supplied.
**Examples:**
```lua
config.set("theme", "dark")
```
```lua
config.set({theme = "dark", fontSize = 14})
```
## config.setLuaValue
`config.setLuaValue(path, value)`
`config.setLuaValue(values)`
Sets configuration while preserving the supplied Lua value representation.
**Parameters:**
- `pathOrValues` — Configuration path or table of values.
- `value?` — Lua value to preserve.
<!--/lua-->
## Configuration Manager guide
@@ -42,3 +194,4 @@ Nested schemas can carry their own `ui` annotations. When a parent object's chil
### Categories
Registered categories appear in descending `priority`, with higher values first. A category's optional `description` appears at the top of the category. Categories referenced by a schema but never registered appear after registered categories in alphabetical order.
+140 -1
View File
@@ -11,4 +11,143 @@ The Datastore API provides functions for interacting with a key-value store that
* **Keys** are represented as a list (Lua table) of strings.
* **Values** can be any persistable value.
${spacelua.renderApiDocumentation("datastore")}
<!--#lua spacelua.renderApiDocumentation("datastore") -->
## datastore.batchDelete
`datastore.batchDelete(keys)`
Deletes multiple values from the key-value store.
**Parameters:**
- `keys` (`table`) — List of keys to delete.
**Example:**
```lua
datastore.batchDelete({{"user", "1"}, {"user", "2"}})
```
## datastore.batchGet
`datastore.batchGet(keys)`
Gets multiple values from the key-value store.
**Parameters:**
- `keys` (`table`) — List of keys to read.
**Returns:**
- `table` — Values in key order, with nil for missing keys.
**Example:**
```lua
local values = datastore.batchGet({{"user", "1"}, {"user", "2"}})
```
## datastore.batchSet
`datastore.batchSet(entries)`
Sets multiple key-value entries in one operation.
**Parameters:**
- `entries` (`table`) — Entries with key and value fields.
**Example:**
```lua
datastore.batchSet({
{key = {"user", "1"}, value = {name = "Alice"}},
{key = {"user", "2"}, value = {name = "Bob"}},
})
```
## datastore.delete
`datastore.delete(key)`
Deletes a value from the key-value store.
**Parameters:**
- `key` (`table`) — Key segments.
**Example:**
```lua
datastore.delete({"user", "123"})
```
## datastore.get
`datastore.get(key)`
Gets a value from the key-value store.
**Parameters:**
- `key` (`table`) — Key segments.
**Returns:**
- Value — Stored value, or nil when absent.
**Example:**
```lua
local user = datastore.get({"user", "123"})
```
## datastore.query
`datastore.query(options)`
Queries key-value entries, optionally restricted to a key prefix.
**Parameters:**
- `options` (`table`) — Query options, including an optional prefix.
**Returns:**
- `table` — Matching key-value entries.
## datastore.queryLua
`datastore.queryLua(prefix, query, scopeVariables?)`
Runs a Space Lua collection query over a key prefix.
**Parameters:**
- `prefix` (`table`) — Key prefix to query.
- `query` (`table`) — Parsed collection query.
- `scopeVariables?` (`table`) — Additional variables available to the query.
**Returns:**
- `table` — Query results converted to Lua values.
## datastore.set
`datastore.set(key, value)`
Sets a value in the key-value store.
**Parameters:**
- `key` (`table`) — Key segments.
- `value` — Value to store.
**Example:**
```lua
datastore.set({"user", "123"}, {name = "John"})
```
<!--/lua-->
+1 -1
View File
@@ -66,4 +66,4 @@ Would be roughly equivalent to the following HTML:
</span>
```
This API is implemented using Lua metatables, its implementation lives here: [[^Library/Std/APIs/DOM]]
This API is implemented using Lua metatables, its implementation lives here: [[^Library/Std/APIs/DOM]]
+891 -1
View File
@@ -9,4 +9,894 @@ references:
The Editor API provides functions for interacting with the editor interface.
${spacelua.renderApiDocumentation("editor")}
<!--#lua spacelua.renderApiDocumentation("editor") -->
## editor.acceptCompletion
`editor.acceptCompletion()`
Accepts the currently selected completion when the completion popup is active.
**Returns:**
- `boolean` — Whether an active completion was accepted.
## editor.alert
`editor.alert(message)`
Shows a browser alert dialog.
**Parameters:**
- `message` (`string`) — The alert message.
## editor.closeCompletion
`editor.closeCompletion()`
Closes the active editor completion popup.
## editor.configureVimMode
`editor.configureVimMode()`
Configures CodeMirror Vim mode from the current SilverBullet Vim settings.
## editor.confirm
`editor.confirm(message, options?)`
Prompts the user to confirm or cancel an action.
**Parameters:**
- `message` (`string`) — The confirmation message.
- `options?` (`{ destructive?: boolean }`) — Optional dialog styling settings.
**Returns:**
- `boolean` — Whether the user confirmed.
## editor.copyToClipboard
`editor.copyToClipboard(data)`
Copies text or binary Blob data to the system clipboard. Clipboard access requires a secure HTTPS context.
**Parameters:**
- `data` (`string | Blob`) — The text or Blob to copy.
**Example:**
```lua
editor.copyToClipboard("Copied text")
```
## editor.cursorCharLeft
`editor.cursorCharLeft()`
Moves the cursor one character left, respecting bidirectional text.
## editor.cursorCharRight
`editor.cursorCharRight()`
Moves the cursor one character right, respecting bidirectional text.
## editor.cursorDocEnd
`editor.cursorDocEnd()`
Moves the cursor to the end of the document.
## editor.cursorDocStart
`editor.cursorDocStart()`
Moves the cursor to the start of the document.
## editor.cursorGroupLeft
`editor.cursorGroupLeft()`
Moves the cursor left by one character group or word.
## editor.cursorGroupRight
`editor.cursorGroupRight()`
Moves the cursor right by one character group or word.
## editor.cursorLineBoundaryLeft
`editor.cursorLineBoundaryLeft()`
Moves the cursor to the left visual boundary of the current line.
## editor.cursorLineBoundaryRight
`editor.cursorLineBoundaryRight()`
Moves the cursor to the right visual boundary of the current line.
## editor.cursorLineDown
`editor.cursorLineDown()`
Moves completion selection down when open, otherwise moves the cursor down one visual line.
## editor.cursorLineEnd
`editor.cursorLineEnd()`
Moves the cursor to the end of the current logical line.
## editor.cursorLineStart
`editor.cursorLineStart()`
Moves the cursor to the start of the current logical line.
## editor.cursorLineUp
`editor.cursorLineUp()`
Moves completion selection up when open, otherwise moves the cursor up one visual line.
## editor.cursorPageDown
`editor.cursorPageDown()`
Moves completion selection down one page when open, otherwise moves the cursor down one viewport page.
## editor.cursorPageUp
`editor.cursorPageUp()`
Moves completion selection up one page when open, otherwise moves the cursor up one viewport page.
## editor.deleteCharBackward
`editor.deleteCharBackward()`
Deletes the selection or the character before the cursor.
## editor.deleteCharForward
`editor.deleteCharForward()`
Deletes the selection or the character after the cursor.
## editor.deleteGroupBackward
`editor.deleteGroupBackward()`
Deletes the selection or the character group before the cursor.
## editor.deleteGroupForward
`editor.deleteGroupForward()`
Deletes the selection or the character group after the cursor.
## editor.deleteLine
`editor.deleteLine()`
Deletes the current line or the lines touched by the selection.
## editor.deleteLineBoundaryBackward
`editor.deleteLineBoundaryBackward()`
Deletes the selection or text back to the current line boundary.
## editor.deleteLineBoundaryForward
`editor.deleteLineBoundaryForward()`
Deletes the selection or text forward to the current line boundary.
## editor.dispatch
`editor.dispatch(change)`
Dispatches a CodeMirror transaction to the editor view.
**Parameters:**
- `change` (`Transaction`) — The CodeMirror transaction to dispatch.
## editor.downloadFile
`editor.downloadFile(filename, dataUrl)`
Triggers a browser download of a data URL under the given filename.
**Parameters:**
- `filename` (`string`) — The downloaded filename.
- `dataUrl` (`string`) — The data URL to download.
**Example:**
```lua
editor.downloadFile("test.txt", "data:text/plain;base64,SGVsbG8=")
```
## editor.filterBox
`editor.filterBox(label, options, helpText?, placeHolder?)`
Shows a filterable option picker similar to the page navigator.
**Parameters:**
- `label` (`string`) — The label shown beside the filter input.
- `options` (`FilterOption[]`) — The available options.
- `helpText?` (`string`) — Help text shown below the picker.
- `placeHolder?` (`string`) — Placeholder text for the filter input.
**Returns:**
- `FilterOption | undefined` — The selected option, or undefined if dismissed.
**Example:**
```lua
local result = editor.filterBox("Select:", {
{name = "Option 1", value = "1"},
{name = "Option 2", value = "2", description = "More details"}
})
```
## editor.flashNotification
`editor.flashNotification(message, type?, options?)`
Shows a flash notification in the editor UI.
**Parameters:**
- `message` (`string`) — The message to display.
- `type?` (`NotificationType`) — The notification severity: "info", "error", or "warning".
- `options?` (`{ timeout?: number; actions?: NotificationAction[] }`) — Optional timeout and action buttons. A timeout of 0 keeps the notification visible until dismissed.
**Example:**
```lua
editor.flashNotification("Update available", "warning", {
timeout = 0,
actions = {{
name = "Reload",
run = function() editor.reloadUI() end
}}
})
```
## editor.focus
`editor.focus()`
Returns focus to the main editor.
## editor.fold
`editor.fold()`
Folds the code or markup region at the cursor.
## editor.foldAll
`editor.foldAll()`
Folds all foldable regions in the editor.
## editor.forceLint
`editor.forceLint()`
Forces editor linting to run, including when the content has not changed.
## editor.getCurrentEditor
`editor.getCurrentEditor()`
Returns the name of the currently active editor implementation.
**Returns:**
- `string` — The editor name, or `page` for the page editor.
## editor.getCurrentLine
`editor.getCurrentLine()`
Returns the current line's range and text, including a `|^|` cursor marker variant.
**Returns:**
- `{ from: number; to: number; text: string; textWithCursor: string }` — The line containing the main selection head.
## editor.getCurrentPage
`editor.getCurrentPage()`
Returns the name of the page or document currently open in the editor.
**Returns:**
- `string` — The current page name.
## editor.getCurrentPageMeta
`editor.getCurrentPageMeta()`
Returns metadata for the page or document currently open in the editor.
**Returns:**
- `PageMeta | undefined` — The current page metadata, if indexed.
## editor.getCurrentPath
`editor.getCurrentPath()`
Returns the path of the page or document currently open in the editor.
**Returns:**
- `string` — The current page path.
## editor.getCursor
`editor.getCursor()`
Returns the cursor position as a character offset from the start of the document.
**Returns:**
- `number` — The cursor offset.
## editor.getRecentlyOpenedPages
`editor.getRecentlyOpenedPages()`
Returns page metadata ordered from most to least recently opened.
**Returns:**
- `PageMeta[]` — Recently opened pages.
## editor.getSelection
`editor.getSelection()`
Returns the current selection range and selected text.
**Returns:**
- `{ from: number; to: number; text: string }` — The main editor selection.
## editor.getText
`editor.getText()`
Returns the full text of the currently open page or document.
**Returns:**
- `string` — The editor contents.
## editor.getUiOption
`editor.getUiOption(key)`
Returns the current value of an editor UI option.
**Parameters:**
- `key` (`string`) — The UI option key.
**Returns:**
- `any` — The option value.
## editor.goHistory
`editor.goHistory(delta)`
Moves backward or forward through browser history.
**Parameters:**
- `delta` (`number`) — The relative history offset; negative moves backward and positive moves forward.
## editor.hidePanel
`editor.hidePanel(id)`
Hides the panel at a specified editor UI location.
**Parameters:**
- `id` (`string`) — The panel location identifier.
## editor.indentLess
`editor.indentLess()`
Decreases indentation for the current line or selection.
## editor.indentMore
`editor.indentMore()`
Increases indentation for the current line or selection.
## editor.insertAtCursor
`editor.insertAtCursor(text, scrollIntoView?, cursorPlaceHolder?)`
Inserts text at the cursor and moves the cursor after it or to an optional `|^|` marker.
**Parameters:**
- `text` (`string`) — The text to insert.
- `scrollIntoView?` (`boolean`) — Whether to scroll the new cursor position into view.
- `cursorPlaceHolder?` (`boolean`) — Whether to remove `|^|` and move the cursor to its position.
## editor.insertAtPos
`editor.insertAtPos(text, pos, cursorPlaceHolder?)`
Inserts text at a character offset, optionally placing the cursor at a `|^|` marker.
**Parameters:**
- `text` (`string`) — The text to insert.
- `pos` (`number`) — The character offset at which to insert.
- `cursorPlaceHolder?` (`boolean`) — Whether to remove `|^|` and move the cursor to its position.
## editor.insertNewline
`editor.insertNewline()`
Accepts the active completion, or inserts a newline with appropriate indentation.
## editor.invokeCommand
`editor.invokeCommand(name, args?)`
Invokes a client command by name.
**Parameters:**
- `name` (`string`) — The command name.
- `args?` (`string[]`) — Arguments passed to the command.
## editor.isMobile
`editor.isMobile()`
Checks whether the current device lacks a fine pointer and should be treated as mobile.
**Returns:**
- `boolean` — Whether the editor is running in a mobile-style pointer environment.
## editor.moveCursor
`editor.moveCursor(pos, center?)`
Moves and focuses the cursor at a character offset, scrolling it into view.
**Parameters:**
- `pos` (`number`) — The character offset to move to.
- `center?` (`boolean`) — Whether to vertically center the cursor.
## editor.moveCursorToLine
`editor.moveCursorToLine(line, column?, center?)`
Moves the cursor to a one-based line and column, clamping the column to the line length.
**Parameters:**
- `line` (`number`) — The one-based line number.
- `column?` (`number`) — The one-based column number.
- `center?` (`boolean`) — Whether to vertically center the cursor.
## editor.moveLineDown
`editor.moveLineDown()`
Moves the current line or selected lines downward.
## editor.moveLineUp
`editor.moveLineUp()`
Moves the current line or selected lines upward.
## editor.navigate
`editor.navigate(ref, replaceState?, newWindow?)`
Navigates to a page reference without restoring its remembered cursor and scroll position.
**Parameters:**
- `ref` (`Ref | string`) — The page reference to navigate to.
- `replaceState?` (`boolean`) — Whether to replace the current browser history state.
- `newWindow?` (`boolean`) — Whether to open the reference in a new window.
**Example:**
```lua
editor.navigate("CHANGELOG@123")
```
## editor.newWindow
`editor.newWindow()`
Opens the current SilverBullet URL in a new browser window.
## editor.open
`editor.open(ref, replaceState?, newWindow?)`
Opens a page reference and restores its remembered cursor and scroll position when possible.
**Parameters:**
- `ref` (`Ref | string`) — The page reference to open.
- `replaceState?` (`boolean`) — Whether to replace the current browser history state.
- `newWindow?` (`boolean`) — Whether to open the reference in a new window.
**Example:**
```lua
editor.open("CHANGELOG")
```
## editor.openCommandPalette
`editor.openCommandPalette()`
Opens the command palette.
## editor.openPageNavigator
`editor.openPageNavigator(mode?)`
Opens the page navigator in the requested browsing mode.
**Parameters:**
- `mode?` (`page | meta | document | all`) — The navigator mode.
## editor.openSearchPanel
`editor.openSearchPanel()`
Opens the editor's native search panel.
## editor.openUrl
`editor.openUrl(url, existingWindow?)`
Opens a URL in the browser.
**Parameters:**
- `url` (`string`) — The URL to open.
- `existingWindow?` (`boolean`) — Whether to reuse an existing window.
## editor.prompt
`editor.prompt(message, defaultValue?)`
Prompts the user for text input.
**Parameters:**
- `message` (`string`) — The prompt message.
- `defaultValue?` (`string`) — The initial input value.
**Returns:**
- `string | undefined` — The entered text, or undefined if dismissed.
## editor.rebuildEditorState
`editor.rebuildEditorState()`
Rebuilds the CodeMirror editor state from the current client configuration.
## editor.redo
`editor.redo()`
Redoes the most recently undone editor change.
## editor.reloadConfigAndCommands
`editor.reloadConfigAndCommands()`
Reloads space scripts and styles, then rebuilds the editor state.
## editor.reloadPage
`editor.reloadPage()`
Force reloads the current page in the editor.
## editor.reloadUI
`editor.reloadUI()`
Force reloads the browser UI.
## editor.replaceRange
`editor.replaceRange(from, to, text, cursorPlaceHolder?)`
Replaces a text range, optionally placing the cursor at a `|^|` marker in the replacement.
**Parameters:**
- `from` (`number`) — The start offset of the range.
- `to` (`number`) — The end offset of the range.
- `text` (`string`) — The replacement text.
- `cursorPlaceHolder?` (`boolean`) — Whether to remove `|^|` and move the cursor to its position.
## editor.save
`editor.save()`
Forces the current page or document to be saved.
## editor.selectAll
`editor.selectAll()`
Selects the entire editor document.
## editor.selectCharLeft
`editor.selectCharLeft()`
Extends the selection one character left, respecting bidirectional text.
## editor.selectCharRight
`editor.selectCharRight()`
Extends the selection one character right, respecting bidirectional text.
## editor.selectDocEnd
`editor.selectDocEnd()`
Extends the selection to the end of the document.
## editor.selectDocStart
`editor.selectDocStart()`
Extends the selection to the start of the document.
## editor.selectGroupLeft
`editor.selectGroupLeft()`
Extends the selection left by one character group or word.
## editor.selectGroupRight
`editor.selectGroupRight()`
Extends the selection right by one character group or word.
## editor.selectLineBoundaryLeft
`editor.selectLineBoundaryLeft()`
Extends the selection to the left visual boundary of the current line.
## editor.selectLineBoundaryRight
`editor.selectLineBoundaryRight()`
Extends the selection to the right visual boundary of the current line.
## editor.selectLineDown
`editor.selectLineDown()`
Extends the selection downward by one visual line.
## editor.selectLineEnd
`editor.selectLineEnd()`
Extends the selection to the end of the current logical line.
## editor.selectLineStart
`editor.selectLineStart()`
Extends the selection to the start of the current logical line.
## editor.selectLineUp
`editor.selectLineUp()`
Extends the selection upward by one visual line.
## editor.selectPageDown
`editor.selectPageDown()`
Extends the selection downward by one viewport page.
## editor.selectPageUp
`editor.selectPageUp()`
Extends the selection upward by one viewport page.
## editor.sendMessage
`editor.sendMessage(type, data?)`
Sends a public message to the active document editor, if one is open.
**Parameters:**
- `type` (`string`) — The message type.
- `data?` (`any`) — Data attached to the message.
## editor.setSelection
`editor.setSelection(from, to)`
Sets the main editor selection to a character range.
**Parameters:**
- `from` (`number`) — The selection anchor offset.
- `to` (`number`) — The selection head offset.
## editor.setText
`editor.setText(newText, shouldIsolateHistory?)`
Updates the editor text with a minimal diff while preserving the cursor when possible.
**Parameters:**
- `newText` (`string`) — The complete replacement text.
- `shouldIsolateHistory?` (`boolean`) — Whether to isolate the change in undo history.
## editor.setUiOption
`editor.setUiOption(key, value)`
Sets an editor UI option and reloads the editor.
**Parameters:**
- `key` (`string`) — The UI option key.
- `value` (`any`) — The option value.
## editor.showPanel
`editor.showPanel(id, mode, html, script)`
Shows an HTML panel in a specified editor UI location.
**Parameters:**
- `id` (`string`) — The panel location identifier.
- `mode` (`number`) — The panel display mode or size.
- `html` (`HTMLElement | HTMLElement[] | string`) — The panel content.
- `script` (`string`) — A script associated with the panel content.
## editor.showProgress
`editor.showProgress(progressType, progressPercentage?)`
Shows, updates, or hides a sync or indexing progress indicator.
**Parameters:**
- `progressType` (`sync | index`) — The operation represented by the indicator.
- `progressPercentage?` (`number`) — Completion percentage, or undefined to hide the indicator.
## editor.startCompletion
`editor.startCompletion()`
Explicitly starts editor completion at the cursor.
## editor.toggleComment
`editor.toggleComment()`
Comments or uncomments the current line or selection.
## editor.toggleFold
`editor.toggleFold()`
Toggles folding for the region at the cursor.
## editor.transposeChars
`editor.transposeChars()`
Transposes the characters around the cursor.
## editor.undo
`editor.undo()`
Undoes the most recent editor change.
## editor.unfold
`editor.unfold()`
Unfolds the folded region at the cursor.
## editor.unfoldAll
`editor.unfoldAll()`
Unfolds all folded regions in the editor.
## editor.updateBakedSections
`editor.updateBakedSections()`
Re-evaluates every baked section on the current page and replaces each body with its latest output.
## editor.uploadFile
`editor.uploadFile(accept?, capture?)`
Opens the browser's native file picker and returns the selected file's bytes and metadata.
**Parameters:**
- `accept?` (`string`) — Accepted file types for the file input.
- `capture?` (`string`) — The media capture mode for the file input.
**Returns:**
- `UploadFile` — The selected file's name, content type, and bytes.
**Example:**
```lua
local file = editor.uploadFile(".txt")
print(file.name)
```
## editor.vimEx
`editor.vimEx(exCommand)`
Executes a Vim Ex command in the active Vim-mode editor.
**Parameters:**
- `exCommand` (`string`) — The Ex command to execute.
<!--/lua-->
+58 -1
View File
@@ -6,4 +6,61 @@ references:
The `encoding` namespace converts between strings, byte buffers, Base64, and UTF-8.
${spacelua.renderApiDocumentation("encoding")}
<!--#lua spacelua.renderApiDocumentation("encoding") -->
## encoding.base64Decode
`encoding.base64Decode(encoded)`
Decodes a Base64 string into a byte buffer.
**Parameters:**
- `encoded` (`string`)
**Returns:**
- `bytes` — Decoded bytes.
## encoding.base64Encode
`encoding.base64Encode(data)`
Encodes a string or byte buffer as Base64.
**Parameters:**
- `data` (`string|bytes`)
**Returns:**
- `string` — Base64-encoded data.
## encoding.utf8Decode
`encoding.utf8Decode(data)`
Decodes a UTF-8 byte buffer into a string.
**Parameters:**
- `data` (`bytes`)
**Returns:**
- `string` — Decoded text.
## encoding.utf8Encode
`encoding.utf8Encode(value)`
Encodes a UTF-8 string into a byte buffer.
**Parameters:**
- `value` (`string`)
**Returns:**
- `bytes` — UTF-8 encoded bytes.
<!--/lua-->
+49 -1
View File
@@ -8,4 +8,52 @@ references:
The Event API provides functions for working with SilverBullet's event bus system, allowing communication between different parts of the application.
${spacelua.renderApiDocumentation("event")}
<!--#lua spacelua.renderApiDocumentation("event") -->
## event.dispatch
`event.dispatch(eventName, data)`
Dispatches an event and collects responses from its listeners.
**Parameters:**
- `eventName` (`string`) — Event name.
- `data` — Event payload.
**Returns:**
- `table` — Listener responses.
**Example:**
```lua
local responses = event.dispatch("data.request", {id = 123})
```
## event.listEvents
`event.listEvents()`
Lists all event names that currently have listeners.
**Returns:**
- `table` — Registered event names.
## event.listen
`event.listen(listener)`
Registers a Space Lua listener on the event bus.
**Parameters:**
- `listener` (`table`) — Listener definition with name and run callback.
**Example:**
```lua
event.listen { name = "my-event", run = function(e) print(e.data) end }
```
<!--/lua-->
+484 -1
View File
@@ -7,4 +7,487 @@ references:
These functions are defined in the global namespace. Alongside standard Lua functions, Space Lua provides the `each` and `some` convenience functions.
${spacelua.renderApiDocumentation()}
<!--#lua spacelua.renderApiDocumentation() -->
## adder
`adder(a, b)`
Adds two numbers.
**Parameters:**
- `a` (`number`) — First number.
- `b` (`number`) — Second number.
**Returns:**
- `number` — sum
## assert
`assert(value, message?)`
Raises an error when a value is falsy; otherwise completes successfully.
**Parameters:**
- `value` — Condition to test.
- `message?` (`string`) — Error detail.
**Example:**
```lua
assert(user ~= nil, "user is required")
```
**See:** [[API/global]]
## clock
`clock()`
## dofile
`dofile(path)`
Reads and executes a Lua source file from the current space.
**Parameters:**
- `path` (`string`) — Space-relative Lua file path.
**See:** [[API/global]]
## each
`each(table)`
Returns a Space Lua iterator over array-like values without yielding indices.
**Parameters:**
- `table` (`table`)
**Returns:**
- `function` — Iterator yielding values.
**Example:**
```lua
for fruit in each({"apple", "banana"}) do
print(fruit)
end
```
**See:** [[API/global]]
## error
`error(message)`
Raises a Lua runtime error with the supplied message.
**Parameters:**
- `message` (`string`)
**See:** [[API/global]]
## formatMarkdownTable
`formatMarkdownTable(tree)`
**Parameters:**
- `tree`
## getmetatable
`getmetatable(table)`
Returns a table's metatable, or `nil` when none is set.
**Parameters:**
- `table` (`table`)
**Returns:**
- `table|nil`
**See:** [[API/global]]
## helloWorld
`helloWorld(name)`
**Parameters:**
- `name`
## ipairs
`ipairs(table)`
Returns an iterator over consecutive integer keys starting at 1 and stopping at the first `nil`.
**Parameters:**
- `table` (`table`)
**Returns:**
- `function` — Iterator yielding index and value.
**Example:**
```lua
for i, fruit in ipairs({"apple", "banana"}) do
print(i, fruit)
end
```
**See:** [[API/global]]
## load
`load(chunk)`
Compiles Lua source into a callable chunk without executing it.
**Parameters:**
- `chunk` (`string`) — Lua source code.
**Returns:**
- `function|nil` — Compiled chunk or `nil`.
- `string` — Compilation error when unsuccessful.
**See:** [[API/global]]
## marquee
`marquee(text)`
**Parameters:**
- `text`
## next
`next(table, index?)`
Returns the next table key and value after a given key, or the first pair when the key is omitted.
**Parameters:**
- `table` (`table`)
- `index?` — Previous key.
**Returns:**
- Value — Next key or `nil`.
- Value — Value at the next key.
**See:** [[API/global]]
## nodeParentOfType
`nodeParentOfType(tree, position, nodeType)`
**Parameters:**
- `tree`
- `position`
- `nodeType`
## pairs
`pairs(table)`
Returns an iterator over all table key-value pairs, respecting `__pairs`.
**Parameters:**
- `table` (`table`)
**Returns:**
- `function` — Iterator plus its state and initial control value.
**Example:**
```lua
for key, value in pairs({name = "Ada", age = 36}) do
print(key, value)
end
```
**See:** [[API/global]]
## pcall
`pcall(function, ...): boolean, ...`
Calls a function in protected mode and returns a success flag followed by results or an error message.
**Parameters:**
- `function` (`function`)
- `...` — Arguments passed to the function.
**Returns:**
- `boolean` — Whether the call succeeded.
- Value — Call results or error message.
**Example:**
```lua
local ok, result = pcall(function() return mightFail() end)
```
**See:** [[API/global]]
## print
`print(...)`
Prints string representations of its arguments to the runtime log.
**Parameters:**
- `...` — Values to print.
**Example:**
```lua
print("Hello, world!")
```
**See:** [[API/global]]
## rawequal
`rawequal(a, b)`
Tests two values for equality without invoking `__eq`.
**Parameters:**
- `a`
- `b`
**Returns:**
- `boolean`
**See:** [[API/global]]
## rawget
`rawget(table, key)`
Reads a table key without invoking `__index`.
**Parameters:**
- `table` (`table`)
- `key`
**Returns:**
- Value — Stored value or `nil`.
**See:** [[API/global]]
## rawlen
`rawlen(value)`
Returns a string or table length without invoking `__len`.
**Parameters:**
- `value` (`string|table`)
**Returns:**
- `integer`
**See:** [[API/global]]
## rawset
`rawset(table, key, value)`
Sets a table key without invoking `__newindex` and returns the table.
**Parameters:**
- `table` (`table`)
- `key`
- `value`
**Returns:**
- `table`
**Example:**
```lua
local t = setmetatable({}, {__newindex = function() error("blocked") end})
rawset(t, "name", "Ada")
```
**See:** [[API/global]]
## select
`select("#", ...): integer`
`select(index, ...): ...`
Returns the count of extra arguments or all arguments from a selected position onward.
**Parameters:**
- `index` (`integer|string`) — One-based index, negative index from the end, or `#`.
- `...`
**Returns:**
- Value — Argument count or selected argument values.
**See:** [[API/global]]
## setmetatable
`setmetatable(table, metatable)`
Sets a table's metatable and returns the table.
**Parameters:**
- `table` (`table`)
- `metatable` (`table`)
**Returns:**
- `table`
**See:** [[API/global]]
## some
`some(value)`
Returns `nil` for empty Space Lua values and otherwise returns the value unchanged.
**Parameters:**
- `value` — Value to normalize; blank strings, empty tables, infinities, and NaN are empty.
**Returns:**
- Value — Original value or `nil`.
**Example:**
```lua
print(some(" ") or "empty")
print(some({}) or "empty")
print(some(0))
```
**See:** [[API/global]]
## toggleReadOnlyMode
`toggleReadOnlyMode()`
## tonumber
`tonumber(value): number|nil`
`tonumber(value, base): integer|nil`
Converts a number or numeric string to a Lua number, optionally in a base from 2 through 36.
**Parameters:**
- `value` (`number|string`)
- `base?` (`integer`)
**Returns:**
- `number|nil`
**Example:**
```lua
print(tonumber("2a", 16)) -- 42
```
**See:** [[API/global]]
## tostring
`tostring(value)`
Converts a value to a string, respecting its `__tostring` metamethod.
**Parameters:**
- `value`
**Returns:**
- `string`
**See:** [[API/global]]
## type
`type(value)`
Returns the Lua type name of a value.
**Parameters:**
- `value`
**Returns:**
- `string`
**See:** [[API/global]]
## xpcall
`xpcall(function, errorHandler, ...): boolean, ...`
Calls a function in protected mode and transforms any error with an error handler.
**Parameters:**
- `function` (`function`)
- `errorHandler` (`function`)
- `...` — Arguments passed to the function.
**Returns:**
- `boolean` — Whether the call succeeded.
- Value — Call results or handler results.
**Example:**
```lua
local ok, message = xpcall(riskyOperation, function(err)
return "Operation failed: " .. tostring(err)
end)
```
**See:** [[API/global]]
<!--/lua-->
+21 -1
View File
@@ -10,4 +10,24 @@ HTTP APIs
> **warning** Warning
> Deprecated: use [[API/net]] instead.
${spacelua.renderApiDocumentation("http")}
<!--#lua spacelua.renderApiDocumentation("http") -->
## http.request
`http.request(url, options?)`
> **Deprecated:** Use net.proxyFetch instead.
Performs an authenticated HTTP request through the server proxy.
**Parameters:**
- `url` (`string`) — Target URL.
- `options?` (`table`) — Method, headers, body, and response encoding.
**Returns:**
- `table` — Status, headers, and decoded response body.
**See:** [[API/net#net.proxyFetch(url, options?)]]
<!--/lua-->
+246 -3
View File
@@ -10,7 +10,241 @@ The `index` API provides functions for interacting with SilverBullet's [[Object
The main query API is `index.objects`; the other collection functions are mostly convenient filters over the same index.
${spacelua.renderApiDocumentation("index")}
<!--#lua spacelua.renderApiDocumentation("index") -->
## index.aggregates
`index.aggregates()`
Returns stored aggregate records as a query collection.
## index.aspiringPages
`index.aspiringPages()`
Returns linked but not yet created pages as a query collection.
## index.comments
`index.comments()`
Returns all indexed inline comment objects as a query collection. Equivalent to index.tag "comment".
## index.contentPages
`index.contentPages(tagName?)`
Returns non-meta pages, optionally filtered by an additional tag, as a query collection.
## index.defineTag
`index.defineTag(tagDefinition)`
Defines or updates a tag and its Lua metatable.
## index.deleteObject
`index.deleteObject(page, tag, ref)`
Deletes an indexed object identified by page, tag, and reference.
## index.describeSchema
`index.describeSchema()`
Returns raw JSON Schemas for every configured tag that declares one.
## index.documents
`index.documents()`
Returns all indexed documents as a query collection.
## index.ensureFullIndex
`index.ensureFullIndex()`
Ensures the complete object index is available and current.
## index.extractFrontmatter
`index.extractFrontmatter(text, options?)`
Extracts and optionally transforms frontmatter and top-level tags in Markdown text.
**Parameters:**
- `text` (`string`) — Markdown text to inspect.
- `options?` (`table`) — Optional frontmatter and tag removal settings.
**Returns:**
- `table` — Parsed frontmatter and the optionally transformed text.
## index.getObjectByRef
`index.getObjectByRef(page, tag, ref)`
Returns an indexed object identified by page, tag, and reference.
## index.headers
`index.headers(tagName?)`
Returns all headers, optionally filtered by an additional tag, as a query collection.
## index.indexObjects
`index.indexObjects(page, objects)`
Indexes a collection of objects for a page.
## index.items
`index.items(tagName?)`
Returns all list items, optionally filtered by an additional tag, as a query collection.
## index.links
`index.links()`
Returns all indexed links as a query collection.
## index.markdown
`index.markdown(text, pageMeta?)`
Indexes Markdown text in memory and returns the objects extracted from it.
**Parameters:**
- `text` (`string`) — Markdown text to index.
- `pageMeta?` (`table`) — Optional page metadata used during indexing.
**Returns:**
- `table` — Objects extracted from the Markdown text.
## index.metaPages
`index.metaPages()`
Returns all meta pages as a query collection.
## index.objects
`index.objects(tagName)`
Returns objects carrying a tag as a query collection.
## index.pages
`index.pages(tagName?)`
Returns all pages, optionally filtered by an additional tag, as a query collection.
## index.paragraphs
`index.paragraphs(tagName?)`
Returns indexed paragraphs, optionally filtered by an additional tag, as a query collection.
## index.patchFrontmatter
`index.patchFrontmatter(text, patch)`
Applies a table of updates to the frontmatter in Markdown text.
**Parameters:**
- `text` (`string`) — Markdown text to update.
- `patch` (`table`) — Frontmatter keys and values to merge.
**Returns:**
- `string` — Markdown text with updated frontmatter.
## index.previewProcessedObjects
`index.previewProcessedObjects(page, objects)`
Runs the indexing pipeline without writing and returns processed tag/object pairs.
## index.queryLuaObjects
`index.queryLuaObjects(tag, query, scopedVariables?)`
Executes a structured Lua collection query against indexed objects.
## index.reindexSpace
`index.reindexSpace()`
Rebuilds the object index for the entire space.
## index.relations
`index.relations()`
Returns all indexed relations as a query collection.
## index.resolveAnchor
`index.resolveAnchor(name, page?)`
Resolves a named anchor to its host page, tag, and source range.
**Parameters:**
- `name` (`string`) — Anchor name without the leading dollar sign.
- `page?` (`string`) — Optional page to restrict the lookup to.
**Returns:**
- `table` — Resolution result including success or missing/duplicate reason.
## index.subPages
`index.subPages(pageName)`
Returns pages nested below a page name as a query collection.
## index.tables
`index.tables(tagName?)`
Returns indexed table rows, optionally filtered by an additional tag, as a query collection.
## index.tag
`index.tag(tagName)`
Returns objects carrying a tag as a query collection.
## index.tagSchema
`index.tagSchema(tagName)`
Returns the raw JSON Schema for a tag, or nil when none is declared.
## index.tags
`index.tags()`
Returns all indexed tag objects as a query collection.
## index.tasks
`index.tasks(tagName?)`
Returns all tasks, optionally filtered by an additional tag, as a query collection.
## index.validateObjects
`index.validateObjects(page, objects)`
Validates objects for a page and returns the first validation error, if any.
<!--/lua-->
## Integrated Query examples
@@ -20,11 +254,19 @@ ${query[[from index.pages() limit 1]]}
Query three sub-pages below the API page:
${query[[from p = index.subPages("API") limit 3 select p.name]]}
<!--#lua query[[from p = index.subPages("API") limit 3 select p.name]] -->
API/asset
API/clientStore
API/codeWidget
<!--/lua-->
Render three incomplete tasks:
${query[[from t = index.tasks() where not t.done limit 3 select templates.taskItem(t)]]}
<!--#lua query[[from t = index.tasks() where not t.done limit 3 select templates.taskItem(t)]] -->
* [ ] [[Outline Stress Test@1458]] A task as ordered's child
* [ ] [[Outline Stress Test@1559]] Task inside ordered child and now what will happen when this starts to wrap. Oh it looks nice!
* [ ] [[Attribute@1612]] Task with an attribute, I’m so cool
<!--/lua-->
Ad-hoc index a Markdown fragment and select its list items:
@@ -36,3 +278,4 @@ ${query[[
`index.extractFrontmatter` can inspect and optionally transform frontmatter and top-level tags. For example, this returns the frontmatter of the current page:
${(index.extractFrontmatter(editor.getText())).frontmatter}
+161 -1
View File
@@ -8,4 +8,164 @@ The `js` namespace provides JavaScript interoperability, including dynamic modul
`js.importFromSpace` resolves a space-relative file path to the current space's same-origin `/.fs` URL. This lets a library import a JavaScript module shipped as a [[Frontmatter#files]] asset without constructing a deployment-specific base URL. A leading slash is optional, and a sole `default` export is unwrapped like `js.import`.
${spacelua.renderApiDocumentation("js")}
<!--#lua spacelua.renderApiDocumentation("js") -->
## js.eachIterable
`js.eachIterable(iterable)`
Creates a Lua iterator over a JavaScript async iterable.
**Parameters:**
- `iterable` (`userdata`) — JavaScript async iterable.
**Returns:**
- `function` — Iterator yielding successive JavaScript values.
**Example:**
```lua
for value in js.eachIterable(someJsAsyncIterable) do
print(value)
end
```
## js.import
`js.import(url)`
Dynamically imports a JavaScript module from a URL.
**Parameters:**
- `url` (`string`) — Module URL.
**Returns:**
- `userdata` — Imported module, with a sole default export unwrapped.
**Example:**
```lua
local lib = js.import("https://esm.sh/lodash@4.17.21")
```
## js.importFromSpace
`js.importFromSpace(path)`
Imports a JavaScript module from a file in the current space.
**Parameters:**
- `path` (`string`) — Space-relative module path, with an optional leading slash.
**Returns:**
- `userdata` — Imported module, with a sole default export unwrapped.
**Example:**
```lua
local acme = js.importFromSpace("Library/acme/acme.js")
```
## js.log
`js.log(...)`
Logs values to the JavaScript console.
**Parameters:**
- `...` — Values to log.
**Example:**
```lua
js.log("User data:", {name = "Ada"})
```
## js.new
`js.new(constructor, ...): userdata`
Creates an instance of a JavaScript class.
**Parameters:**
- `constructor` (`userdata`) — JavaScript constructor function.
- `...` — Constructor arguments converted to JavaScript values.
**Returns:**
- `userdata` — New JavaScript instance.
**Example:**
```lua
local value = js.new(js.window.Date, "2024-03-14")
```
## js.stringify
`js.stringify(value)`
Serializes a value as JSON using JavaScript semantics.
**Parameters:**
- `value` — Value to serialize.
**Returns:**
- `string` — JSON representation.
**Example:**
```lua
print(js.stringify({1, 2, 3})) -- [1,2,3]
```
## js.tojs
`js.tojs(value)`
Converts a Lua value to its JavaScript representation.
**Parameters:**
- `value` — Lua value to convert.
**Returns:**
- Value — Converted JavaScript value.
**Example:**
```lua
local jsArray = js.tojs({1, 2, 3})
```
## js.tolua
`js.tolua(value)`
Converts a JavaScript value to its Lua representation.
**Parameters:**
- `value` — JavaScript value to convert.
**Returns:**
- Value — Converted Lua value.
**Example:**
```lua
local luaTable = js.tolua(jsArray)
```
<!--/lua-->
+64 -1
View File
@@ -7,4 +7,67 @@ references:
The JSON Schema API provides functions for validating JSON objects against JSON schemas.
${spacelua.renderApiDocumentation("jsonschema")}
<!--#lua spacelua.renderApiDocumentation("jsonschema") -->
## jsonschema.inferFromObject
`jsonschema.inferFromObject(object)`
Infers a best-effort draft 2020-12 JSON Schema from a sample value.
**Parameters:**
- `object` — Sample value whose shape is inferred.
**Returns:**
- `table` — Inferred schema marked x-inferred.
**Example:**
```lua
local schema = jsonschema.inferFromObject({name = "Widget", count = 3})
```
## jsonschema.validateObject
`jsonschema.validateObject(schema, object)`
Validates a value against a JSON Schema.
**Parameters:**
- `schema` (`table`) — JSON Schema to apply.
- `object` — Value to validate.
**Returns:**
- `string` — Validation error, or nil when valid.
**Example:**
```lua
local schema = {type = "object", properties = {name = {type = "string"}}, required = {"name"}}
local err = jsonschema.validateObject(schema, {name = "John"})
```
## jsonschema.validateSchema
`jsonschema.validateSchema(schema)`
Checks whether a JSON Schema has a supported top-level shape.
**Parameters:**
- `schema` — JSON Schema to validate.
**Returns:**
- `string` — Schema error, or nil when valid.
**Example:**
```lua
local err = jsonschema.validateSchema({type = "object"})
```
<!--/lua-->
+39 -1
View File
@@ -7,4 +7,42 @@ references:
The Language API provides functions for parsing code in various programming languages and listing supported languages.
${spacelua.renderApiDocumentation("language")}
<!--#lua spacelua.renderApiDocumentation("language") -->
## language.listLanguages
`language.listLanguages()`
Lists all supported fenced-code-block languages.
**Returns:**
- `table` — Supported language names.
**Example:**
```lua
local languages = language.listLanguages()
```
## language.parseLanguage
`language.parseLanguage(language, code)`
Parses code using a supported fenced-code-block language.
**Parameters:**
- `language` (`string`) — Language name or alias.
- `code` (`string`) — Source code to parse.
**Returns:**
- `table` — Parsed syntax tree.
**Example:**
```lua
local tree = language.parseLanguage("javascript", "const answer = 42")
```
<!--/lua-->
+141 -1
View File
@@ -8,4 +8,144 @@ references:
The Lua API provides functions for parsing and evaluating Lua code.
${spacelua.renderApiDocumentation("lua")}
<!--#lua spacelua.renderApiDocumentation("lua") -->
## lua.evalExpression
`lua.evalExpression(expression)`
Evaluates a Space Lua expression.
**Parameters:**
- `expression` (`string`) — Lua expression to evaluate.
**Returns:**
- Value — Evaluated result.
**Example:**
```lua
local result = lua.evalExpression("1 + 2 * 3")
print(result)
```
## lua.inspect
`lua.inspect(path?)`
Inspects a value in the live Space Lua environment and returns serializable type, function, definition, and property metadata.
**Parameters:**
- `path?` (`table`) — Sequence of property names from the global environment; omit to inspect globals.
**Returns:**
- `table|nil` — Inspection metadata, or nil when the requested path does not exist.
**Example:**
```lua
local info = lua.inspect({"editor", "getText"})
```
## lua.parse
`lua.parse(code)`
> **Deprecated:** Use lua.parseBlock instead.
Deprecated alias for lua.parseBlock.
**Parameters:**
- `code` (`string`) — Lua code to parse.
**Returns:**
- `table` — Parsed Lua block AST.
## lua.parseBlock
`lua.parseBlock(code)`
Parses a Space Lua chunk and returns its AST. Blocks retain comments in source order with their exact text, kind, and source range.
**Parameters:**
- `code` (`string`) — Lua code to parse.
**Returns:**
- `table` — Parsed Lua block AST.
**Example:**
```lua
local ast = lua.parseBlock("print(\"Hello\")")
```
## lua.parseExpression
`lua.parseExpression(expression)`
Parses a Space Lua expression and returns its AST.
**Parameters:**
- `expression` (`string`) — Lua expression to parse.
**Returns:**
- `table` — Parsed expression AST.
**Example:**
```lua
local expression = lua.parseExpression("1 + 2 * 3")
```
## lua.prettyPrintBlock
`lua.prettyPrintBlock(block, options?)`
Pretty-prints a parsed Space Lua block. Comments are preserved while their placement and indentation are normalized.
**Parameters:**
- `block` (`table`) — Parsed block AST.
- `options?` (`table`) — Formatting options: `indentWidth`, `quote`, and `trailingComma`.
**Returns:**
- `string` — Formatted Lua source.
**Example:**
```lua
local formatted = lua.prettyPrintBlock(lua.parseBlock("if a then return 1 end"))
```
## lua.prettyPrintExpression
`lua.prettyPrintExpression(expression, options?)`
Pretty-prints a parsed Space Lua expression.
**Parameters:**
- `expression` (`table`) — Parsed expression AST.
- `options?` (`table`) — Formatting options: `indentWidth`, `quote`, and `trailingComma`.
**Returns:**
- `string` — Formatted Lua source.
**Example:**
```lua
local formatted = lua.prettyPrintExpression(lua.parseExpression("{a=1,b=2}"))
```
<!--/lua-->
+129 -1
View File
@@ -9,4 +9,132 @@ references:
The Markdown API provides functions for parsing and rendering Markdown content.
${spacelua.renderApiDocumentation("markdown")}
<!--#lua spacelua.renderApiDocumentation("markdown") -->
## markdown.bakeSections
`markdown.bakeSections(text, pageName?)`
Re-evaluates all baked Lua sections in Markdown text; sections that error or only render as HTML are left unchanged.
**Parameters:**
- `text` (`string`) — Markdown containing baked sections.
- `pageName?` (`string`) — Page used as currentPage during evaluation.
**Returns:**
- `string` — Markdown with updated baked section bodies.
**Example:**
```lua
local text = "Total: <!--#lua 1 + 2 -->\nold\n<!-- /lua -->"
print(markdown.bakeSections(text))
```
## markdown.expandMarkdown
`markdown.expandMarkdown(text, options?)`
`markdown.expandMarkdown(tree, options?)`
Expands Markdown transclusions, Lua directives, and task references.
**Parameters:**
- `textOrTree` — Markdown text or parsed tree.
- `options?` (`table`) — Expansion switches: expandTransclusions, expandLuaDirectives, and rewriteTasks; all default to true.
**Returns:**
- Value — Expanded text or tree, matching the input form.
**Example:**
```lua
local expanded = markdown.expandMarkdown("This is some Lua: ${1 + 2}")
```
## markdown.markdownToHtml
`markdown.markdownToHtml(text, options?)`
Renders Markdown text to HTML.
**Parameters:**
- `text` (`string`) — Markdown source.
- `options?` (`table`) — HTML rendering options.
**Returns:**
- `string` — Rendered HTML.
**Example:**
```lua
local html = markdown.markdownToHtml("# Title")
```
## markdown.objectsToTable
`markdown.objectsToTable(data, options?)`
Formats a list of objects as a Markdown table.
**Parameters:**
- `data` (`table`) — Rows to render.
- `options?` (`table`) — Optional renderCell callback.
**Returns:**
- `string` — Markdown table.
**Example:**
```lua
local tableText = markdown.objectsToTable({{name = "Pete", age = 20}})
```
## markdown.parseMarkdown
`markdown.parseMarkdown(text)`
Parses Markdown text into a syntax tree.
**Parameters:**
- `text` (`string`) — Markdown source.
**Returns:**
- `table` — Parsed Markdown tree.
**Example:**
```lua
local tree = markdown.parseMarkdown("# Title")
```
## markdown.renderParseTree
`markdown.renderParseTree(tree)`
Renders a Markdown syntax tree back to source text.
**Parameters:**
- `tree` (`table`) — Markdown syntax tree.
**Returns:**
- `string` — Rendered Markdown.
**Example:**
```lua
local tree = markdown.parseMarkdown("# Title")
print(markdown.renderParseTree(tree))
```
<!--/lua-->
+475 -1
View File
@@ -6,4 +6,478 @@ references:
The `math` namespace contains Lua-compatible numeric functions plus Space Lua's `cosineSimilarity` helper.
${spacelua.renderApiDocumentation("math")}
<!--#lua spacelua.renderApiDocumentation("math") -->
## math.abs
`math.abs(x)`
Returns the absolute value of `x`.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.acos
`math.acos(x)`
Returns the arc cosine of `x` in radians.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.asin
`math.asin(x)`
Returns the arc sine of `x` in radians.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.atan
`math.atan(y, x?)`
Returns the arc tangent of `y/x` in radians, using `1` for omitted `x`.
**Parameters:**
- `y` (`number`)
- `x?` (`number`)
**Returns:**
- `number`
## math.ceil
`math.ceil(x)`
Returns the smallest integer greater than or equal to `x`.
**Parameters:**
- `x` (`number`)
**Returns:**
- `integer`
## math.cos
`math.cos(x)`
Returns the cosine of `x` radians.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.cosh
`math.cosh(x)`
> **Deprecated:** Retained for compatibility with older Lua versions.
Returns the hyperbolic cosine of `x`.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.cosineSimilarity
`math.cosineSimilarity(vecA, vecB)`
Returns the cosine similarity between two equal-length numeric vectors.
**Parameters:**
- `vecA` (`table`)
- `vecB` (`table`)
**Returns:**
- `number` — Cosine similarity.
**Example:**
```lua
print(math.cosineSimilarity({1, 2, 3}, {4, 5, 6}))
```
## math.deg
`math.deg(x)`
Converts an angle from radians to degrees.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
**Example:**
```lua
print(math.deg(math.pi)) -- 180
```
## math.exp
`math.exp(x)`
Returns `e` raised to `x`.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.floor
`math.floor(x)`
Returns the largest integer less than or equal to `x`.
**Parameters:**
- `x` (`number`)
**Returns:**
- `integer`
## math.fmod
`math.fmod(x, y)`
Returns the remainder of `x / y` with the quotient rounded toward zero.
**Parameters:**
- `x` (`number`)
- `y` (`number`)
**Returns:**
- `number`
## math.frexp
`math.frexp(x)`
Decomposes `x` into a normalized fraction and a power-of-two exponent.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number` — Fraction.
- `integer` — Exponent.
## math.ldexp
`math.ldexp(m, e)`
Returns `m * 2^e`, the inverse of `math.frexp`.
**Parameters:**
- `m` (`number`)
- `e` (`integer`)
**Returns:**
- `number`
## math.log
`math.log(x, base?)`
Returns the logarithm of `x`, using the natural base unless another base is supplied.
**Parameters:**
- `x` (`number`)
- `base?` (`number`)
**Returns:**
- `number`
**Example:**
```lua
print(math.log(100, 10)) -- 2
```
## math.max
`math.max(x, ...): number`
Returns the greatest of its arguments.
**Returns:**
- `number`
## math.min
`math.min(x, ...): number`
Returns the least of its arguments.
**Returns:**
- `number`
## math.modf
`math.modf(x)`
Splits `x` into its integral and fractional parts.
**Parameters:**
- `x` (`number`)
**Returns:**
- `integer` — Integral part.
- `float` — Fractional part.
**Example:**
```lua
local integer, fraction = math.modf(3.14)
```
## math.pow
`math.pow(x, y)`
> **Deprecated:** Use the `^` operator instead.
Returns `x` raised to the power `y`.
**Parameters:**
- `x` (`number`)
- `y` (`number`)
**Returns:**
- `number`
## math.rad
`math.rad(x)`
Converts an angle from degrees to radians.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.random
`math.random(): number`
`math.random(n): integer`
`math.random(m, n): integer`
Returns a pseudo-random float or an integer in a requested inclusive range.
**Parameters:**
- `m?` (`integer`)
- `n?` (`integer`)
**Returns:**
- `number` — Pseudo-random result.
**Example:**
```lua
print(math.random())
print(math.random(10))
print(math.random(5, 10))
```
## math.randomseed
`math.randomseed(): integer, integer`
`math.randomseed(x, y): integer, integer`
Seeds the pseudo-random generator and returns the two seeds used.
**Parameters:**
- `x?` (`integer`)
- `y?` (`integer`)
**Returns:**
- `integer` — First seed.
- `integer` — Second seed.
## math.sin
`math.sin(x)`
Returns the sine of `x` radians.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.sinh
`math.sinh(x)`
> **Deprecated:** Retained for compatibility with older Lua versions.
Returns the hyperbolic sine of `x`.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.sqrt
`math.sqrt(x)`
Returns the square root of `x`.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.tan
`math.tan(x)`
Returns the tangent of `x` radians.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.tanh
`math.tanh(x)`
> **Deprecated:** Retained for compatibility with older Lua versions.
Returns the hyperbolic tangent of `x`.
**Parameters:**
- `x` (`number`)
**Returns:**
- `number`
## math.tointeger
`math.tointeger(x)`
Converts a value to an integer when it has an exact finite integral representation.
**Parameters:**
- `x` — Value to convert.
**Returns:**
- `integer|nil` — Converted integer or `nil`.
## math.type
`math.type(x)`
Returns `integer` or `float` for a number, or `nil` for other values.
**Parameters:**
- `x` — Value to inspect.
**Returns:**
- `string|nil` — Numeric subtype or `nil`.
## math.ult
`math.ult(m, n)`
Compares two integers as unsigned 32-bit values.
**Parameters:**
- `m` (`integer`)
- `n` (`integer`)
**Returns:**
- `boolean`
**Example:**
```lua
print(math.ult(2, 3)) -- true
```
<!--/lua-->
+108 -1
View File
@@ -8,7 +8,113 @@ references:
The Message Queue API provides functions for implementing a simple message queue system.
${spacelua.renderApiDocumentation("mq")}
<!--#lua spacelua.renderApiDocumentation("mq") -->
## mq.ack
`mq.ack(queue, id)`
Acknowledges one queue message as processed.
**Parameters:**
- `queue` (`string`) — Queue name.
- `id` (`string`) — Message ID.
## mq.awaitEmptyQueue
`mq.awaitEmptyQueue(queue)`
Waits until a queue has no pending or processing messages.
**Parameters:**
- `queue` (`string`) — Queue name.
## mq.batchAck
`mq.batchAck(queue, ids)`
Acknowledges multiple queue messages as processed.
**Parameters:**
- `queue` (`string`) — Queue name.
- `ids` (`table`) — Message IDs.
## mq.batchSend
`mq.batchSend(queue, bodies)`
Sends multiple messages to a queue in one operation.
**Parameters:**
- `queue` (`string`) — Queue name.
- `bodies` (`table`) — Message bodies.
## mq.flushAllQueues
`mq.flushAllQueues()`
Removes all messages from every queue.
## mq.flushQueue
`mq.flushQueue(queue)`
Removes all messages from a queue.
**Parameters:**
- `queue` (`string`) — Queue name.
## mq.getQueueStats
`mq.getQueueStats(queue?)`
Gets queued, processing, and dead-letter counts for a queue.
**Parameters:**
- `queue?` (`string`) — Queue name.
**Returns:**
- `table` — Queue statistics.
## mq.send
`mq.send(queue, body)`
Sends a message to a queue.
**Parameters:**
- `queue` (`string`) — Queue name.
- `body` — Message body.
**Example:**
```lua
mq.send("tasks", "my task")
```
## mq.subscribe
`mq.subscribe(spec)`
Subscribes a Space Lua callback to a message queue.
**Parameters:**
- `spec` (`table`) — Subscription with queue, optional batchSize and pollInterval, autoAck (default true), and a run(messages) callback; each message has queue, id, and body fields.
**Example:**
```lua
mq.subscribe { queue = "tasks", batchSize = 1, run = function(messages) print(messages[1].body) end }
```
<!--/lua-->
## Example
@@ -27,3 +133,4 @@ mq.subscribe {
${widgets.button("Send message on queue", function()
mq.send("testqueue", "Hello world")
end)}
+47 -1
View File
@@ -16,4 +16,50 @@ The response table contains `ok`, `status`, `headers`, and `body`. JSON response
`net.readURI` and `net.writeURI` dispatch to the best service registered for the URI. Pass `{encoding = "text/markdown"}` to `net.readURI` when a service should force a particular result encoding.
${spacelua.renderApiDocumentation("net")}
<!--#lua spacelua.renderApiDocumentation("net") -->
## net.proxyFetch
`net.proxyFetch(url, options?)`
Performs an HTTP request through the SilverBullet server to avoid browser CORS restrictions.
**Parameters:**
- `url` (`string`) — URL to request.
- `options?` (`table`) — Optional method, headers, body, and responseEncoding values.
**Returns:**
- `table` — Response status, headers, decoded body, and ok flag.
## net.readURI
`net.readURI(uri, options?)`
Reads content from a URI using the best matching service.
**Parameters:**
- `uri` (`string`) — URI to read.
- `options?` (`table`) — Optional service-specific values such as encoding.
**Returns:**
- Value — Content returned by the matching service.
## net.writeURI
`net.writeURI(uri, content)`
Writes content to a URI using the best matching service.
**Parameters:**
- `uri` (`string`) — URI to write.
- `content` (`string|userdata`) — Text or binary content to write.
**Returns:**
- Value — Result returned by the matching service.
<!--/lua-->
+70 -1
View File
@@ -27,4 +27,73 @@ The `os` namespace provides date, time, and clock functions.
- `%Z` and `%z`: time zone name and UTC offset
- `%%`: literal percent sign
${spacelua.renderApiDocumentation("os")}
<!--#lua spacelua.renderApiDocumentation("os") -->
## os.clock
`os.clock()`
Returns a high-resolution elapsed time value in seconds.
**Returns:**
- `number` — Browser performance timer in seconds.
## os.date
`os.date(format?, timestamp?)`
Formats a timestamp as a date string or date table, optionally in UTC.
**Parameters:**
- `format?` (`string`) — `strftime`-style format, `*t` for a table, and optional leading `!` for UTC.
- `timestamp?` (`number`) — Unix timestamp; defaults to the current time.
**Returns:**
- `string|table` — Formatted date or date fields.
**Example:**
```lua
print(os.date("%Y-%m-%d"))
local utc = os.date("!*t")
```
## os.difftime
`os.difftime(t2, t1)`
Returns the difference in seconds from timestamp `t1` to `t2`.
**Parameters:**
- `t2` (`number`)
- `t1` (`number`)
**Returns:**
- `number` — The value `t2 - t1` in seconds.
## os.time
`os.time(): integer`
`os.time(dateTable): integer`
Returns the current Unix timestamp or one built from a local date table.
**Parameters:**
- `dateTable?` (`table`) — Local date fields `year`, `month`, `day`, and optional `hour`, `min`, and `sec`.
**Returns:**
- `integer` — Seconds since the Unix epoch.
**Example:**
```lua
local timestamp = os.time({year = 2020, month = 1, day = 1})
```
<!--/lua-->
+69 -1
View File
@@ -7,7 +7,74 @@ references:
The Service API exposes a simple service registry leveraged by various parts of SilverBullet. See [[Service]].
${spacelua.renderApiDocumentation("service")}
<!--#lua spacelua.renderApiDocumentation("service") -->
## service.define
`service.define(spec)`
Defines a service that can be discovered by selector.
**Parameters:**
- `spec` (`table`) — Selector, match rule, and run callback.
**Example:**
```lua
service.define { selector = "greeter", match = {}, run = function(name) return "Hello " .. name end }
```
## service.discover
`service.discover(selector, data)`
Discovers matching services sorted by descending priority.
**Parameters:**
- `selector` (`string`) — Service selector.
- `data` — Value passed to match callbacks.
**Returns:**
- `table` — Matching service descriptors.
## service.invoke
`service.invoke(match, data)`
Invokes a previously discovered service match.
**Parameters:**
- `match` (`table`) — Service match returned by service.discover.
- `data` — Value passed to the service.
**Returns:**
- Value — Service result.
## service.invokeBestMatch
`service.invokeBestMatch(selector, data)`
Discovers and invokes the highest-priority matching service.
**Parameters:**
- `selector` (`string`) — Service selector.
- `data` — Value used for matching and invocation.
**Returns:**
- Value — Best matching service result.
**Example:**
```lua
local greeting = service.invokeBestMatch("greeter", "Pete")
```
<!--/lua-->
# Architecture
@@ -45,3 +112,4 @@ service.define {
```
To invoke: ${service.invokeBestMatch("greeter-service", "Pete")} and ${service.invokeBestMatch("greeter-service", "Hank")}
+30 -1
View File
@@ -7,4 +7,33 @@ references:
The Shell API provides functions for running shell commands and interacting with processes.
${spacelua.renderApiDocumentation("shell")}
<!--#lua spacelua.renderApiDocumentation("shell") -->
## shell.run
`shell.run(command, arguments, stdin?)`
Runs a shell command on the server and returns its output.
**Parameters:**
- `command` (`string`) — Executable name.
- `arguments` (`table`) — Command arguments.
- `stdin?` (`string`) — Text supplied on standard input.
**Returns:**
- `table` — stdout, stderr, and numeric exit code.
**Examples:**
```lua
local result = shell.run("ls", {"-l"})
print(result.stdout)
```
```lua
local result = shell.run("cat", {}, "hello")
print(result.stdout)
```
<!--/lua-->
+152 -1
View File
@@ -8,4 +8,155 @@ references:
The Space API provides functions for interacting with pages, documents, and files in the space.
${spacelua.renderApiDocumentation("space")}
<!--#lua spacelua.renderApiDocumentation("space") -->
## space.deleteDocument
`space.deleteDocument(name)`
Deletes a document from the space.
## space.deleteFile
`space.deleteFile(name)`
Deletes an arbitrary file from the space.
## space.deletePage
`space.deletePage(name)`
Deletes a page from the space.
## space.fileExists
`space.fileExists(name)`
Checks whether an arbitrary file exists in the space.
## space.getAttachmentMeta
`space.getAttachmentMeta(name)`
> **Deprecated:** Use space.getDocumentMeta instead.
Deprecated alias for space.getDocumentMeta.
## space.getDocumentMeta
`space.getDocumentMeta(name)`
Returns metadata for a document.
## space.getFileMeta
`space.getFileMeta(name)`
Returns metadata for an arbitrary space file.
## space.getPageMeta
`space.getPageMeta(name)`
Returns metadata for a page.
## space.listAttachments
`space.listAttachments()`
> **Deprecated:** Use space.listDocuments instead.
Deprecated alias for space.listDocuments.
## space.listDocuments
`space.listDocuments()`
Lists all non-page documents in the space.
## space.listFiles
`space.listFiles()`
Lists every file in the space.
## space.listPages
`space.listPages()`
Lists all pages in the space.
## space.listPlugs
`space.listPlugs()`
Lists all plug files in the space.
## space.pageExists
`space.pageExists(name)`
Checks whether a page exists in the space.
## space.readAttachment
`space.readAttachment(name)`
> **Deprecated:** Use space.readDocument instead.
Deprecated alias for space.readDocument.
## space.readDocument
`space.readDocument(name)`
Reads a document as binary data.
## space.readFile
`space.readFile(name)`
Reads an arbitrary space file as binary data.
## space.readFileWithMeta
`space.readFileWithMeta(name)`
Reads an arbitrary space file together with its metadata.
## space.readPage
`space.readPage(name)`
Reads a page and returns its Markdown text.
## space.readPageWithMeta
`space.readPageWithMeta(name)`
Reads a page and returns both its Markdown text and metadata.
## space.readRef
`space.readRef(ref)`
Reads the text addressed by a page, header, or position reference.
## space.writeDocument
`space.writeDocument(name, data)`
Writes binary document data and returns its metadata.
## space.writeFile
`space.writeFile(name, data)`
Writes an arbitrary binary file and returns its metadata.
## space.writePage
`space.writePage(name, text)`
Writes Markdown text to a page and returns its metadata.
<!--/lua-->
+221 -1
View File
@@ -8,4 +8,224 @@ references:
The Space Lua API provides functions for working with Lua expressions and templates.
${spacelua.renderApiDocumentation("spacelua")}
<!--#lua spacelua.renderApiDocumentation("spacelua") -->
## spacelua.baseUrl
`spacelua.baseUrl()`
Returns the SilverBullet instance's base URL, or `nil` when run on the server.
**Returns:**
- `string|nil`
**Example:**
```lua
local url = spacelua.baseUrl()
print(url)
```
## spacelua.describe
`spacelua.describe(functionOrName)`
Returns structured documentation for a Lua function value or dotted API name.
**Parameters:**
- `functionOrName` (`function|string`) — Function value or dotted API name to inspect.
**Returns:**
- `table|nil` — Structured function metadata, or `nil` when the target is not a function.
**Example:**
```lua
local info = spacelua.describe(editor.getText)
print(info.name, info.kind, info.see)
local sameInfo = spacelua.describe("editor.getText")
```
## spacelua.evalExpression
`spacelua.evalExpression(parsedExpr, envAugmentation?)`
Evaluates a parsed Lua expression, optionally with additional environment values.
**Parameters:**
- `parsedExpr` (`table`) — Parsed expression AST.
- `envAugmentation?` (`table`) — Values added to the expression environment.
**Returns:**
- Value — Evaluated result.
**Example:**
```lua
local parsed = spacelua.parseExpression("x + y")
local result = spacelua.evalExpression(parsed, {x = 1, y = 2})
print(result)
```
## spacelua.interpolate
`spacelua.interpolate(template, envAugmentation?)`
Interpolates `${...}` Lua expressions in a string, optionally with additional environment values.
**Parameters:**
- `template` (`string`) — Template containing `${...}` expressions.
- `envAugmentation?` (`table`) — Values added to the interpolation environment.
**Returns:**
- `string` — Interpolated string.
**Example:**
```lua
local greeting = spacelua.interpolate("Hello ${name}!", {name = "Pete"})
print(greeting)
```
## spacelua.listFunctions
`spacelua.listFunctions(namespace?)`
Lists documented functions in the global environment or an API namespace.
**Parameters:**
- `namespace?` (`table|string`) — Namespace table or dotted name; omit for globals.
**Returns:**
- `table` — Function metadata records.
**Example:**
```lua
for info in each(spacelua.listFunctions("editor")) do
print(info.name, info.description or info.see)
end
```
## spacelua.parseBlock
`spacelua.parseBlock(code)`
Parses a Lua chunk and returns its AST. Blocks retain comments in source order with their exact text, kind, and source range.
**Parameters:**
- `code` (`string`) — Lua code to parse.
**Returns:**
- `table` — Parsed block AST.
**Example:**
```lua
local parsed = spacelua.parseBlock("local x = 1\nreturn x + 2")
```
## spacelua.parseExpression
`spacelua.parseExpression(luaExpression)`
Parses a Lua expression and returns its AST.
**Parameters:**
- `luaExpression` (`string`) — Lua expression to parse.
**Returns:**
- `table` — Parsed expression AST.
**Example:**
```lua
local parsed = spacelua.parseExpression("1 + 1")
```
## spacelua.prettyPrintBlock
`spacelua.prettyPrintBlock(block, options?)`
Pretty-prints a parsed Lua block AST. Comments are preserved while their placement and indentation are normalized.
**Parameters:**
- `block` (`table`) — Parsed block AST.
- `options?` (`table`) — Formatting options: `indentWidth`, `quote`, and `trailingComma`.
**Returns:**
- `string` — Formatted Lua source.
**Example:**
```lua
local formatted = spacelua.prettyPrintBlock(spacelua.parseBlock("if a then return 1 end"))
print(formatted)
```
## spacelua.prettyPrintExpression
`spacelua.prettyPrintExpression(parsedExpr, options?)`
Pretty-prints a parsed Lua expression AST.
**Parameters:**
- `parsedExpr` (`table`) — Parsed expression AST.
- `options?` (`table`) — Formatting options: `indentWidth`, `quote`, and `trailingComma`.
**Returns:**
- `string` — Formatted Lua source.
**Example:**
```lua
local parsed = spacelua.parseExpression("{a=1,b=2}")
print(spacelua.prettyPrintExpression(parsed))
```
## spacelua.renderApiDocumentation
`spacelua.renderApiDocumentation(target?)`
Renders API documentation for a function, namespace, or the global environment as Markdown.
**Parameters:**
- `target?` (`function|table|string`) — Function value, namespace table, or dotted API name to document; omit for globals.
**Returns:**
- `string` — Rendered Markdown.
**Examples:**
Render a namespace as a live API-page directive.
```markdown
${spacelua.renderApiDocumentation("lua")}
```
Render one function by its dotted API name.
```markdown
${spacelua.renderApiDocumentation("editor.getText")}
```
<!--/lua-->
+411 -1
View File
@@ -36,4 +36,414 @@ print(string.match("2024-03-14", "%d+-(%d+)-%d+"))
-- Standard Lua prints "03".
```
${spacelua.renderApiDocumentation("string")}
<!--#lua spacelua.renderApiDocumentation("string") -->
## string.byte
`string.byte(s, i?, j?)`
Returns the numeric character codes in the inclusive range from `i` to `j`.
**Parameters:**
- `s` (`string`)
- `i?` (`integer`)
- `j?` (`integer`)
**Returns:**
- `integer` — One result per character.
## string.char
`string.char(...): string`
Creates a string from numeric character codes.
**Returns:**
- `string`
## string.endsWith
`string.endsWith(s, suffix)`
Returns whether a string ends with a literal suffix.
**Parameters:**
- `s` (`string`)
- `suffix` (`string`)
**Returns:**
- `boolean`
## string.find
`string.find(s, pattern, init?, plain?)`
Finds the first Lua-pattern match and returns its bounds followed by captures.
**Parameters:**
- `s` (`string`)
- `pattern` (`string`)
- `init?` (`integer`)
- `plain?` (`boolean`)
**Returns:**
- `integer|nil` — Start index or `nil`.
- `integer` — End index.
## string.format
`string.format(format, ...): string`
Formats values according to a C-style format string.
**Parameters:**
- `format` (`string`)
- `...` — Values consumed by conversion specifiers.
**Returns:**
- `string`
**Example:**
```lua
print(string.format("Name: %s, score: %.1f", "Ada", 9.5))
```
## string.gmatch
`string.gmatch(s, pattern, init?)`
Returns an iterator over successive Lua-pattern matches and captures.
**Parameters:**
- `s` (`string`)
- `pattern` (`string`)
- `init?` (`integer`)
**Returns:**
- `function` — Match iterator.
**Example:**
```lua
for word in string.gmatch("hello world", "%w+") do
print(word)
end
```
## string.gsub
`string.gsub(s, pattern, replacement, n?)`
Replaces Lua-pattern matches using a string, table, or function replacement.
**Parameters:**
- `s` (`string`)
- `pattern` (`string`)
- `replacement` (`string|table|function`)
- `n?` (`integer`)
**Returns:**
- `string` — Result string.
- `integer` — Number of replacements.
**Example:**
```lua
local result, count = string.gsub("hello hello", "hello", "hi", 1)
print(result, count) -- hi hello 1
```
## string.len
`string.len(s)`
Returns the length of a string.
**Parameters:**
- `s` (`string`)
**Returns:**
- `integer`
## string.lower
`string.lower(s)`
Returns a copy of a string converted to lowercase.
**Parameters:**
- `s` (`string`)
**Returns:**
- `string`
## string.match
`string.match(s, pattern, init?)`
Returns captures from the first Lua-pattern match, or `nil` when none is found.
**Parameters:**
- `s` (`string`)
- `pattern` (`string`)
- `init?` (`integer`)
**Returns:**
- Value — Pattern captures, whole match, or `nil`.
**Example:**
```lua
local year, month = string.match("2024-03", "(%d+)%-(%d+)")
```
## string.matchRegex
`string.matchRegex(s, pattern)`
Matches a string with a JavaScript regular expression and returns the match array.
**Parameters:**
- `s` (`string`)
- `pattern` (`string`)
**Returns:**
- `table|nil`
**Example:**
```lua
local match = string.matchRegex("hello123", "([a-z]+)([0-9]+)")
print(match[1], match[2], match[3])
```
## string.matchRegexAll
`string.matchRegexAll(s, pattern)`
Returns an iterator over all JavaScript regular-expression matches.
**Parameters:**
- `s` (`string`)
- `pattern` (`string`)
**Returns:**
- `function` — Iterator yielding match arrays.
**Example:**
```lua
for match in string.matchRegexAll("a1b2", "([a-z])([0-9])") do
print(match[1], match[2], match[3])
end
```
## string.pack
`string.pack(format, ...): string`
Packs values into a binary string according to a Lua 5.4 format string.
**Parameters:**
- `format` (`string`) — Binary packing format.
- `...` — Values consumed by the format options.
**Returns:**
- `string` — Packed binary string.
## string.packsize
`string.packsize(format)`
Returns the byte size of a fixed-length Lua 5.4 packing format.
**Parameters:**
- `format` (`string`) — Fixed-length binary packing format.
**Returns:**
- `integer` — Packed byte count.
## string.rep
`string.rep(s, n, sep?)`
Returns `n` copies of a string joined by an optional separator.
**Parameters:**
- `s` (`string`)
- `n` (`integer`)
- `sep?` (`string`)
**Returns:**
- `string`
## string.reverse
`string.reverse(s)`
Returns a string with its characters in reverse order.
**Parameters:**
- `s` (`string`)
**Returns:**
- `string`
## string.split
`string.split(s, sep)`
Splits a string on a literal separator and returns the substrings.
**Parameters:**
- `s` (`string`)
- `sep` (`string`)
**Returns:**
- `table`
**Example:**
```lua
for part in each(string.split("a,b,c", ",")) do
print(part)
end
```
## string.startsWith
`string.startsWith(s, prefix)`
Returns whether a string starts with a literal prefix.
**Parameters:**
- `s` (`string`)
- `prefix` (`string`)
**Returns:**
- `boolean`
## string.sub
`string.sub(s, i, j?)`
Returns the substring from inclusive index `i` through `j`, supporting negative indices.
**Parameters:**
- `s` (`string`)
- `i` (`integer`)
- `j?` (`integer`)
**Returns:**
- `string`
## string.trim
`string.trim(s)`
Removes whitespace from both ends of a string.
**Parameters:**
- `s` (`string`)
**Returns:**
- `string`
## string.trimEnd
`string.trimEnd(s)`
Removes whitespace from the end of a string.
**Parameters:**
- `s` (`string`)
**Returns:**
- `string`
## string.trimStart
`string.trimStart(s)`
Removes whitespace from the beginning of a string.
**Parameters:**
- `s` (`string`)
**Returns:**
- `string`
## string.unpack
`string.unpack(format, data, init?)`
Unpacks values from a binary string according to a Lua 5.4 format string.
**Parameters:**
- `format` (`string`) — Binary unpacking format.
- `data` (`string`) — Packed binary string.
- `init?` (`integer`) — One-based starting position.
**Returns:**
- Value — Unpacked values followed by the next unread position.
## string.upper
`string.upper(s)`
Returns a copy of a string converted to uppercase.
**Parameters:**
- `s` (`string`)
**Returns:**
- `string`
<!--/lua-->
+44 -1
View File
@@ -8,4 +8,47 @@ references:
The Sync API provides functions for interacting with the sync engine when the client runs in Sync mode.
${spacelua.renderApiDocumentation("sync")}
<!--#lua spacelua.renderApiDocumentation("sync") -->
## sync.hasInitialSyncCompleted
`sync.hasInitialSyncCompleted()`
Checks whether the initial client synchronization has completed.
**Returns:**
- `boolean` — Whether initial sync is complete.
## sync.performFileSync
`sync.performFileSync(path)`
Prioritizes a file for immediate synchronization and waits for completion.
**Parameters:**
- `path` (`string`) — Space-relative file path.
**Example:**
```lua
sync.performFileSync("notes/important.md")
```
## sync.performSpaceSync
`sync.performSpaceSync()`
Starts an immediate full-space synchronization and waits for completion.
**Returns:**
- `number` — Number of sync operations, or zero without an active worker.
**Example:**
```lua
local changes = sync.performSpaceSync()
```
<!--/lua-->
+156 -1
View File
@@ -8,4 +8,159 @@ references:
The System API provides system-level functions for interacting with the SilverBullet environment.
${spacelua.renderApiDocumentation("system")}
<!--#lua spacelua.renderApiDocumentation("system") -->
## system.cleanDatabases
`system.cleanDatabases()`
> **Deprecated:** Use system.wipeClient or the Client: Wipe command instead.
Deprecated no-op retained for compatibility.
## system.getBaseURI
`system.getBaseURI()`
Returns the browser base URI for this SilverBullet instance.
## system.getConfig
`system.getConfig(key, defaultValue?)`
Returns a configuration value, with an optional default.
## system.getEnv
`system.getEnv()`
> **Deprecated:** The environment is always the client.
Deprecated environment probe that always returns nil.
## system.getMode
`system.getMode()`
Returns rw for read-write mode or ro for read-only mode.
## system.getSpaceConfig
`system.getSpaceConfig(key, defaultValue?)`
> **Deprecated:** Use system.getConfig instead.
Deprecated alias for system.getConfig.
## system.getURLPrefix
`system.getURLPrefix()`
Returns the configured URL path prefix for this SilverBullet instance.
## system.getVersion
`system.getVersion()`
Returns the running SilverBullet version.
## system.invokeCommand
`system.invokeCommand(name, args?)`
> **Deprecated:** Use editor.invokeCommand instead.
Deprecated alias for editor.invokeCommand.
## system.invokeFunction
`system.invokeFunction(name, ...)`
Invokes a loaded plug function by its plug-qualified name.
## system.invokeFunctionOnServer
`system.invokeFunctionOnServer(name, ...)`
> **Deprecated:** Use system.invokeFunction instead.
Deprecated alias for system.invokeFunction.
## system.listCommands
`system.listCommands()`
Returns a map of every currently available command definition.
## system.listSyscalls
`system.listSyscalls()`
Lists registered syscalls with permissions, argument counts, and documentation metadata.
## system.loadPlug
`system.loadPlug(path)`
Loads or reloads one plug from a space file path.
## system.loadScripts
`system.loadScripts()`
Reloads Space Lua scripts and configuration.
## system.loadSpaceScripts
`system.loadSpaceScripts()`
> **Deprecated:** Use system.loadScripts instead.
Deprecated alias for system.loadScripts.
## system.loadSpaceStyles
`system.loadSpaceStyles()`
Reloads custom Space Style definitions.
## system.reboot
`system.reboot()`
Saves the current editor buffer, detects on-disk changes, waits for indexing, and reloads configuration, scripts, styles, and client state. Because the buffer is saved first, an external edit to the currently open page can be overwritten; edit that page through the editor or navigate away first.
## system.reloadConfig
`system.reloadConfig()`
> **Deprecated:** Configuration reloads automatically; use system.reboot when needed.
Deprecated no-op that returns the current configuration.
## system.reloadPlugs
`system.reloadPlugs()`
Reloads every plug available to the client.
## system.serverSyscall
`system.serverSyscall(name, ...)`
> **Deprecated:** Invoke the target syscall directly instead.
Deprecated helper for invoking a named syscall.
## system.unloadPlug
`system.unloadPlug(path)`
Unloads the plug loaded from a space file path.
## system.wipeClient
`system.wipeClient(logout?)`
Wipes local client state, cached files, databases, and optionally the login session.
<!--/lua-->
+205 -1
View File
@@ -6,4 +6,208 @@ references:
The `table` namespace contains the Lua table library and Space Lua collection helpers.
${spacelua.renderApiDocumentation("table")}
<!--#lua spacelua.renderApiDocumentation("table") -->
## table.concat
`table.concat(table, sep?, i?, j?)`
Concatenates table elements from `i` through `j` using an optional separator.
**Parameters:**
- `table` (`table`)
- `sep?` (`string`)
- `i?` (`integer`)
- `j?` (`integer`)
**Returns:**
- `string`
## table.find
`table.find(table, criteriaFn, fromIndex?)`
Finds the first array element accepted by a predicate and returns its index and value.
**Parameters:**
- `table` (`table`)
- `criteriaFn` (`function`) — Predicate called with each value.
- `fromIndex?` (`integer`)
**Returns:**
- `integer|nil` — Matching index or `nil`.
- Value — Matching value.
**Example:**
```lua
local index, value = table.find({1, 2, 3, 4}, function(n) return n % 2 == 0 end)
```
## table.includes
`table.includes(table, value)`
Returns whether any table value is Lua-equal to a requested value.
**Parameters:**
- `table` (`table`)
- `value` — Value to find.
**Returns:**
- `boolean`
## table.insert
`table.insert(table, value)`
`table.insert(table, pos, value)`
Inserts a value at a position, shifting later elements, or appends it when no position is supplied.
**Parameters:**
- `table` (`table`)
- `posOrValue` — Insertion position or appended value.
- `value?` — Value for positional insertion.
**Example:**
```lua
local fruits = {"apple", "orange"}
table.insert(fruits, 2, "banana")
print(table.concat(fruits, ", "))
```
## table.keys
`table.keys(table)`
Returns an array containing all keys of a table or JavaScript object.
**Parameters:**
- `table` (`table`)
**Returns:**
- `table` — Array of keys.
## table.move
`table.move(a1, f, e, t, a2?)`
Moves an inclusive element range to a destination table while handling overlaps.
**Parameters:**
- `a1` (`table`) — Source table.
- `f` (`integer`) — First source index.
- `e` (`integer`) — Last source index.
- `t` (`integer`) — Destination start index.
- `a2?` (`table`) — Destination table; defaults to `a1`.
**Returns:**
- `table` — Destination table.
## table.pack
`table.pack(...): table`
Packs all arguments into a table with a count stored in field `n`.
**Returns:**
- `table` — Arguments at integer keys plus field `n`.
## table.remove
`table.remove(table, pos?)`
Removes and returns an element, shifting later elements down.
**Parameters:**
- `table` (`table`)
- `pos?` (`integer`) — Position; defaults to the last element.
**Returns:**
- Value — Removed value.
## table.select
`table.select(table, ...keys): table`
`table.select(table, keys): table`
Copies selected keys from a table into a new table.
**Parameters:**
- `table` (`table`)
- `keys` — Individual keys or one array-like table of keys.
**Returns:**
- `table`
**Example:**
```markdown
${query[[
from p = index.pages()
limit 3
select table.select(p, "name", "lastModified")
]]}
```
## table.sort
`table.sort(table, comp?)`
Sorts a table in place using ascending order or an optional comparison function.
**Parameters:**
- `table` (`table`)
- `comp?` (`function`)
**Returns:**
- `table` — The sorted table in Space Lua.
**Example:**
```lua
local numbers = {3, 1, 2}
table.sort(numbers, function(a, b) return a > b end)
```
## table.unpack
`table.unpack(table, i?, j?)`
Returns the table values from index `i` through `j` as separate results.
**Parameters:**
- `table` (`table`)
- `i?` (`integer`)
- `j?` (`integer`)
**Returns:**
- Value — One result per selected element.
**Example:**
```lua
local second, third = table.unpack({"a", "b", "c"}, 2, 3)
```
<!--/lua-->
+7 -2
View File
@@ -121,11 +121,15 @@ tag.define {
```
The result is the following:
${query[[
<!--#lua query[[
from t = tags.task
where t.deadline
select table.select(t, "name", "done", "deadline")
]]}
]] -->
|name|done|deadline|
|--|--|--|
|Hello |false|2026-12-31|
<!--/lua-->
## Styling
Tags get assigned a `data-tag-name` attribute in the DOM, which you can use to do custom styling with [[Space Style]].
@@ -138,3 +142,4 @@ a[data-tag-name="my-red-tag"] {
background-color: red;
}
```
+6 -2
View File
@@ -26,6 +26,10 @@ Iterates over a collection and renders a template for each item.
Example:
${template.each(query[[from index.pages() limit 3]], template.new[==[
<!--#lua template.each(query[[from index.pages() limit 3]], template.new[==[
* ${name}
]==])}
]==]) -->
* ADR
* ADR/001 Offline-First PWA
* ADR/002 Sync Engine
<!--/lua-->
+7 -2
View File
@@ -23,7 +23,9 @@ end
Can be used as follows:
${helloWorld("Pete")}
<!--#lua helloWorld("Pete") -->
Hello world, *Pete*!
<!--/lua-->
## DOM widgets
To render a custom HTML-based widget, use the [[API/dom]] elements passed as an argument to `widget.html`:
@@ -74,7 +76,9 @@ function clock()
end
```
${clock()}
<!--#lua clock() -->
Not supported
<!--/lua-->
# API
## widget.new(spec)
@@ -114,3 +118,4 @@ Keys:
* `markdown` (Copy-button content)
* `cssClasses`
* `display` (defaults to `block`)
+30 -1
View File
@@ -8,4 +8,33 @@ references:
The YAML API provides functions for parsing and stringifying YAML content.
${spacelua.renderApiDocumentation("yaml")}
<!--#lua spacelua.renderApiDocumentation("yaml") -->
## yaml.parse
`yaml.parse(text)`
Parses a YAML string into a Lua value.
**Parameters:**
- `text` (`string`) — YAML source text.
**Returns:**
- Value — Parsed YAML value.
## yaml.stringify
`yaml.stringify(value)`
Serializes a Lua value as YAML text.
**Parameters:**
- `value` — Value to serialize.
**Returns:**
- `string` — YAML representation of the value.
<!--/lua-->