Pular para o conteúdo

Receitas

Cada receita responde a um “como faço para…” e traz o mod.ini e o init.luau completos. Todas usam só funções que existem nesta versão (0.1.0-alpha.6), conferidas contra a referência da API. Para usar uma, crie a pasta %APPDATA%\Rusty\mods\<nome>\ com o nome indicado no name, salve os arquivos e acrescente o nome em [mods] enabled no rusty.conf. O passo a passo está em Seu primeiro mod.

Receita O que faz Permissão
Registrar cada aba aberta e fechada conta abas e escreve no log nenhuma
Contar comandos e falhas guarda totais no store nenhuma
Avisar quando um comando longo termina pisca a barra de tarefas nenhuma
Digitar um comando com uma tecla Ctrl+Alt+G digita git status spawn
Abrir uma divisão e rodar um comando nela divide e digita no painel novo spawn
Abrir uma aba com o segundo perfil F9 abre a aba do perfil 2 spawn
Dar zoom no painel com F6 liga e desliga o zoom nenhuma
Pular entre prompts rola até o prompt anterior ou o seguinte nenhuma
Copiar a saída do último comando com uma tecla F8 copia a saída clipboard
Uma tecla, várias ações abre aba e divide spawn
Ligar e desligar o aviso de sino usa rusty.off nenhuma
Silenciar os avisos e lembrar a escolha liga e desliga, guardado no store nenhuma
Lembrar as últimas pastas guarda as cinco últimas pastas nenhuma
Registrar os comandos que falharam usa require nenhuma
Bloquear uma tecla engole uma tecla nenhuma
Descobrir quais funções existem checa funções planejadas nenhuma

Como faço para saber quantas abas estão abertas? Conte os eventos de abrir e fechar. Quando o mod carrega, o Rusty dispara tab_opened para a aba que já existe, então a conta começa certa.

mod.ini

name = tab-log
version = 1.0.0
main = init.luau
api = 1

init.luau

-- Logs every tab that opens or closes, with how many are open now.
local open = 0
rusty.on("tab_opened", function(ev)
open = open + 1
rusty.log("tab " .. ev.tab .. " opened, " .. open .. " open")
end)
rusty.on("tab_closed", function(ev)
open = open - 1
rusty.log("tab " .. ev.tab .. " closed, " .. open .. " open")
end)

Resultado. No mods.log, uma linha por evento: tab-log [info] tab 2 opened, 2 open. A contagem fica na memória do mod e volta a zero a cada recarga.

Como faço para guardar números entre sessões? Use o rusty.store. Este mod conta os comandos que terminaram e quantos falharam. Precisa da integração do shell ativa, que é quem envia o fim do comando.

mod.ini

name = command-count
version = 1.0.0
main = init.luau
api = 1

init.luau

-- Counts finished commands and failures in the mod's store, so the numbers survive a restart.
rusty.on("command_finished", function(ev)
local total = (rusty.store.get("commands") or 0) + 1
rusty.store.set("commands", total)
if ev.exit_code ~= nil and ev.exit_code ~= 0 then
rusty.store.set("failed", (rusty.store.get("failed") or 0) + 1)
end
rusty.log("command " .. total .. " finished, exit " .. tostring(ev.exit_code))
end)

Resultado. command-count [info] command 3 finished, exit 1. Os totais ficam em %LOCALAPPDATA%\Rusty\mod-data\command-count\store.txt. ev.exit_code é nil quando o shell não informa o código; por isso a conversão com tostring no log.

Como faço para ser avisado quando um comando demorado acaba? Compare ev.duration_ms com um limite. O Rusty também tem o aviso embutido shell_integration.notify_after_secs; esta receita é a versão que você controla.

mod.ini

name = long-command-notify
version = 1.0.0
main = init.luau
api = 1

init.luau

-- Shows a notice when a command runs for at least ten seconds.
local LONG_MS = 10000
rusty.on("command_finished", function(ev)
if ev.duration_ms ~= nil and ev.duration_ms >= LONG_MS then
rusty.notify("command took " .. math.floor(ev.duration_ms / 1000) .. " s")
end
end)

Resultado. Um comando de 15 segundos pisca o botão do Rusty na barra de tarefas (se a janela não estiver na frente) com o texto long-command-notify: command took 15 s. O aviso é limitado a um por segundo.

