Skip to content

Instantly share code, notes, and snippets.

@sum01
Last active November 7, 2017 19:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sum01/640ba8710c25469b179750069c064b11 to your computer and use it in GitHub Desktop.
Save sum01/640ba8710c25469b179750069c064b11 to your computer and use it in GitHub Desktop.
A one-size-fits-all fmt plugin for Micro text-editor
VERSION = "1.0.0"
-- Table (of tables) for lookup (keep alphabetical order plz).
-- Reported filetype (by Micro) on the left, command & args on the right.
fmt_table = {
["fish"] = {"fishfmt", "-w"},
["go"] = {"gofmt", "-s -w"},
["rust"] = {"rustfmt", nil}, -- no args, overwrite is default
["shell"] = {"shfmt", "-s -w"}
}
-- Declares the table & options to enable/disable formatter(s)
-- Avoids manually defining commands twice by reading the table
for i, value in pairs(fmt_table) do
-- i and value[2] aren't needed here. Maybe optimize this?
-- An empty table element would return nil
if value[1] ~= nil then
-- value[2] would return args, which we don't need here. We want the cmd string.
if GetOption(value[1]) == nil then
-- Disabled by default, require user to enable for safety
AddOption(value[1], false)
end
end
end
function run_fmt()
-- Prevent infinite loop of onSave()
CurView():Save(false)
local file_type = CurView().Buf:FileType()
-- The literal filetype name (`rust`, `shell`, etc.) is the table's key
-- [1] is the cmd, [2] is args
local target_fmt = fmt_table[file_type]
-- Only do anything if the filetype has is a supported formatter
if target_fmt ~= nil then
-- Only do anything if the specified formatter is enabled
if GetOption(target_fmt[1]) then
-- Load in the 'base' command (ex: `rustfmt`, `gofmt`, etc.)
local cmd = target_fmt[1]
-- Check for args
if target_fmt[2] ~= nil then
-- Add a space between cmd & args
cmd = cmd .. " " .. target_fmt[2]
end
-- Add a space between the cmd & path
cmd = cmd .. " "
-- Actually run the format command
local handle = io.popen(cmd .. CurView().Buf.Path)
local result = handle:read("*a")
handle:close()
-- Reload
CurView():ReOpen()
end
end
end
function onSave(view)
run_fmt()
end
-- User command
MakeCommand("fmt", "fmt.run_fmt", 0)
@sum01
Copy link
Author

sum01 commented Nov 7, 2017

For anyone reading, this idea got expanded into the fmt plugin, so if you want something similar then use that instead.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment