]> git.lizzy.rs Git - micro-zigfmt.git/blob - zigfmt.lua
Don't crash when linter is disabled
[micro-zigfmt.git] / zigfmt.lua
1 VERSION = "0.1.0"
2 PLUGIN_NAME = "zigfmt"
3
4 local micro = import("micro")
5 local config = import("micro/config")
6 local shell = import("micro/shell")
7
8 local COMMAND_NAME = "zigfmt"
9 local LINTER_NAME = "zigfmt"
10
11 local function fullOptionName(name)
12   return PLUGIN_NAME .. "." .. name
13 end
14
15 local ONSAVE_OPTION_NAME = "fmt"
16 local ONSAVE_OPTION = fullOptionName(ONSAVE_OPTION_NAME)
17 local LINTER_OPTION_NAME = "lint"
18 local LINTER_OPTION = fullOptionName(LINTER_OPTION_NAME)
19
20 -- /path/to/test.zig:1:51: error: expected ';', found '}'
21 local ERROR_PATTERN = "%f:%l:%c: %m"
22
23 config.RegisterCommonOption(PLUGIN_NAME, ONSAVE_OPTION_NAME, true)
24 config.RegisterCommonOption(PLUGIN_NAME, LINTER_OPTION_NAME, true)
25
26 function init()
27   config.MakeCommand(COMMAND_NAME, zigfmt, config.NoComplete)
28   config.AddRuntimeFile(PLUGIN_NAME, config.RTHelp, "help/zigfmt.md")
29
30   if linter then
31     linter.makeLinter(LINTER_NAME, "zig", "zig", {"fmt", "--check", "%f"}, ERROR_PATTERN, {}, false, false, 0, 0, function(buf)
32       return buf.Settings[LINTER_OPTION]
33     end)
34   end
35 end
36
37 function onSave(bp)
38   local shouldFmt = bp.Buf:FileType() == "zig" and bp.Buf.Settings[ONSAVE_OPTION]
39   if shouldFmt then
40     zigfmt(bp)
41   end
42   return true
43 end
44
45 function zigfmt(bp)
46   bp:Save()
47   local output, err = shell.ExecCommand("zig", "fmt", bp.Buf.Path)
48   -- any failure here is a parse error, the linter will handle that
49   if err then
50     return
51   end
52   -- no files were changed (zig fmt prints the name of changed files)
53   if output == "" then
54     return
55   end
56   -- the file was changed by zig fmt, so reload it
57   bp.Buf:ReOpen()
58   micro.InfoBar():Message("Formatted " .. bp.Buf.Path)
59 end