Pular para o conteúdo

Exemplos

O repositório do Rusty traz dez mods prontos: o mod de cinco minutos hello (em docs/mods-template/hello/) e nove exemplos em docs/mods-examples/. Esta página mostra o código completo de cada um, como instalá-lo e o que cada parte faz.

  1. Copie a pasta do mod para %APPDATA%\Rusty\mods\. O nome da pasta é o nome do mod e tem de ser igual ao campo name do mod.ini.
  2. Acrescente o nome em [mods] enabled no rusty.conf:
[mods]
enabled = hello
  1. Salve. O Rusty carrega o mod sem reiniciar.
  2. Abra %LOCALAPPDATA%\Rusty\mods.log e procure linhas do mod. Uma linha [host] disabled: ... diz por que ele não está rodando.

O passo a passo completo está em Seu primeiro mod; os campos do mod.ini, em Manifesto e estrutura.

Exemplo Permissões Estado hoje
hello nenhuma roda por inteiro
auto-tab-title nenhuma falta só pane.process_name
clock nenhuma roda; só o config_reloaded falha (falta ev.changed)
command-duration nenhuma roda; o segundo argumento de notify é ignorado
copy-last-output clipboard falta só as opções de notify
git-branch fs_read falha: usa fs.* (a barra de status existe)
kitchen-sink clipboard falha: usa config.get, theme.*, ui.* e as opções de notify
quick-snippets spawn falta só ui.overlay
theme-by-time nenhuma falta só theme.set
url-highlight nenhuma falha na carga: regex.compile, ui.highlight e as opções de notify

O que faz. O mod inicial. Escreve uma linha no log quando uma aba abre, conta as abas no armazenamento do mod (o número sobrevive a um reinício) e mostra um aviso a cada dez abas. Usa só funções que existem hoje e não pede permissão.

Como instalar. Copie docs/mods-template/hello/ para %APPDATA%\Rusty\mods\hello\ e habilite com enabled = hello. Abra uma aba nova e confira o mods.log: aparecem hello [info] loaded hello 1.0.0, api 1 e hello [info] tab 1 opened, 1 in total. A contagem fica em %LOCALAPPDATA%\Rusty\mod-data\hello\store.txt.

# hello: the starter mod. Copy this folder to %APPDATA%\Rusty\mods\hello\ and add
# `hello` to [mods] enabled in rusty.conf. The folder name must equal `name`.
# Every key is explained in docs/MODDING.md, section 3.
name = hello
version = 1.0.0
author = Rusty docs
description = Logs each new tab, counts them, and notifies every tenth one.
main = init.luau
api = 1
# Optional. Defaults shown: no permissions, 8 MB of memory, 20 ms per callback.
# permissions = clipboard, fs_read, spawn, pane_text
# memory_mb = 8
# time_ms = 20
-- hello: the starter mod for Rusty.
--
-- What it does:
-- * writes a line to %LOCALAPPDATA%\Rusty\mods.log when a tab opens;
-- * counts the tabs in its own store, so the count survives a restart;
-- * shows a notice every tenth tab.
--
-- It uses only functions the host registers today (docs/MODDING.md, section 5).
-- Save this file while Rusty runs and the mod reloads by itself.
-- rusty.mod.info() returns this mod's name, version, folder and API level.
local info = rusty.mod.info()
rusty.log("loaded " .. info.name .. " " .. info.version .. ", api " .. rusty.api.version())
-- Runs when the mod loads, and again after each reload.
rusty.on("startup", function()
local count = rusty.store.get("tabs") or 0
rusty.log("startup: " .. count .. " tabs counted so far")
end)
-- Runs for every tab the user opens. ev.tab is the number of the new tab.
rusty.on("tab_opened", function(ev)
local count = (rusty.store.get("tabs") or 0) + 1
rusty.store.set("tabs", count)
rusty.log("tab " .. ev.tab .. " opened, " .. count .. " in total")
if count % 10 == 0 then
rusty.notify(count .. " tabs opened so far")
end
end)
  • mod.ini. Os quatro campos obrigatórios (name, version, main, api = 1) mais author e description. As linhas comentadas no fim mostram as chaves opcionais com os valores padrão: sem permissions, 8 MB de memória e 20 ms por chamada. name é hello, igual à pasta.
  • Cabeçalho do init.luau. rusty.mod.info() devolve uma tabela com name, version, dir e api; rusty.api.version() devolve 1. O mod os junta numa linha de log ao ser carregado.
  • startup. Dispara depois da carga e depois de cada recarga. O mod lê o contador com rusty.store.get("tabs") or 0 (a primeira vez a chave não existe e a leitura dá nil) e o registra.
  • tab_opened. A cada aba nova, soma um ao contador, grava com rusty.store.set e escreve o número da aba (ev.tab) e o total no log.
  • count % 10 == 0. A cada dez abas chama rusty.notify. Nesta versão o aviso pisca o botão do Rusty na barra de tarefas quando a janela não está na frente; não há caixa de aviso.
  • Salve o init.luau com o Rusty aberto: o mod recarrega e a próxima linha de log já usa o texto novo.

O que faz. Faz o título de cada aba seguir o programa em execução e, com o shell parado, o nome da pasta atual. Um título cortado em max_length células ganha reticências.

Como instalar. Copie docs/mods-examples/auto-tab-title/ para %APPDATA%\Rusty\mods\auto-tab-title\. rusty.tab.set_title, rusty.timer.after, rusty.timer.cancel, rusty.str.truncate, rusty.path.basename e rusty.settings.get existem hoje; só rusty.pane.process_name não. A chamada a ela, 150 ms depois de cada command_started, falha com attempt to call a nil value, e esse erro conta para o limite de 5 erros em 60 segundos.

