Skip to content

Plugin Lua API

github-actions[bot] edited this page Dec 4, 2026 · 2 revisions

GridLock Lua 5.1 / LuaJIT gl.* API Reference

GridLock ships an optional Tier-2 scripting host (plugins/gridlock_lua/libgridlock_lua.so, configured via -Dlua=auto|enabled|disabled) compiled strictly against the pure-C99 v2.0 ABI. Core gridlock has zero liblua dependency.


1. Startup, package.path, Watchdog & Sandboxing

  • Init Scripts: Loads <config-dir>/init.lua (default ~/.config/gridlock/init.lua, overridden by --config-dir or GRIDLOCK_CONFIG_DIR), installed <config-dir>/plugins/<name>/init.lua, and optional <workspace>/.gridlock/init.lua / <workspace>/.gridlock/plugins/<name>/init.lua.
  • Offline LuaRocks (Zero Networking): Prepends <config-dir>/lua/?.lua, <config-dir>/data/luarocks/share/lua/<abi>/?.lua, and <config-dir>/data/luarocks/lib/lua/<abi>/?.so (matching 5.1 for LuaJIT or 5.4 for PUC Lua) and runs pcall(require, "luarocks.loader").
  • Instruction-Count Watchdog: Every lua_pcall runs under a 1,000,000-instruction lua_sethook timeout guard so infinite loops never freeze the IDE.
  • Untrusted Workspace Sandbox: Workspace .gridlock/init.lua scripts execute in a restricted environment stripping os.execute, os.remove, os.rename, io.popen, and package.loadlib unless the workspace is explicitly trusted.
  • Hot Reload: Run Reload Lua Configuration (lua.reload_init) from the Command Palette (Ctrl+Shift+P), or iterate live in the PLAYGROUND sidebar (Ctrl+Shift+R).

2. gl.api / gl.core

gl.core is an alias for gl.api.

Function Signature / Parameters Return / Behavior
gl.api.abi_version Constant string "2.0"
gl.api.log(level, msg) level: "debug" | "info" | "warn" | "error", msg: string Emits ANSI/OSC-sanitized workstation log.
gl.api.config_dir() (none) Active config directory path (--config-dir aware).
gl.api.data_dir() (none) Plugin data directory path.
gl.api.workspace_root() (none) Active workspace root path.
gl.api.is_workspace_trusted() (none) Boolean workspace trust state.
gl.api.defer_fn(delay_ms, fn) delay_ms: integer >= 0, fn: function() (also accepts (fn, delay_ms) and alias gl.api.defer) Schedules one-shot fn() on the Qt GUI thread after delay_ms ms under the watchdog; cancelled automatically on unload/reload.

3. gl.buf