Como faço para digitar um comando com um atalho? Escute key, chame rusty.pane.send_text e devolva "consume" para a tecla não chegar ao shell. O Enter é "\r"; sem ele o texto fica na linha de comando.

Precisa de spawn no mod.ini.

mod.ini

name = key-snippet
version = 1.0.0
main = init.luau
api = 1
permissions = spawn

init.luau

-- Ctrl+Alt+G types "git status" and Enter into the focused pane.
-- Needs the spawn permission: typing into a shell runs commands.
rusty.on("key", function(ev)
if ev.ctrl and ev.alt and ev.key == "g" then
rusty.pane.send_text("git status\r", ev.pane)
return "consume"
end
end)

Resultado. Ctrl+Alt+G digita git status no painel focado. As outras teclas passam. Sem spawn no mod.ini, o mod é desativado com permission `spawn` was not granted.

Como faço para dividir o painel e já rodar algo no painel novo? O mod pede split_vertical e, quando o evento pane_opened chega com o número do painel novo, digita nele. A bandeira waiting impede que um painel aberto por outro motivo receba o texto.

Precisa de spawn no mod.ini.

mod.ini

name = split-and-run
version = 1.0.0
main = init.luau
api = 1
permissions = spawn

init.luau

-- Ctrl+Alt+D splits the focused pane and types a command into the new one.
local waiting = false
rusty.on("key", function(ev)
if ev.ctrl and ev.alt and not ev.shift and ev.key == "d" then
waiting = true
rusty.action("split_vertical")
return "consume"
end
end)
rusty.on("pane_opened", function(ev)
if waiting then
waiting = false
rusty.pane.send_text("git log --oneline -20\r", ev.pane)
end
end)

Resultado. Ctrl+Alt+D divide o painel com uma divisória vertical e digita git log --oneline -20 e Enter no painel novo.

Como faço para abrir uma aba com um perfil específico? Use new_tab_profile_N, onde N é a posição do perfil no menu do botão + (de 1 a 9). Veja Perfis.

Precisa de spawn no mod.ini.

mod.ini

name = profile-two
version = 1.0.0
main = init.luau
api = 1
permissions = spawn

init.luau

-- F9 opens a new tab with the second profile.
rusty.on("key", function(ev)
if ev.key == "f9" and not (ev.ctrl or ev.alt or ev.shift) then
rusty.action("new_tab_profile_2")
return "consume"
end
end)

Resultado. F9 abre uma aba nova com o perfil 2. Não dá para escolher a pasta inicial nem o título por rusty.action.

Como faço para ampliar o painel focado até ocupar a aba toda? A ação toggle_zoom_pane liga e desliga o zoom. Ela não pede permissão.

mod.ini

name = zoom-key
version = 1.0.0
main = init.luau
api = 1

init.luau

-- F6 toggles the zoom of the focused pane.
rusty.on("key", function(ev)
if ev.key == "f6" and not (ev.ctrl or ev.alt or ev.shift) then
rusty.action("toggle_zoom_pane")
return "consume"
end
end)

Resultado. F6 amplia o painel focado; apertar de novo volta ao layout anterior.

Como faço para rolar até o prompt anterior ou o seguinte? As ações scroll_to_prev_prompt e scroll_to_next_prompt usam as marcas que o shell envia. Elas dependem da integração do shell; sem as marcas, não há prompts para onde pular.

mod.ini

name = prompt-jump
version = 1.0.0
main = init.luau
api = 1

init.luau

-- Ctrl+Alt+Up and Ctrl+Alt+Down jump between prompts in the scrollback.
rusty.on("key", function(ev)
if ev.ctrl and ev.alt and not ev.shift then
if ev.key == "up" then
rusty.action("scroll_to_prev_prompt")
return "consume"
elseif ev.key == "down" then
rusty.action("scroll_to_next_prompt")
return "consume"
end
end
end)

Resultado. Ctrl+Alt+Up rola até o prompt anterior; Ctrl+Alt+Down, até o seguinte. As ações de rolagem não fazem nada com um programa de tela cheia aberto.