name = auto-tab-title
version = 1.0.0
author = Rusty examples
description = Tab titles follow the running program, or the folder name when idle.
main = init.luau
api = 1
memory_mb = 8
time_ms = 20
[setting.max_length]
type = int
default = 24
min = 8
max = 60
label = Maximum length
description = Longest tab title, in cells. Longer titles are cut with an ellipsis.
-- Needs phase 2: rusty.pane.process_name is not registered yet (docs/MODS.md, 9.0). The file compiles;
-- calls to them fail when they run.
-- Tab titles: the running program while a command runs, otherwise the folder name.
-- A title set here overrides the title the program sets with OSC 0/2, until this mod clears it
-- (rusty.tab.set_title(tab, nil)).
local busy = {} -- pane id -> true while a command runs
local pending = {} -- pane id -> timer that reads the program name after the command starts
local function folder_name(cwd: string?): string?
if cwd == nil then
return nil
end
local trimmed = string.gsub(cwd, "[\\/]+$", "")
return rusty.path.basename(trimmed)
end
local function apply(tab: number, title: string?)
if title ~= nil then
title = rusty.str.truncate(title, rusty.settings.get("max_length"), "…")
end
rusty.tab.set_title(tab, title)
end
local function cancel_pending(pane: number)
if pending[pane] then
rusty.timer.cancel(pending[pane])
pending[pane] = nil
end
end
rusty.on("command_started", function(ev)
busy[ev.pane] = true
cancel_pending(ev.pane)
-- The program is not running yet when the shell sends OSC 133;C: look again shortly.
pending[ev.pane] = rusty.timer.after(150, function()
pending[ev.pane] = nil
local info = rusty.pane.info(ev.pane)
if info == nil then
return
end
local program = rusty.pane.process_name(ev.pane)
if program ~= nil then
program = string.gsub(program, "%.exe$", "")
end
apply(ev.tab, program or folder_name(info.cwd))
end)
end)
rusty.on("command_finished", function(ev)
busy[ev.pane] = nil
cancel_pending(ev.pane)
local info = rusty.pane.info(ev.pane)
if info then
apply(ev.tab, folder_name(info.cwd))
end
end)
rusty.on("cwd_changed", function(ev)
if not busy[ev.pane] then
apply(ev.tab, folder_name(ev.cwd))
end
end)
rusty.on("pane_closed", function(ev)
busy[ev.pane] = nil
cancel_pending(ev.pane)
end)
  • [setting.max_length]. Uma configuração do mod: número inteiro de 8 a 60, padrão 24, com rótulo e descrição para a tela de configurações. O mod.ini com [setting.*] é aceito, e o valor se lê com rusty.settings.get.
  • busy e pending. Tabelas indexadas pelo número do painel: busy diz se há um comando em execução; pending guarda o número do timer que vai descobrir o nome do programa.
  • folder_name. Tira as barras do fim de cwd e devolve o último trecho com rusty.path.basename. rusty.path.basename existe hoje.
  • apply. Corta o título com rusty.str.truncate e o aplica com rusty.tab.set_title(tab, title); com nil, o título volta a ser o que o programa define.
  • command_started. Marca o painel como ocupado e, 150 ms depois (o programa ainda não está rodando quando o shell avisa), pergunta o nome do programa. O rusty.timer.after devolve o número do timer, e rusty.timer.cancel(número) o cancela (se o comando acaba antes dos 150 ms, o timer é cancelado).
  • command_finished, cwd_changed, pane_closed. Voltam ao nome da pasta, atualizam o título quando o shell muda de pasta fora de um comando e limpam o estado de um painel fechado.
  • O que você consegue hoje: tudo, menos o nome do programa. Sem rusty.pane.process_name, o mod não descobre qual programa roda. Com rusty.pane.info(pane).title, o título que o programa definiu, dá para fazer algo parecido (veja Painéis e texto).

O que faz. Mostra a hora local à direita da barra de status, em formato de 24 ou 12 horas, com ou sem segundos. É o exemplo de timer opt-in: ele existe só enquanto o mod está habilitado e pausa com a janela sem foco (sem background).

Como instalar. Copie docs/mods-examples/clock/ para %APPDATA%\Rusty\mods\clock\. rusty.ui.status.segment, rusty.timer.every, rusty.timer.cancel, rusty.time.format e rusty.settings.get existem, então o relógio aparece na barra de status. Veja Barra de status e decoração de abas.

name = clock
version = 1.0.0
author = Rusty examples
description = Shows the local time in the status bar. Uses an opt-in timer.
main = init.luau
api = 1
memory_mb = 4
time_ms = 5
[setting.format]
type = choice
default = 24h
options = 24h, 12h
label = Time format
description = 24-hour or 12-hour clock.
[setting.show_seconds]
type = bool
default = false
label = Show seconds
description = Shows seconds and refreshes every second instead of every five seconds.
-- Clock segment on the right of the status bar.
-- The timer is the only timer of this mod. It exists only while the mod is enabled,
-- and the API pauses it while the window is unfocused or minimized.
local timer = nil
local function tick()
local pattern = if rusty.settings.get("format") == "12h" then "%I:%M" else "%H:%M"
if rusty.settings.get("show_seconds") then
pattern = pattern .. ":%S"
end
rusty.ui.status.segment{
id = "clock",
text = rusty.time.format(pattern),
color = "muted",
align = "right",
}
end
local function start()
if timer then
rusty.timer.cancel(timer)
end
tick()
local interval = if rusty.settings.get("show_seconds") then 1000 else 5000
timer = rusty.timer.every(interval, tick)
end
rusty.on("startup", start)
rusty.on("config_reloaded", function(ev)
for _, key in ev.changed do
if string.find(key, "mods.clock.", 1, true) == 1 then
start()
return
end
end
end)
rusty.on("shutdown", function()
if timer then
rusty.timer.cancel(timer)
timer = nil
end
end)
  • mod.ini. Pede só 4 MB de memória e 5 ms por chamada (memory_mb = 4, time_ms = 5): um mod leve declara limites menores que os padrões. As duas configurações são uma escolha (24h ou 12h) e um booleano.
  • tick. Escolhe o padrão de formato (%H:%M ou %I:%M), acrescenta :%S se mostrar segundos e atualiza o segmento clock, alinhado à direita, com rusty.ui.status.segment{...}.
  • start. Cancela o timer anterior, atualiza a hora e cria rusty.timer.every(interval, tick): 1000 ms com segundos, 5000 ms sem. O número que o every devolve fica em timer, e rusty.timer.cancel(timer) o cancela.
  • startup, config_reloaded, shutdown. Inicia na carga, reinicia o timer se o usuário mudar uma configuração mods.clock.* e cancela o timer ao sair. Hoje os três eventos existem, mas config_reloaded ainda não traz ev.changed (é planejado): o laço for _, key in ev.changed falha quando a configuração é recarregada, e o erro conta para a desativação do mod (5 em 60 segundos). O relógio continua com as configurações da carga.
  • O que você consegue hoje: o relógio, o timer e o segmento na barra de status funcionam. Só a troca de configuração com o mod ligado não é refeita: salve o init.luau (o mod recarrega) para aplicar uma nova configuração.

O que faz. Quando um comando longo termina numa aba que você não está olhando, deixa um distintivo nessa aba (a duração, verde se deu certo, vermelho se falhou) até você voltar a ela, e avisa com a duração e o código de saída.

Como instalar. Copie docs/mods-examples/command-duration/ para %APPDATA%\Rusty\mods\command-duration\. rusty.pane.info, rusty.str.truncate, rusty.settings.get, rusty.ui.tab.decorate e rusty.ui.tab.clear existem. O segundo argumento de rusty.notify é ignorado: o aviso só pisca o botão na barra de tarefas.

name = command-duration
version = 1.0.0
author = Rusty examples
description = Badges a background tab when a long command ends, and notifies with the duration.
main = init.luau
api = 1
memory_mb = 8
time_ms = 20
[setting.threshold_s]
type = int
default = 30
min = 1
max = 3600
label = Threshold (seconds)
description = Commands that ran at least this long get a badge and a notification.
[setting.notify]
type = bool
default = true
label = Notify
description = Shows a notification when a long command ends in a background tab.
-- Needs phase 2: rusty.ui.tab.clear, rusty.ui.tab.decorate, rusty.notify(text, opts) are not registered yet (docs/MODS.md, 9.0). The file compiles;
-- calls to them fail when they run.
-- Command duration badge.
-- A long command that ends in a tab the user is not looking at leaves a badge on that tab
-- (its duration, green on success, red on failure) until the tab is focused again.
-- The built-in shell_integration.notify_after_secs only flashes the taskbar; this adds the badge
-- and a notification with the duration and the exit code.
local badged = {} -- tab id -> true while its badge is shown
local function format_duration(ms: number): string
local seconds = math.floor(ms / 1000)
if seconds < 60 then
return seconds .. "s"
end
if seconds < 3600 then
return math.floor(seconds / 60) .. "m" .. (seconds % 60) .. "s"
end
return math.floor(seconds / 3600) .. "h" .. math.floor((seconds % 3600) / 60) .. "m"
end
rusty.on("command_finished", function(ev)
local duration = ev.duration_ms
if duration == nil or duration < rusty.settings.get("threshold_s") * 1000 then
return
end
local info = rusty.pane.info(ev.pane)
if info == nil or info.visible then
return -- the user is looking at this tab
end
local failed = ev.exit_code ~= nil and ev.exit_code ~= 0
local text = format_duration(duration)
rusty.ui.tab.decorate(ev.tab, {
color = if failed then "error" else "success",
badge = rusty.str.truncate(text, 4),
})
badged[ev.tab] = true
if rusty.settings.get("notify") then
local summary = if failed
then string.format("Failed with exit code %d after %s", ev.exit_code, text)
else string.format("Finished in %s", text)
rusty.notify(summary, {
level = if failed then "error" else "info",
pane = ev.pane,
})
end
end)
local function clear_badge(tab: number)
if badged[tab] then
rusty.ui.tab.clear(tab)
badged[tab] = nil
end
end
rusty.on("tab_focused", function(ev)
clear_badge(ev.tab)
end)
rusty.on("tab_closed", function(ev)
badged[ev.tab] = nil
end)
  • Comentário de abertura. Diz que a configuração interna shell_integration.notify_after_secs só pisca a barra de tarefas; o mod acrescenta o distintivo e a notificação.
  • format_duration. Transforma milissegundos em 45s, 3m20s ou 1h5m. É Luau puro e funciona em qualquer versão.
  • command_finished. Ignora comandos abaixo do limite (threshold_s vezes 1000), pergunta com rusty.pane.info se a aba está visível, calcula failed a partir de ev.exit_code e decora a aba com rusty.ui.tab.decorate (faixa verde ou vermelha e a duração como emblema, até 4 células). Depois chama rusty.notify(summary, { level, pane }); hoje o segundo argumento é ignorado.
  • tab_focused. Ao entrar na aba, rusty.ui.tab.clear tira o distintivo. badged lembra de quais abas têm um.
  • tab_closed. Esquece a aba fechada.
  • O que você consegue hoje: o distintivo na aba funciona, com ev.duration_ms e ev.exit_code. A receita Avisar quando um comando longo termina mostra só o aviso. A marca some quando você volta à aba, quando ela fecha ou quando os mods reiniciam.

O que faz. Acrescenta um item à paleta de comandos que copia a saída do último comando sem as linhas em branco das pontas e diz quantas linhas copiou. A ação nativa copy_last_output copia a saída como ela é.

Como instalar. Copie docs/mods-examples/copy-last-output/ para %APPDATA%\Rusty\mods\copy-last-output\. rusty.ui.palette.add, rusty.clipboard.set e rusty.pane.last_output existem hoje, então o item aparece na paleta como copy-last-output: .... Falta só o segundo argumento de rusty.notify ({ level = ... }), que é ignorado. O mod.ini pede só clipboard, mas rusty.pane.last_output exige pane_text: para o mod funcionar, declare permissions = clipboard, pane_text.

name = copy-last-output
version = 1.0.0
author = Rusty examples
description = Palette entry that copies the last command output without its blank edge lines.
main = init.luau
api = 1
permissions = clipboard
memory_mb = 8
time_ms = 20
-- Needs phase 2: rusty.notify(text, opts) are not registered yet (docs/MODS.md, 9.0). The file compiles;
-- calls to them fail when they run.
-- Palette entry: copies the output of the last command, without blank lines at its edges.
-- The built-in copy_last_output action copies the output as it is; this one trims it and
-- reports how many lines it copied.
local function trim_blank_edges(text: string): string
local lines = {}
for line in string.gmatch(text .. "\n", "(.-)\r?\n") do
table.insert(lines, line)
end
local first, last = 1, #lines
while first <= last and string.match(lines[first], "^%s*$") do
first += 1
end
while last >= first and string.match(lines[last], "^%s*$") do
last -= 1
end
return table.concat(lines, "\n", first, last)
end
rusty.ui.palette.add{
id = "copy-last-output",
title = "Copy last command output (trimmed)",
keywords = "copy output clipboard",
run = function()
local output = rusty.pane.last_output()
if output == nil then
rusty.notify("No finished command in this pane yet.", { level = "warn" })
return
end
local text = trim_blank_edges(output)
if text == "" then
rusty.notify("The last command printed nothing.")
return
end
if rusty.clipboard.set(text) then
local _, newlines = string.gsub(text, "\n", "")
rusty.notify("Copied " .. (newlines + 1) .. " lines.")
else
rusty.notify("The clipboard is not available.", { level = "error" })
end
end,
}
  • mod.ini. permissions = clipboard: o mod escreve na área de transferência. É um exemplo sem [setting.*].
  • trim_blank_edges. Separa o texto em linhas (aceitando \r\n), anda do começo e do fim enquanto a linha é só espaço e junta o meio com table.concat(lines, "\n", first, last). Luau puro, funciona hoje.
  • rusty.ui.palette.add{...}. Registra o item copy-last-output na paleta, com título, palavras-chave e a função run. As palavras-chave são aceitas e ignoradas. Na paleta o item aparece como copy-last-output: título.
  • run. Lê a saída com rusty.pane.last_output() (exige pane_text), avisa se não há comando ou se saiu vazio, copia com rusty.clipboard.set e conta as linhas com string.gsub. A forma rusty.notify(texto, { level = ... }) é planejada.
  • O que você consegue hoje: rusty.action("copy_last_output") copia a saída bruta, com clipboard. A receita Copiar a saída do último comando com uma tecla liga isso a uma tecla.

O que faz. Mostra o ramo do Git do painel focado na barra de status, lendo .git/HEAD dentro das pastas do projeto. Com HEAD solto, mostra o começo do hash do commit.

Como instalar. Copie docs/mods-examples/git-branch/ para %APPDATA%\Rusty\mods\git-branch\. A barra de status existe (rusty.ui.status.segment e rusty.ui.status.remove), mas rusty.fs.* não, e fs_read só libera links file:. rusty.pane.info e rusty.path.join existem.

