]> git.lizzy.rs Git - micro.git/blob - runtime/plugins/linter/linter.lua
Add support for job control
[micro.git] / runtime / plugins / linter / linter.lua
1 if GetOption("linter") == nil then
2     AddOption("linter", true)
3 end
4
5 function linter_onSave()
6     if GetOption("linter") then
7         local ft = CurView().Buf.FileType
8         local file = CurView().Buf.Path
9         local devnull = "/dev/null"
10         if OS == "windows" then
11             devnull = "NUL"
12         end
13         if ft == "Go" then
14             linter_lint("gobuild", "go build -o " .. devnull, "%f:%l: %m")
15             linter_lint("golint", "golint " .. CurView().Buf.Path, "%f:%l:%d+: %m")
16         elseif ft == "Lua" then
17             linter_lint("luacheck", "luacheck --no-color " .. file, "%f:%l:%d+: %m")
18         elseif ft == "Python" then
19             linter_lint("pyflakes", "pyflakes " .. file, "%f:%l: %m")
20         elseif ft == "C" then
21             linter_lint("gcc", "gcc -fsyntax-only -Wall -Wextra " .. file, "%f:%l:%d+:.+: %m")
22         elseif ft == "D" then
23             linter_lint("dmd", "dmd -color=off -o- -w -wi -c " .. file, "%f%(%l%):.+: %m")
24         elseif ft == "Java" then
25             linter_lint("javac", "javac " .. file, "%f:%l: error: %m")
26         elseif ft == "JavaScript" then
27             linter_lint("jshint", "jshint " .. file, "%f: line %l,.+, %m")
28         end
29     else
30         CurView():ClearAllGutterMessages()
31     end
32 end
33
34 function linter_lint(linter, cmd, errorformat)
35     CurView():ClearGutterMessages(linter)
36
37     JobStart(cmd, "", "", "linter_onExit", linter, errorformat)
38 end
39
40 function linter_onExit(output, linter, errorformat)
41     local lines = linter_split(output, "\n")
42
43     local regex = errorformat:gsub("%%f", "(.+)"):gsub("%%l", "(%d+)"):gsub("%%m", "(.+)")
44     for _,line in ipairs(lines) do
45         -- Trim whitespace
46         line = line:match("^%s*(.+)%s*$")
47         if string.find(line, regex) then
48             local file, line, msg = string.match(line, regex)
49             if linter_basename(CurView().Buf.Path) == linter_basename(file) then
50                 CurView():GutterMessage(linter, tonumber(line), msg, 2)
51             end
52         end
53     end
54 end
55
56 function linter_split(str, sep)
57     local result = {}
58     local regex = ("([^%s]+)"):format(sep)
59     for each in str:gmatch(regex) do
60         table.insert(result, each)
61     end
62     return result
63 end
64
65 function linter_basename(file)
66     local name = string.gsub(file, "(.*/)(.*)", "%2")
67     return name
68 end