Como faço para copiar a saída do último comando? A ação copy_last_output copia a saída para a área de transferência, e pede clipboard. O mod não vê o texto: a cópia fica entre o Rusty e o Windows.

Precisa de clipboard no mod.ini.

mod.ini

name = copy-output-key
version = 1.0.0
main = init.luau
api = 1
permissions = clipboard

init.luau

-- F8 copies the output of the last command to the clipboard.
rusty.on("key", function(ev)
if ev.key == "f8" and not (ev.ctrl or ev.alt or ev.shift) then
rusty.action("copy_last_output")
rusty.log("copied the last output")
return "consume"
end
end)

Resultado. F8 copia a saída do último comando. Precisa das marcas de comando da integração do shell.

Como faço para ligar várias ações a uma tecla? Chame rusty.action uma depois da outra: o Rusty as executa na ordem dos pedidos, depois que o handler termina.

Precisa de spawn no mod.ini.

mod.ini

name = tab-and-split
version = 1.0.0
main = init.luau
api = 1
permissions = spawn

init.luau

-- Ctrl+Alt+Shift+N opens a new tab and splits it in two.
rusty.on("key", function(ev)
if ev.ctrl and ev.alt and ev.shift and ev.key == "n" then
rusty.action("new_tab")
rusty.action("split_vertical")
return "consume"
end
end)

Resultado. Uma aba nova, já dividida em dois painéis lado a lado. A fila de pedidos de um mod aceita 64 pedidos de uma vez; passando disso, rusty.action devolve false.

Como faço para cancelar uma inscrição em um evento? Guarde o número que rusty.on devolveu e passe-o a rusty.off. Aqui, uma tecla liga e desliga o aviso do evento bell, e ele começa desligado.

mod.ini

name = bell-toggle
version = 1.0.0
main = init.luau
api = 1

init.luau

-- Ctrl+Alt+Shift+B turns the bell notice on and off. It starts off.
local bell_id = nil
local function on_bell(ev)
rusty.notify("bell in pane " .. ev.pane)
end
rusty.on("key", function(ev)
if ev.ctrl and ev.alt and ev.shift and ev.key == "b" then
if bell_id then
rusty.off(bell_id)
bell_id = nil
rusty.log("bell notice off")
else
bell_id = rusty.on("bell", on_bell)
rusty.log("bell notice on")
end
return "consume"
end
end)

Resultado. Cada vez que você aperta o atalho, o log registra bell notice on ou bell notice off. Com o aviso ligado, um sino num painel pisca a barra de tarefas (no máximo uma vez por segundo).

Como faço para ter uma opção que sobrevive a reinícios? O rusty.store guarda um booleano que um atalho inverte. (Para opções que o usuário edita no rusty.conf, veja Configurações.)

mod.ini

name = mute-notices
version = 1.0.0
main = init.luau
api = 1

init.luau

-- Notice for long commands, with a key that mutes it. The choice is kept in the store.
local LONG_MS = 10000
rusty.on("command_finished", function(ev)
if rusty.store.get("muted") then
return
end
if ev.duration_ms ~= nil and ev.duration_ms >= LONG_MS then
rusty.notify("command took " .. math.floor(ev.duration_ms / 1000) .. " s")
end
end)
rusty.on("key", function(ev)
if ev.ctrl and ev.alt and ev.shift and ev.key == "m" then
local muted = not (rusty.store.get("muted") or false)
rusty.store.set("muted", muted)
rusty.log("muted = " .. tostring(muted))
return "consume"
end
end)

Resultado. Ctrl+Alt+Shift+M alterna entre avisar e silenciar. O valor fica em store.txt e vale na próxima vez que o Rusty abrir. Outra forma de ter opções é uma constante no topo do arquivo, como LONG_MS: edite e salve, e o mod recarrega.

Como faço para guardar a lista das últimas pastas que visitei? O evento cwd_changed traz a pasta do painel. O mod mantém as cinco mais recentes em chaves dir1 a dir5 do store. Precisa da integração do shell, que informa a pasta.

mod.ini

name = recent-dirs
version = 1.0.0
main = init.luau
api = 1

init.luau