name = git-branch
version = 1.0.0
author = Rusty examples
description = Shows the git branch of the focused pane in the status bar.
main = init.luau
api = 1
permissions = fs_read
memory_mb = 8
time_ms = 20
[setting.position]
type = choice
default = right
options = left, right
label = Position
description = Side of the status bar where the branch is shown.
[setting.sha_length]
type = int
default = 7
min = 4
max = 12
label = Commit length
description = Characters of the commit shown when HEAD is detached.
-- Needs phase 2: rusty.fs.find_up, rusty.fs.kind, rusty.fs.read are not registered yet (docs/MODS.md, 9.0). The file compiles;
-- calls to them fail when they run.
-- Git branch segment for the focused pane.
-- Reads .git/HEAD inside the project folders (fs_read). Nothing is written.
local function branch_label(cwd: string): string?
local git = rusty.fs.find_up(".git", cwd)
if git == nil then
return nil
end
if rusty.fs.kind(git) ~= "dir" then
-- linked worktrees and submodules keep their HEAD outside the project folder
return "worktree"
end
local head = rusty.fs.read(rusty.path.join(git, "HEAD"))
if head == nil then
return nil
end
local branch = string.match(head, "^ref: refs/heads/(.-)%s*$")
if branch then
return branch
end
local sha = string.match(head, "^(%x+)")
if sha then
return string.sub(sha, 1, rusty.settings.get("sha_length"))
end
return nil
end
local function refresh()
local info = rusty.pane.info()
local label = if info and info.cwd then branch_label(info.cwd) else nil
if label == nil then
rusty.ui.status.remove("git-branch")
return
end
rusty.ui.status.segment{
id = "git-branch",
text = "⎇ " .. label,
color = "accent",
align = rusty.settings.get("position"),
}
end
rusty.on("startup", refresh)
rusty.on("pane_focused", refresh)
rusty.on("tab_focused", refresh)
rusty.on("cwd_changed", refresh)
rusty.on("command_finished", refresh) -- `git checkout` changes HEAD
  • mod.ini. permissions = fs_read: só leitura de arquivos, nada é escrito. As configurações escolhem o lado da barra e o tamanho do hash (4 a 12).
  • branch_label. Procura .git subindo as pastas com rusty.fs.find_up, trata a pasta que não é um diretório (worktrees e submódulos) como "worktree", lê HEAD com rusty.fs.read e extrai o ramo com string.match(head, "^ref: refs/heads/(.-)%s*$"). Os padrões de texto são Luau puro.
  • refresh. Pergunta a pasta do painel com rusty.pane.info(), calcula o rótulo e mostra ou remove o segmento git-branch.
  • Quando atualiza. Em startup, pane_focused, tab_focused, cwd_changed e command_finished (um git checkout muda o HEAD).
  • O que você consegue hoje: os eventos existem, cwd_changed traz ev.cwd e a barra de status está pronta para mostrar o ramo, mas o mod não tem como ler o arquivo .git/HEAD, então falha ao chamar rusty.fs.find_up. O prompt do Rusty já mostra o ramo do Git.

O que faz. Um bloco pequeno para cada área da API, na ordem: configurações, armazenamento, popup com widgets, segmento de status, gancho de teclas, atalho registrado, tema, item de menu de contexto, destaque por expressão regular, troca de glifo e item de paleta. Serve de mapa da API completa do projeto.

Como instalar. Copie docs/mods-examples/kitchen-sink/ para %APPDATA%\Rusty\mods\kitchen-sink\. rusty.keys.bind, rusty.ui.palette.add, rusty.settings.get, rusty.store.*, rusty.clipboard.set e rusty.time.format existem. Ainda são planejados rusty.config.get, rusty.theme.*, rusty.ui.overlay, rusty.ui.status, rusty.ui.context_menu, rusty.ui.highlight, rusty.ui.glyph e as opções de rusty.notify. O init.luau chega a rusty.theme.register na carga, e o mod é desativado ali, com um erro de chamada a valor nil. A tabela rusty.ui existe, mas só com palette.

