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.
Como instalar um exemplo
Seção intitulada “Como instalar um exemplo”- Copie a pasta do mod para
%APPDATA%\Rusty\mods\. O nome da pasta é o nome do mod e tem de ser igual ao camponamedomod.ini. - Acrescente o nome em
[mods] enablednorusty.conf:
[mods]enabled = hello- Salve. O Rusty carrega o mod sem reiniciar.
- Abra
%LOCALAPPDATA%\Rusty\mods.loge 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.
mod.ini
Seção intitulada “mod.ini”# 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 = helloversion = 1.0.0author = Rusty docsdescription = Logs each new tab, counts them, and notifies every tenth one.main = init.luauapi = 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 = 20init.luau
Seção intitulada “init.luau”-- 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") endend)Por partes
Seção intitulada “Por partes”mod.ini. Os quatro campos obrigatórios (name,version,main,api = 1) maisauthoredescription. As linhas comentadas no fim mostram as chaves opcionais com os valores padrão: sempermissions, 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 comname,version,direapi;rusty.api.version()devolve1. 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 comrusty.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 comrusty.store.sete escreve o número da aba (ev.tab) e o total no log.count % 10 == 0. A cada dez abas chamarusty.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.luaucom o Rusty aberto: o mod recarrega e a próxima linha de log já usa o texto novo.
auto-tab-title
Seção intitulada “auto-tab-title”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.
mod.ini
Seção intitulada “mod.ini”name = auto-tab-titleversion = 1.0.0author = Rusty examplesdescription = Tab titles follow the running program, or the folder name when idle.main = init.luauapi = 1memory_mb = 8time_ms = 20
[setting.max_length]type = intdefault = 24min = 8max = 60label = Maximum lengthdescription = Longest tab title, in cells. Longer titles are cut with an ellipsis.init.luau
Seção intitulada “init.luau”-- 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 runslocal 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 endend
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)) endend)
rusty.on("cwd_changed", function(ev) if not busy[ev.pane] then apply(ev.tab, folder_name(ev.cwd)) endend)
rusty.on("pane_closed", function(ev) busy[ev.pane] = nil cancel_pending(ev.pane)end)Por partes
Seção intitulada “Por partes”[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. Omod.inicom[setting.*]é aceito, e o valor se lê comrusty.settings.get.busyepending. Tabelas indexadas pelo número do painel:busydiz se há um comando em execução;pendingguarda o número do timer que vai descobrir o nome do programa.folder_name. Tira as barras do fim decwde devolve o último trecho comrusty.path.basename.rusty.path.basenameexiste hoje.apply. Corta o título comrusty.str.truncatee o aplica comrusty.tab.set_title(tab, title); comnil, 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. Orusty.timer.afterdevolve o número do timer, erusty.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. Comrusty.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.
mod.ini
Seção intitulada “mod.ini”name = clockversion = 1.0.0author = Rusty examplesdescription = Shows the local time in the status bar. Uses an opt-in timer.main = init.luauapi = 1memory_mb = 4time_ms = 5
[setting.format]type = choicedefault = 24hoptions = 24h, 12hlabel = Time formatdescription = 24-hour or 12-hour clock.
[setting.show_seconds]type = booldefault = falselabel = Show secondsdescription = Shows seconds and refreshes every second instead of every five seconds.init.luau
Seção intitulada “init.luau”-- 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 endend)
rusty.on("shutdown", function() if timer then rusty.timer.cancel(timer) timer = nil endend)Por partes
Seção intitulada “Por partes”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 (24hou12h) e um booleano.tick. Escolhe o padrão de formato (%H:%Mou%I:%M), acrescenta:%Sse mostrar segundos e atualiza o segmentoclock, alinhado à direita, comrusty.ui.status.segment{...}.start. Cancela o timer anterior, atualiza a hora e criarusty.timer.every(interval, tick): 1000 ms com segundos, 5000 ms sem. O número que oeverydevolve fica emtimer, erusty.timer.cancel(timer)o cancela.startup,config_reloaded,shutdown. Inicia na carga, reinicia o timer se o usuário mudar uma configuraçãomods.clock.*e cancela o timer ao sair. Hoje os três eventos existem, masconfig_reloadedainda não trazev.changed(é planejado): o laçofor _, key in ev.changedfalha 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.
command-duration
Seção intitulada “command-duration”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.
mod.ini
Seção intitulada “mod.ini”name = command-durationversion = 1.0.0author = Rusty examplesdescription = Badges a background tab when a long command ends, and notifies with the duration.main = init.luauapi = 1memory_mb = 8time_ms = 20
[setting.threshold_s]type = intdefault = 30min = 1max = 3600label = Threshold (seconds)description = Commands that ran at least this long get a badge and a notification.
[setting.notify]type = booldefault = truelabel = Notifydescription = Shows a notification when a long command ends in a background tab.init.luau
Seção intitulada “init.luau”-- 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, }) endend)
local function clear_badge(tab: number) if badged[tab] then rusty.ui.tab.clear(tab) badged[tab] = nil endend
rusty.on("tab_focused", function(ev) clear_badge(ev.tab)end)
rusty.on("tab_closed", function(ev) badged[ev.tab] = nilend)Por partes
Seção intitulada “Por partes”- Comentário de abertura. Diz que a configuração interna
shell_integration.notify_after_secssó pisca a barra de tarefas; o mod acrescenta o distintivo e a notificação. format_duration. Transforma milissegundos em45s,3m20sou1h5m. É Luau puro e funciona em qualquer versão.command_finished. Ignora comandos abaixo do limite (threshold_svezes 1000), pergunta comrusty.pane.infose a aba está visível, calculafaileda partir deev.exit_codee decora a aba comrusty.ui.tab.decorate(faixa verde ou vermelha e a duração como emblema, até 4 células). Depois chamarusty.notify(summary, { level, pane }); hoje o segundo argumento é ignorado.tab_focused. Ao entrar na aba,rusty.ui.tab.cleartira o distintivo.badgedlembra 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_mseev.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.
copy-last-output
Seção intitulada “copy-last-output”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.
mod.ini
Seção intitulada “mod.ini”name = copy-last-outputversion = 1.0.0author = Rusty examplesdescription = Palette entry that copies the last command output without its blank edge lines.main = init.luauapi = 1permissions = clipboardmemory_mb = 8time_ms = 20init.luau
Seção intitulada “init.luau”-- 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,}Por partes
Seção intitulada “Por partes”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 comtable.concat(lines, "\n", first, last). Luau puro, funciona hoje.rusty.ui.palette.add{...}. Registra o itemcopy-last-outputna paleta, com título, palavras-chave e a funçãorun. As palavras-chave são aceitas e ignoradas. Na paleta o item aparece comocopy-last-output: título.run. Lê a saída comrusty.pane.last_output()(exigepane_text), avisa se não há comando ou se saiu vazio, copia comrusty.clipboard.sete conta as linhas comstring.gsub. A formarusty.notify(texto, { level = ... })é planejada.- O que você consegue hoje:
rusty.action("copy_last_output")copia a saída bruta, comclipboard. A receita Copiar a saída do último comando com uma tecla liga isso a uma tecla.
git-branch
Seção intitulada “git-branch”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.
mod.ini
Seção intitulada “mod.ini”name = git-branchversion = 1.0.0author = Rusty examplesdescription = Shows the git branch of the focused pane in the status bar.main = init.luauapi = 1permissions = fs_readmemory_mb = 8time_ms = 20
[setting.position]type = choicedefault = rightoptions = left, rightlabel = Positiondescription = Side of the status bar where the branch is shown.
[setting.sha_length]type = intdefault = 7min = 4max = 12label = Commit lengthdescription = Characters of the commit shown when HEAD is detached.init.luau
Seção intitulada “init.luau”-- 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 nilend
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 HEADPor partes
Seção intitulada “Por partes”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.gitsubindo as pastas comrusty.fs.find_up, trata a pasta que não é um diretório (worktrees e submódulos) como"worktree", lêHEADcomrusty.fs.reade extrai o ramo comstring.match(head, "^ref: refs/heads/(.-)%s*$"). Os padrões de texto são Luau puro.refresh. Pergunta a pasta do painel comrusty.pane.info(), calcula o rótulo e mostra ou remove o segmentogit-branch.- Quando atualiza. Em
startup,pane_focused,tab_focused,cwd_changedecommand_finished(umgit checkoutmuda oHEAD). - O que você consegue hoje: os eventos existem,
cwd_changedtrazev.cwde 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 chamarrusty.fs.find_up. O prompt do Rusty já mostra o ramo do Git.
kitchen-sink
Seção intitulada “kitchen-sink”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.
mod.ini
Seção intitulada “mod.ini”name = kitchen-sinkversion = 1.0.0author = Rusty examplesdescription = One example per API area: settings, status bar, store, keys, themes, menus, overlay.main = init.luauapi = 1permissions = clipboardmemory_mb = 12time_ms = 20
[setting.greeting]type = textdefault = hello from kitchen-sinkmax_length = 40label = Greetingdescription = Text shown in the status bar and at the top of the panel.
[setting.accent]type = colordefault = #e8743blabel = Status colourdescription = Colour of the status bar segment.
[setting.level]type = intdefault = 3min = 1max = 10label = Leveldescription = A number shown in the status bar.
[setting.ratio]type = floatdefault = 0.5min = 0max = 1label = Ratiodescription = Value of the progress bar in the panel.
[setting.mode]type = choicedefault = compactoptions = compact, fulllabel = Panel layoutdescription = Compact shows the basics; full adds the note field.
[setting.verbose]type = booldefault = falselabel = Verbose logdescription = Writes every key press to mods.log.init.luau
Seção intitulada “init.luau”-- 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.uilocal 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 nend
-- 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 endend
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 nilend)
-- 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)Por partes
Seção intitulada “Por partes”mod.ini.permissions = clipboardememory_mb = 12. As seis configurações mostram todos os tipos previstos:text,color,int,float,choiceebool.- 1. Configurações.
rusty.settings.getexiste;rusty.config.get(leitura dorusty.conf) é planejada. - 2. Armazenamento.
bump_countconta quantas vezes o painel abriu comrusty.store.geterusty.store.set. Esta parte roda hoje. - 3. Popup.
ui.overlay.opencom uma árvore de widgets (Text,Row,Spacer,Progress,List,Input) eon_eventparaactivate,submiteclose. Osidpreservam o foco e o texto digitado quando a árvore é atualizada. - 4. Segmento de status.
ui.status.segmentcom cor vinda de uma configuração, dica eon_click. - 5. Gancho de teclas.
rusty.on("key", ...)que consomef12e, comverbose, 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.addeui.glyph.replacesão planejadas.ui.palette.addexiste: o item aparece na paleta comokitchen-sink: título. - Fim. Um
startupescreve no logkitchen-sink loaded, API 1.
quick-snippets
Seção intitulada “quick-snippets”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.
mod.ini
Seção intitulada “mod.ini”name = quick-snippetsversion = 1.0.0author = Rusty examplesdescription = Popup with a filterable list of snippets; Enter types the chosen one into the pane.main = init.luauapi = 1permissions = spawnmemory_mb = 8time_ms = 20
[setting.press_enter]type = booldefault = falselabel = Press Enter after typingdescription = Sends Enter after the snippet, so it runs at once. Off by default.init.luau
Seção intitulada “init.luau”-- 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 = nillocal focused_pane = nil -- from pane_focused: where send_text typesrusty.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 nilend
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 itemsend
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 = "" endend
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,}Por partes
Seção intitulada “Por partes”mod.ini.permissions = spawn: digitar num painel executa comandos, por isso é tratado como executar.SNIPPETS. Uma lista de tabelas comid,labeletext. Só Luau.focused_pane. Guarda o painel focado a partir do eventopane_focused(ev.pane). É o padrão certo para esta versão, onde não há função que devolva o painel focado.visible_items,rootehandle. Filtram a lista pelo texto digitado, montam a árvore de widgets e tratam os eventoschange,activateeclosedo 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". Vejarusty.pane.send_text. rusty.keys.binderusty.ui.palette.add. Abrem o popup. As duas existem (veja Teclas e paleta); só o popup é planejado. O campokeywordsdo 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.addcom umidpor item) faz o papel da lista. A receita Digitar um comando com uma tecla usa o mesmosend_text.
theme-by-time
Seção intitulada “theme-by-time”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'.
mod.ini
Seção intitulada “mod.ini”name = theme-by-timeversion = 1.0.0author = Rusty examplesdescription = Switches the colour theme at the start and end of the day, by local time.main = init.luauapi = 1memory_mb = 8time_ms = 20
[setting.day_start]type = intdefault = 7min = 0max = 23label = Day starts at (hour)description = Local hour, 0 to 23, when the day theme starts.
[setting.day_end]type = intdefault = 19min = 0max = 23label = 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 = choicedefault = rusty-lightoptions = rusty-light, rusty-dark, campbelllabel = Day themedescription = Theme used during the day.
[setting.night_theme]type = choicedefault = rusty-darkoptions = rusty-light, rusty-dark, campbelllabel = Night themedescription = Theme used during the night.init.luau
Seção intitulada “init.luau”-- 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 endend
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)Por partes
Seção intitulada “Por partes”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 usaor. Luau puro.check. Pede a hora comrusty.time.now().houre aplica o tema comrusty.theme.set(name), que devolve se deu certo.currentevita reaplicar o mesmo tema.config_reloaded.rusty.theme.seté uma troca de sessão: recarregar orusty.confa desfaz, então o mod zeracurrente aplica de novo.rusty.timer.every(60000, check). Uma checagem por minuto. Sembackground = 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.
url-highlight
Seção intitulada “url-highlight”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.
mod.ini
Seção intitulada “mod.ini”name = url-highlightversion = 1.0.0author = Rusty examplesdescription = Underlines http and https links on screen and opens the last link of the output.main = init.luauapi = 1memory_mb = 8time_ms = 20init.luau
Seção intitulada “init.luau”-- 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") returnend
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 foundend
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,}Por partes
Seção intitulada “Por partes”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 comhttp://ouhttps://e não termina em pontuação.rusty.regex.compile(URL). Compila o padrão e devolvenilmais uma mensagem em caso de erro; nesse caso o mod registra e fazreturn. Planejada.rusty.ui.highlight.add{...}. Destaca todas as ocorrências com cor de destaque e sublinhado. Planejada.last_url. Percorre o texto comre:finde guarda a última ocorrência.rusty.ui.palette.add{...}. O item chamarusty.pane.last_output(), extrai o link e o abre comrusty.open_url(url), ou avisa que não achou.rusty.ui.palette.adderusty.open_urlexistem;rusty.pane.last_outputexige a permissãopane_text, que omod.inideste exemplo não declara.- O que você consegue hoje: o próprio Rusty abre URLs com Ctrl+clique. Veja Links e caminhos.