Function Signature / Description
gl.buf.open_buffer(uri, [opts]) Opens/focuses a virtual buffer (gridlock://...). opts: { title, readonly, focus }. Alias: gl.buf.open_virtual. Returns buf_id.
gl.buf.close_buffer(buf_id) Closes virtual buffer.
gl.buf.active() Returns active buf_id.
gl.buf.line_count(buf_id) Returns 0-based line count.
gl.buf.get_lines(buf_id, start_0, end_0) Returns array of lines [start_0, end_0).
gl.buf.set_lines(buf_id, start_0, end_0, lines) Replaces [start_0, end_0) with lines array and syncs the editor immediately.
gl.buf.get_cursor(buf_id) / set_cursor(buf_id, line, col) Reads/sets 0-based cursor position.
gl.buf.create_namespace(name) Creates/retrieves extmark namespace ID ns_id.
gl.buf.set_extmark(buf_id, ns_id, line_0, col_0, opts) Adds gutter sign, line highlight, or EOL virtual text ({ sign_text, virt_text, hl_group, priority }).
gl.buf.clear_namespace(buf_id, ns_id, [start_0, end_0]) Clears extmarks in ns_id.

4. gl.keymap & gl.autocmd

Function Signature / Description
gl.keymap.register_command(id, title, fn) Registers a command in Command Palette (Ctrl+Shift+P) and Tools -> Plugins.
gl.keymap.set(mode, lhs, rhs, [opts]) Binds lhs (single key or chord like "<leader>mr" / "C-c m r") in mode ("global", "normal", "insert", "visual", "debug") to a command ID string or Lua function. opts: { buffer, desc }.
gl.keymap.del(mode, lhs, [buffer_id]) Removes a keymap binding.
gl.autocmd.create(event, opts) Subscribes to event with opts = { pattern = "*", group = "...", priority = 0, callback = function(ev) ... end }. Returns handle.
gl.autocmd.delete(handle) Unsubscribes handle.

Supported autocmd events: "BufReadPost", "BufWritePre" (vetoable by returning false), "BufWritePost", "CursorMoved", "ModeChanged", "BuildFinished", "ThemeChanged", "DebugLaunchPre" (vetoable), "DebugSessionStart", "RankStopped", "BreakpointHit", "FinalizeDetected".


5. gl.dbg / gl.mpi (Async GDB/MI Inspection)

gl.mpi is an alias for gl.dbg.

Function Parameters Callback / Return
gl.dbg.active_rank() (none) Integer focused MPI rank ID (0-based).
gl.dbg.rank_count() (none) Integer total rank count (0 when idle).
gl.dbg.rank_state(rank) rank: integer State string ("stopped", "running", "idle", etc.).
gl.dbg.send_mi_async(rank, mi_cmd, cb) rank: integer, mi_cmd: GDB/MI command string, cb: function(res) Dispatches tokenized async MI command; invokes cb(res) on GUI thread with res = { ok, status, status_code, rank, raw, value, memory, begin, contents }. Leading numeric MI token is stripped from res.raw.
gl.dbg.read_register(rank, reg_name, cb) rank: integer, reg_name: string (e.g. "rsp" or "$rsp", "rip", "x0"), cb: function(res) Evaluates -data-evaluate-expression "(unsigned long long)$<reg>"; res.value holds the numeric register value string when res.ok == true.
gl.dbg.read_memory(rank, addr, byte_len, cb) rank: integer, addr: hex string or integer address (e.g. "0x7fffffffe000"), byte_len: positive integer, cb: function(res) Issues -data-read-memory-bytes <addr> <byte_len>; res.begin holds start address, res.contents holds lowercase hex byte string (2 * byte_len chars), and res.memory holds raw MI memory block.
gl.dbg.register_type_visualizer(opts) { id, type_regex, callback } Custom summary & child rows in VariablesDockWidget.
gl.dbg.set_rank_badge(rank, text, [severity, tooltip]) / clear_rank_badge(rank) severity: "info" | "success" | "warning" | "error" Sets/clears rank badge on ServerRackView.

6. gl.ui (Declarative Panels & 2D Retained-Mode Canvas), gl.marks, gl.regs, gl.diag

2D Canvas API Reference

Function Parameters Behavior & Event Payload
gl.ui.create_canvas(title_or_opts, [location]) title_or_opts: string title or { key, title, dock }; location: "bottom" (default docked tab), "right" (right rail), "dock" (docked bottom), or "popup" / "floating" (non-modal Qt::Tool window with draggable header & close button) Returns cid (panel_id). Floating "popup" dialogs automatically take keyboard focus on open.
gl.ui.canvas_draw(cid, cmds) cid: canvas ID, cmds: array of command tables Retained draw ops (op or type): "clear", "line", "polyline", "rect", "circle", "text". Supports { x, y, w, h } or { x0, y0, x1, y1 }, radius, stroke_width, color / rgba / stroke / fill (0xRRGGBBAA), filled = true, points = {{x, y}, ...}, text, font_pt.
gl.ui.canvas_heatmap(cid, grid2d, [opts]) cid: canvas ID, grid2d: 2D Lua array grid[row][col] of numbers, opts: { vmin, vmax, colormap = "viridis" | "plasma" | "coolwarm" | "grayscale" } Blits scalar matrix onto canvas with automatic zoom/pan and live hover (row, col, value) readout.
gl.ui.canvas_blit(cid, rgba_bytes, w, h) cid: canvas ID, rgba_bytes: raw w * h * 4 byte string or table, w, h: integer pixels Blits RGBA8888 image buffer directly to canvas.
gl.ui.canvas_on_click(cid, fn) cid: canvas ID, fn: function(ev) Fires on stationary left-click (< 4 px drag) with ev = { x, y, row, col, button, panel_id } (world coords + heatmap cell indices).
gl.ui.canvas_on_key(cid, fn) cid: canvas ID, fn: function(ev) Fires on focused canvas key press with ev = { key, code, modifiers, shift, ctrl, alt, panel_id } (e.g. ev.key == "Left", "Space", "a").

Other gl.ui, gl.marks, gl.regs, gl.diag Helpers

Function Signature / Description
gl.ui.create_panel(opts) / update_panel_rows(id, rows) / close_panel(id) Declarative "table", "tree", "text", "custom_buffer", or "canvas" panel.
gl.ui.open_popup(opts) / close_popup(id) Anchored text popup over editor.
gl.ui.set_status_segment(key, text, [opts]) / remove_status_segment(key) Clickable status-bar segment.
gl.ui.prompt_input(opts, cb) Non-blocking input dialog.
gl.marks.set / get / del, gl.regs.get / set, gl.diag.set / clear Buffer marks, named registers, and namespaced editor diagnostics.

7. Complete Runnable Examples

Example 1: Live GDB Stack & Memory Inspector (read_register + read_memory)

local cid = gl.ui.create_canvas("Live Stack & Memory Inspector", "popup")

local function render_lines(lines)
  local cmds = { { op = "clear", color = 0x1E1E2EFF } }
  for i, line in ipairs(lines) do
    cmds[#cmds + 1] = {
      op = "text",
      x = 16,
      y = 24 + (i - 1) * 20,
      text = line,
      rgba = (i == 1) and 0x89B4FAFF or 0xA6E3A1FF,
      font_pt = 10,
    }
  end
  gl.ui.canvas_draw(cid, cmds)
end

local function refresh_stack()
  local rank = gl.dbg.active_rank()
  gl.dbg.read_register(rank, "rsp", function(reg)
    if not reg.ok then
      render_lines({ "Rank " .. rank .. ": waiting (" .. reg.status .. ")" })
      return
    end
    local rsp_hex = string.format("0x%x", tonumber(reg.value) or 0)
    gl.dbg.read_memory(rank, rsp_hex, 32, function(mem)
      local hex = (mem.ok and mem.contents) or "(memory unreadable)"
      render_lines({
        string.format("Rank %d  RSP = %s", rank, rsp_hex),
        "Top 16B: " .. string.sub(hex, 1, 32),
        "Next 16B: " .. string.sub(hex, 33, 64),
      })
    end)
  end)
end

gl.autocmd.create("RankStopped", { pattern = "*", callback = refresh_stack })
refresh_stack()

Example 2: 2D Scalar Heatmap Visualizer (canvas_heatmap + canvas_on_click)

local cid = gl.ui.create_canvas("2D Thermal Field (Viridis)", "bottom")
local rows, cols = 32, 32
local grid = {}
for r = 1, rows do
  grid[r] = {}
  for c = 1, cols do
    local dx, dy = (c - cols / 2) / 8.0, (r - rows / 2) / 8.0
    grid[r][c] = math.exp(-(dx * dx + dy * dy))
  end
end

gl.ui.canvas_heatmap(cid, grid, { vmin = 0.0, vmax = 1.0, colormap = "viridis" })
gl.ui.canvas_on_click(cid, function(ev)
  local val = (grid[ev.row + 1] and grid[ev.row + 1][ev.col + 1]) or 0.0
  gl.api.log("info", string.format("Cell (%d, %d) = %.4f", ev.row, ev.col, val))
end)

Example 3: Interactive Timer + Click + Keyboard HUD (defer_fn + canvas_on_key)

local cid = gl.ui.create_canvas("Interactive HUD", "popup")
local px, py, tick = 120, 80, 0

local function render()
  gl.ui.canvas_draw(cid, {
    { op = "clear", color = 0x11111BFF },
    { op = "rect", x = px, y = py, w = 32, h = 32, rgba = 0x89B4FAFF, filled = true },
    { op = "text", x = 12, y = 20, text = "Tick: " .. tick, rgba = 0xCDD6F4FF, font_pt = 10 },
  })
end

local function step()
  tick = tick + 1
  render()
  gl.api.defer_fn(250, step)
end

gl.ui.canvas_on_click(cid, function(ev) px, py = ev.x - 16, ev.y - 16; render() end)
gl.ui.canvas_on_key(cid, function(ev)
  if ev.key == "Left" then px = px - 12 elseif ev.key == "Right" then px = px + 12 end
  if ev.key == "Up" then py = py - 12 elseif ev.key == "Down" then py = py + 12 end
  render()
end)

step()

Clone this wiki locally