name = kitchen-sink
version = 1.0.0
author = Rusty examples
description = One example per API area: settings, status bar, store, keys, themes, menus, overlay.
main = init.luau
api = 1
permissions = clipboard
memory_mb = 12
time_ms = 20
[setting.greeting]
type = text
default = hello from kitchen-sink
max_length = 40
label = Greeting
description = Text shown in the status bar and at the top of the panel.
[setting.accent]
type = color
default = #e8743b
label = Status colour
description = Colour of the status bar segment.
[setting.level]
type = int
default = 3
min = 1
max = 10
label = Level
description = A number shown in the status bar.
[setting.ratio]
type = float
default = 0.5
min = 0
max = 1
label = Ratio
description = Value of the progress bar in the panel.
[setting.mode]
type = choice
default = compact
options = compact, full
label = Panel layout
description = Compact shows the basics; full adds the note field.
[setting.verbose]
type = bool
default = false
label = Verbose log
description = Writes every key press to mods.log.
-- Needs phase 2: rusty.config.get, rusty.theme.register, rusty.theme.set, rusty.ui, rusty.notify(text, opts) are not registered yet (docs/MODS.md, 9.0). The file compiles;
-- calls to them fail when they run.
-- Kitchen sink: one small block per API area. Read it from top to bottom.
local ui = rusty.ui
local panel = nil -- the open overlay, if any
-- 1. Settings and read-only config. Mod settings come from [mods.kitchen-sink] in rusty.conf.
local function describe(): string
return string.format("%s level %d font %s pt",
rusty.settings.get("greeting"),
rusty.settings.get("level"),
tostring(rusty.config.get("font.size")))
end
-- 2. Persistent store: how many times the panel was opened, kept across restarts.
local function bump_count(): number
local n = (rusty.store.get("opened") or 0) + 1
rusty.store.set("opened", n)
return n
end
-- 3. Overlay with a widget tree. Ids keep focus and typed text when the tree is updated.
local function panel_root()
local ratio = rusty.settings.get("ratio")
local children = {
ui.Text{ text = rusty.settings.get("greeting"), style = "accent" },
ui.Row{
gap = 2,
children = {
ui.Text{ text = "Opened " .. tostring(rusty.store.get("opened") or 0) .. " times" },
ui.Spacer{ size = 1 },
ui.Text{ text = rusty.time.format("%H:%M"), style = "muted" },
},
},
ui.Progress{
id = "ratio",
value = ratio,
label = string.format("%d%%", math.floor(ratio * 100)),
},
ui.List{
id = "actions",
height = 4,
items = {
{ id = "copy", label = "Copy stats", detail = "clipboard" },
{ id = "notify", label = "Send a test notification" },
{ id = "theme", label = "Switch to kitchen-dusk", detail = "theme" },
{ id = "close", label = "Close" },
},
},
}
if rusty.settings.get("mode") == "full" then
table.insert(children, ui.Input{ id = "note", placeholder = "Note (logged on Enter)" })
end
return ui.Column{ gap = 1, children = children }
end
local function panel_event(ev)
if ev.type == "activate" and ev.id == "actions" then
if ev.value == "copy" then
rusty.clipboard.set(describe())
elseif ev.value == "notify" then
rusty.notify("Test from kitchen-sink", { title = "Kitchen sink", level = "info" })
elseif ev.value == "theme" then
rusty.theme.set("kitchen-dusk")
elseif ev.value == "close" and panel then
panel:close()
end
elseif ev.type == "submit" and ev.id == "note" then
rusty.log("note: " .. ev.value)
elseif ev.type == "close" then
panel = nil
end
end
local function open_panel()
bump_count()
if panel ~= nil then
return
end
panel = ui.overlay.open{
id = "kitchen-panel",
title = "Kitchen sink",
width = 64,
height = 16,
root = panel_root(),
on_event = panel_event,
}
end
-- 4. Status segment: colour and text from settings, click opens the panel.
local function refresh_status()
ui.status.segment{
id = "kitchen",
text = describe(),
color = rusty.settings.get("accent"),
align = "right",
tooltip = "Open the kitchen-sink panel",
on_click = open_panel,
}
end
rusty.on("startup", refresh_status)
rusty.on("config_reloaded", refresh_status)
-- 5. Key hook: runs before the terminal sees the key. "consume" swallows it.
-- Here F12 is swallowed (the program in the pane never receives it), and every key is
-- logged when the verbose setting is on.
rusty.on("key", function(ev)
if rusty.settings.get("verbose") then
rusty.log("key " .. ev.key .. (if ev.ctrl then " ctrl" else ""))
end
if ev.key == "f12" then
return "consume"
end
return nil
end)
-- 6. Key binding. It is refused, with a log line, when [keys] already uses the chord.
rusty.keys.bind("ctrl+alt+k", open_panel)
-- 7. Theme: registered themes join the theme list while this mod is enabled.
rusty.theme.register("kitchen-dusk", {
background = "#1b1a24",
foreground = "#e6e1f0",
cursor = "#e8743b",
selection = "#3b3650",
palette = {
"#1b1a24", "#e06c75", "#98c379", "#e5c07b",
"#61afef", "#c678dd", "#56b6c2", "#abb2bf",
"#5c6370", "#ff7b86", "#b0e592", "#f0d58c",
"#7fc3ff", "#e09cf0", "#7ad8e4", "#e6e1f0",
},
})
-- 8. Context menu item: shown on right click in every pane.
ui.context_menu.add{
id = "copy-stats",
title = "Copy kitchen-sink stats",
when = "always",
run = function()
rusty.clipboard.set(describe() .. " opened " .. tostring(rusty.store.get("opened") or 0))
end,
}
-- 9. Cell highlight by regex (alternation) and glyph replacement (display only, one cell).
ui.highlight.add{
id = "todo",
pattern = "TODO|FIXME",
style = { bold = true, fg = "warning" },
}
ui.glyph.replace{ from = 0x2192, text = ">" }
-- 10. Palette entry, with a notification and a log line.
ui.palette.add{
id = "open-panel",
title = "Open the panel",
keywords = "kitchen panel demo",
run = function()
open_panel()
rusty.log("panel opened from the palette", "warn")
end,
}
rusty.on("startup", function()
rusty.log("kitchen-sink loaded, API " .. tostring(rusty.api.version()))
end)
  • mod.ini. permissions = clipboard e memory_mb = 12. As seis configurações mostram todos os tipos previstos: text, color, int, float, choice e bool.
  • 1. Configurações. rusty.settings.get existe; rusty.config.get (leitura do rusty.conf) é planejada.
  • 2. Armazenamento. bump_count conta quantas vezes o painel abriu com rusty.store.get e rusty.store.set. Esta parte roda hoje.
  • 3. Popup. ui.overlay.open com uma árvore de widgets (Text, Row, Spacer, Progress, List, Input) e on_event para activate, submit e close. Os id preservam o foco e o texto digitado quando a árvore é atualizada.
  • 4. Segmento de status. ui.status.segment com cor vinda de uma configuração, dica e on_click.
  • 5. Gancho de teclas. rusty.on("key", ...) que consome f12 e, com verbose, registra cada tecla. Esta parte roda hoje, exceto a leitura da configuração.
  • 6. Atalho registrado. rusty.keys.bind("ctrl+alt+k", open_panel). Existe: o Rusty a recusa com um erro se o [keys] do usuário ou outro mod já usa a combinação. Como o mod falha logo depois, o atalho some com ele.
  • 7 a 10. Tema, menu, destaques e paleta. rusty.theme.register, ui.context_menu.add, ui.highlight.add e ui.glyph.replace são planejadas. ui.palette.add existe: o item aparece na paleta como kitchen-sink: título.
  • Fim. Um startup escreve no log kitchen-sink loaded, API 1.

O que faz. Ctrl+Alt+S (ou um item da paleta) abre um popup com uma lista filtrável de trechos de comando. Enter digita o trecho escolhido no painel focado, com ou sem Enter no fim.

Como instalar. Copie docs/mods-examples/quick-snippets/ para %APPDATA%\Rusty\mods\quick-snippets\. rusty.keys.bind e rusty.ui.palette.add existem: o mod carrega, Ctrl+Alt+S fica ligado e o item aparece na paleta como quick-snippets: .... Mas rusty.ui.overlay.open, que mostra o popup, não existe: ao apertar a tecla ou escolher o item, a função falha com attempt to index nil e o erro conta para o limite de 5 em 60 segundos.

