]> git.lizzy.rs Git - micro.git/blob - runtime/plugins/linter/linter.lua
f0c3e5f62e9c4f0216dd6e0511c9ec219f093238
[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 = view.Buf.Filetype
8         local file = view.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 " .. view.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         view:ClearAllGutterMessages()
31     end
32 end
33
34 function linter_lint(linter, cmd, errorformat)
35     view:ClearGutterMessages(linter)
36
37     local handle = io.popen("(" .. cmd .. ")" .. " 2>&1")
38     local lines = linter_split(handle:read("*a"), "\n")
39     handle:close()
40
41     local regex = errorformat:gsub("%%f", "(.+)"):gsub("%%l", "(%d+)"):gsub("%%m", "(.+)")
42     for _,line in ipairs(lines) do
43         -- Trim whitespace
44         line = line:match("^%s*(.+)%s*$")
45         if string.find(line, regex) then
46             local file, line, msg = string.match(line, regex)
47             if linter_basename(view.Buf.Path) == linter_basename(file) then
48                 view:GutterMessage(linter, tonumber(line), msg, 2)
49             end
50         end
51     end
52 end
53
54 function linter_split(str, sep)
55     local result = {}
56     local regex = ("([^%s]+)"):format(sep)
57     for each in str:gmatch(regex) do
58         table.insert(result, each)
59     end
60     return result
61 end
62
63 function linter_basename(file)
64     local name = string.gsub(file, "(.*/)(.*)", "%2")
65     return name
66 end