-- Keeps the five most recent folders in the store (dir1 is the newest).
-- Ctrl+Alt+Shift+R writes them to the log.
local MAX = 5
local function remember(cwd)
local list = { cwd }
for i = 1, MAX do
local old = rusty.store.get("dir" .. i)
if old ~= nil and old ~= cwd and #list < MAX then
table.insert(list, old)
end
end
for i = 1, MAX do
if list[i] then
rusty.store.set("dir" .. i, list[i])
else
rusty.store.delete("dir" .. i)
end
end
end
rusty.on("cwd_changed", function(ev)
remember(ev.cwd)
end)
rusty.on("key", function(ev)
if ev.ctrl and ev.alt and ev.shift and ev.key == "r" then
for i = 1, MAX do
local dir = rusty.store.get("dir" .. i)
if dir ~= nil then
rusty.log(i .. ". " .. tostring(dir))
end
end
return "consume"
end
end)

Resultado. Ctrl+Alt+Shift+R escreve no log 1. C:\projetos\app, 2. .... Para digitar uma dessas pastas num painel, combine com a receita Digitar um comando com uma tecla.

Como faço para dividir o código em arquivos? Ponha o trecho em outro .luau da pasta do mod e chame require. O nome do módulo usa minúsculas, dígitos, _ e -, e o resultado é guardado: o arquivo roda uma vez.

mod.ini

name = fail-log
version = 1.0.0
main = init.luau
api = 1

fmt.luau

-- Turns milliseconds into "45s" or "3m20s".
local M = {}
function M.duration(ms: number): string
local seconds = math.floor(ms / 1000)
if seconds < 60 then
return seconds .. "s"
end
return math.floor(seconds / 60) .. "m" .. (seconds % 60) .. "s"
end
return M

init.luau

local fmt = require("fmt")
-- Writes a warning for each command that exits with a non-zero code.
rusty.on("command_finished", function(ev)
if ev.exit_code ~= nil and ev.exit_code ~= 0 then
rusty.log("pane " .. ev.pane .. " failed with code " .. ev.exit_code
.. " after " .. fmt.duration(ev.duration_ms or 0), "warn")
end
end)

Resultado. fail-log [warn] pane 1 failed with code 1 after 2s. O arquivo extra tem de se chamar fmt.luau e ficar na mesma pasta de init.luau. Salve o init.luau depois de mudar um módulo: só ele dispara a recarga.

Como faço para impedir que uma tecla faça algo? Um handler de key que devolve "consume" sem fazer nada engole a tecla: nem o Rusty nem o programa do painel a recebem.

mod.ini

name = block-f12
version = 1.0.0
main = init.luau
api = 1

init.luau

-- Swallows F12, so neither Rusty nor the program in the pane sees it.
rusty.on("key", function(ev)
if ev.key == "f12" and not (ev.ctrl or ev.alt or ev.shift) then
return "consume"
end
end)

Resultado. Apertar F12 não faz nada. O mesmo vale para um atalho do próprio Rusty: um mod que engole Ctrl+Shift+T tira esse atalho do Rusty (veja Atalhos). Por isso, escolha teclas que você não usa.

Como faço para escrever um mod que use uma função nova quando ela existir? Teste a função antes de chamar. rusty é uma tabela; o que não existe vale nil. Esta receita registra no log quais funções (algumas planejadas) o seu Rusty tem.

mod.ini

name = api-probe
version = 1.0.0
main = init.luau
api = 1

init.luau

-- Logs which functions this Rusty has. Useful when a mod should adapt to newer versions.
local function exists(path)
local node = rusty
for part in string.gmatch(path, "[^.]+") do
if type(node) ~= "table" then
return false
end
node = node[part]
if node == nil then
return false
end
end
return true
end
rusty.on("startup", function()
rusty.log("api version " .. tostring(rusty.api.version()))
for _, path in { "notify", "pane.send_text", "timer.every", "ui.palette.add", "ui.status.segment", "fs.read" } do
rusty.log(path .. ": " .. (if exists(path) then "yes" else "no"))
end
end)

Resultado. Nesta versão, notify, pane.send_text, timer.every, ui.palette.add e ui.status.segment aparecem como yes, e fs.read como no. Num Rusty futuro que registre mais funções, as linhas mudam sozinhas, e o mod pode escolher entre usar a função nova ou uma alternativa de rusty.action.