]> git.lizzy.rs Git - micro.git/blob - runtime/plugins/literate/literate.lua
Merge pull request #1327 from Osmose/git-commit-diff
[micro.git] / runtime / plugins / literate / literate.lua
1 local config = import("micro/config")
2
3 function startswith(str, start)
4    return string.sub(str,1,string.len(start))==start
5 end
6
7 function endswith(str, endStr)
8    return endStr=='' or string.sub(str,-string.len(endStr))==endStr
9 end
10
11 function split(string, sep)
12     local sep, fields = sep or ":", {}
13     local pattern = string.format("([^%s]+)", sep)
14     string:gsub(pattern, function(c) fields[#fields+1] = c end)
15     return fields
16 end
17
18 function onBufferOpen(buf)
19     if not endswith(buf.Path, ".lit") then
20         return
21     end
22
23     local codetype = "unknown"
24     for i=1,buf:LinesNum() do
25         local line = buf:Line(i-1)
26         if startswith(line, "@code_type") then
27             codetype = split(line, " ")[2]
28             break
29         end
30     end
31
32     local syntaxFile = ""
33     syntaxFile = syntaxFile .. "filetype: literate-" .. codetype .. "\n"
34     syntaxFile = syntaxFile .. "detect:\n"
35     syntaxFile = syntaxFile .. "    filename: \"\\\\.lit$\"\n"
36     syntaxFile = syntaxFile .. "rules:\n"
37     syntaxFile = syntaxFile .. "    - include: \"markdown\"\n"
38     syntaxFile = syntaxFile .. "    - special: \"^(@s|@title|@code_type|@comment_type|@include|@change|@change_end)\"\n"
39     syntaxFile = syntaxFile .. "    - special: \"(@add_css|@overwrite_css|@colorscheme|@compiler|@error_format|@book)\"\n"
40     syntaxFile = syntaxFile .. "    - default:\n"
41     syntaxFile = syntaxFile .. "        start: \"---.*$\"\n"
42     syntaxFile = syntaxFile .. "        end: \"---$\"\n"
43     syntaxFile = syntaxFile .. "        limit-group: \"identifier\"\n"
44     syntaxFile = syntaxFile .. "        rules:\n"
45     syntaxFile = syntaxFile .. "            - special:\n"
46     syntaxFile = syntaxFile .. "                start: \"@\\\\{\"\n"
47     syntaxFile = syntaxFile .. "                end: \"\\\\}\"\n"
48     syntaxFile = syntaxFile .. "                rules: []\n"
49     syntaxFile = syntaxFile .. "            - include: " .. codetype .. "\n"
50
51     config.AddRuntimeFileFromMemory(config.RTSyntax, "literate.yaml", syntaxFile)
52     config.Reload()
53     buf:UpdateRules()
54 end