name = quick-snippets
version = 1.0.0
author = Rusty examples
description = Popup with a filterable list of snippets; Enter types the chosen one into the pane.
main = init.luau
api = 1
permissions = spawn
memory_mb = 8
time_ms = 20
[setting.press_enter]
type = bool
default = false
label = Press Enter after typing
description = Sends Enter after the snippet, so it runs at once. Off by default.
-- Needs phase 2: rusty.ui, rusty.ui.overlay.open are not registered yet (docs/MODS.md, 9.0). The file compiles;
-- calls to them fail when they run.
-- Quick snippets: Ctrl+Alt+S (or the palette entry) opens a popup with a filterable list.
-- Enter types the chosen snippet into the focused pane. Typing is an action of the program
-- running in the pane, so this mod asks for the spawn permission.
local SNIPPETS = {
{ id = "git-status", label = "git status -sb", text = "git status -sb" },
{ id = "git-log", label = "git log --oneline -20", text = "git log --oneline -20" },
{ id = "cargo-test", label = "cargo test", text = "cargo test" },
{ id = "dir-hidden", label = "List hidden files", text = "Get-ChildItem -Force" },
{ id = "ps-version", label = "PowerShell version", text = "$PSVersionTable" },
{ id = "clear", label = "Clear screen", text = "Clear-Host" },
}
local overlay = nil
local focused_pane = nil -- from pane_focused: where send_text types
rusty.on("pane_focused", function(ev) focused_pane = ev.pane end)
local filter = ""
local function find_snippet(id: string)
for _, s in SNIPPETS do
if s.id == id then
return s
end
end
return nil
end
local function visible_items()
local items = {}
local needle = string.lower(filter)
for _, s in SNIPPETS do
if needle == "" or string.find(string.lower(s.label), needle, 1, true) then
table.insert(items, { id = s.id, label = s.label, detail = s.text })
end
end
return items
end
local function root()
local ui = rusty.ui
return ui.Column{
gap = 1,
children = {
ui.Input{ id = "filter", placeholder = "Filter snippets" },
ui.List{ id = "list", items = visible_items(), height = 8 },
},
}
end
local function handle(ev)
if ev.type == "change" and ev.id == "filter" then
filter = ev.value
overlay:set(root())
elseif ev.type == "activate" and ev.id == "list" then
local snippet = find_snippet(ev.value)
overlay:close()
if snippet then
local text = snippet.text
if rusty.settings.get("press_enter") then
text = text .. "\n" -- a newline is sent as Enter
end
if focused_pane then
rusty.pane.send_text(text, focused_pane)
end
end
elseif ev.type == "close" then
overlay = nil
filter = ""
end
end
local function open()
if overlay ~= nil then
return
end
overlay = rusty.ui.overlay.open{
id = "snippets",
title = "Snippets",
width = 60,
height = 14,
root = root(),
on_event = handle,
}
end
rusty.keys.bind("ctrl+alt+s", open)
rusty.ui.palette.add{
id = "open-snippets",
title = "Open snippets",
keywords = "snippet type insert",
run = open,
}
  • mod.ini. permissions = spawn: digitar num painel executa comandos, por isso é tratado como executar.
  • SNIPPETS. Uma lista de tabelas com id, label e text. Só Luau.
  • focused_pane. Guarda o painel focado a partir do evento pane_focused (ev.pane). É o padrão certo para esta versão, onde não há função que devolva o painel focado.
  • visible_items, root e handle. Filtram a lista pelo texto digitado, montam a árvore de widgets e tratam os eventos change, activate e close do popup. Planejados.
  • Digitar o trecho. rusty.pane.send_text(text, focused_pane) existe hoje. Atenção: o exemplo acrescenta "\n" (comentário: “a newline is sent as Enter”), mas esta versão escreve os bytes como estão, e Enter é "\r". Veja rusty.pane.send_text.
  • rusty.keys.bind e rusty.ui.palette.add. Abrem o popup. As duas existem (veja Teclas e paleta); só o popup é planejado. O campo keywords do item é aceito e ignorado.
  • O que você consegue hoje: ligar o atalho, pôr itens na paleta e digitar no painel. Falta o popup: um item de paleta por trecho (rusty.ui.palette.add com um id por item) faz o papel da lista. A receita Digitar um comando com uma tecla usa o mesmo send_text.

O que faz. Troca o tema de cores pela hora local: um tema de dia e um de noite, com a hora de início e a de fim configuráveis (o dia pode atravessar a meia-noite).

Como instalar. Copie docs/mods-examples/theme-by-time/ para %APPDATA%\Rusty\mods\theme-by-time\. rusty.timer.every, rusty.time.now e rusty.settings.get existem; rusty.theme.set não, e a chamada falha com attempt to index nil with 'set'.

name = theme-by-time
version = 1.0.0
author = Rusty examples
description = Switches the colour theme at the start and end of the day, by local time.
main = init.luau
api = 1
memory_mb = 8
time_ms = 20
[setting.day_start]
type = int
default = 7
min = 0
max = 23
label = Day starts at (hour)
description = Local hour, 0 to 23, when the day theme starts.
[setting.day_end]
type = int
default = 19
min = 0
max = 23
label = Day ends at (hour)
description = Local hour, 0 to 23, when the night theme starts. Can be lower than the start hour.
[setting.day_theme]
type = choice
default = rusty-light
options = rusty-light, rusty-dark, campbell
label = Day theme
description = Theme used during the day.
[setting.night_theme]
type = choice
default = rusty-dark
options = rusty-light, rusty-dark, campbell
label = Night theme
description = Theme used during the night.
-- Needs phase 2: rusty.theme.set is not registered yet (docs/MODS.md, 9.0). The file compiles;
-- calls to them fail when they run.
-- Switches the colour theme by the local hour.
-- rusty.theme.set is a session override: rusty.conf keeps its own [colors] theme, and a
-- config reload clears the override. This mod then applies the scheduled theme again.
local current: string? = nil
local function wanted_theme(hour: number): string
local start = rusty.settings.get("day_start")
local stop = rusty.settings.get("day_end")
local daytime
if start <= stop then
daytime = hour >= start and hour < stop
else
-- the day wraps past midnight, for example 22 to 6
daytime = hour >= start or hour < stop
end
if daytime then
return rusty.settings.get("day_theme")
end
return rusty.settings.get("night_theme")
end
local function check()
local name = wanted_theme(rusty.time.now().hour)
if name ~= current and rusty.theme.set(name) then
current = name
end
end
rusty.on("startup", check)
rusty.on("config_reloaded", function()
current = nil
check()
end)
-- One check a minute. While the window is unfocused the API pauses this timer, and it
-- fires once when the window gets focus again.
rusty.timer.every(60000, check)
  • mod.ini. Quatro configurações: duas horas (inteiros de 0 a 23) e dois temas escolhidos de uma lista (rusty-light, rusty-dark, campbell).
  • wanted_theme. Decide dia ou noite pela hora. Quando o início é maior que o fim (por exemplo 22 a 6), o dia atravessa a meia-noite e a comparação usa or. Luau puro.
  • check. Pede a hora com rusty.time.now().hour e aplica o tema com rusty.theme.set(name), que devolve se deu certo. current evita reaplicar o mesmo tema.
  • config_reloaded. rusty.theme.set é uma troca de sessão: recarregar o rusty.conf a desfaz, então o mod zera current e aplica de novo.
  • rusty.timer.every(60000, check). Uma checagem por minuto. Sem background = true, o timer fica em pausa com a janela sem foco e roda uma vez quando a janela volta, o que serve aqui: o tema só importa com a janela à vista.
  • O que você consegue hoje: a hora e o timer funcionam; só falta trocar o tema. Para trocar de tema, use o rusty.conf.

O que faz. Sublinha os links http e https na tela e acrescenta à paleta um item que abre o último link da saída do último comando. O Ctrl+clique num link continua sendo do terminal.

Como instalar. Copie docs/mods-examples/url-highlight/ para %APPDATA%\Rusty\mods\url-highlight\. O mod.ini é válido, mas o mod é desativado na carga: rusty.regex.compile não existe e o código do topo falha com attempt to index nil with 'compile'. rusty.ui.palette.add e rusty.open_url (dentro do run do item, que é um gesto) existem; rusty.ui.highlight.add e as opções de rusty.notify não.

name = url-highlight
version = 1.0.0
author = Rusty examples
description = Underlines http and https links on screen and opens the last link of the output.
main = init.luau
api = 1
memory_mb = 8
time_ms = 20
-- Needs phase 2: rusty.regex.compile, rusty.ui.highlight.add, rusty.notify(text, opts) are not registered yet (docs/MODS.md, 9.0). The file compiles;
-- calls to them fail when they run.
-- Link highlighting. Ctrl+click on a link is still handled by the terminal itself, so this
-- mod only draws the links and adds a palette entry for the last link of the last output.
-- The URL must start with http:// or https:// and must not end with punctuation.
local URL = "https?://[A-Za-z0-9._~:/?#@!$&'*+,;=%-]*[A-Za-z0-9_/#=%-]"
local re, err = rusty.regex.compile(URL)
if re == nil then
rusty.log("bad URL pattern: " .. tostring(err), "error")
return
end
rusty.ui.highlight.add{
id = "links",
pattern = URL,
style = { fg = "accent", underline = true },
}
local function last_url(text: string): string?
local found = nil
local init = 1
while true do
local s, e = re:find(text, init)
if s == nil then
break
end
found = string.sub(text, s, e)
init = e + 1
end
return found
end
rusty.ui.palette.add{
id = "open-last-url",
title = "Open last link from command output",
keywords = "url link browser",
run = function()
local output = rusty.pane.last_output()
local url = if output then last_url(output) else nil
if url == nil then
rusty.notify("No link in the last command output.", { level = "warn" })
else
rusty.open_url(url)
end
end,
}
  • mod.ini. Só os campos básicos, sem permissões e sem configurações.
  • URL. Um padrão de texto do Lua para um endereço que começa com http:// ou https:// e não termina em pontuação.
  • rusty.regex.compile(URL). Compila o padrão e devolve nil mais uma mensagem em caso de erro; nesse caso o mod registra e faz return. Planejada.
  • rusty.ui.highlight.add{...}. Destaca todas as ocorrências com cor de destaque e sublinhado. Planejada.
  • last_url. Percorre o texto com re:find e guarda a última ocorrência.
  • rusty.ui.palette.add{...}. O item chama rusty.pane.last_output(), extrai o link e o abre com rusty.open_url(url), ou avisa que não achou. rusty.ui.palette.add e rusty.open_url existem; rusty.pane.last_output exige a permissão pane_text, que o mod.ini deste exemplo não declara.
  • O que você consegue hoje: o próprio Rusty abre URLs com Ctrl+clique. Veja Links e caminhos.