diff options
-rw-r--r-- | README.md | 1 | ||||
-rw-r--r-- | plugins/detectindent.lua | 64 |
2 files changed, 65 insertions, 0 deletions
@@ -13,6 +13,7 @@ Plugin | Description [`autowrap`](plugins/autowrap.lua?raw=1) | Automatically hardwraps lines when typing [`bracketmatch`](plugins/bracketmatch.lua?raw=1) | Underlines matching right-bracket of left-bracket under caret *([screenshot](https://user-images.githubusercontent.com/3920290/80132745-0c863f00-8594-11ea-8875-c455c6fd7eae.png))* [`colorpreview`](plugins/colorpreview.lua?raw=1) | Underlays color values (eg. `#ff00ff` or `rgb(255, 0, 255)`) with their resultant color. *([screenshot](https://user-images.githubusercontent.com/3920290/80743752-731bd780-8b15-11ea-97d3-847db927c5dc.png))* +[`detectindent`](plugins/detectindent.lua?raw=1) | Automatically detects and uses the indentation size and tab type of a loaded file [`drawwhitespace`](plugins/drawwhitespace.lua?raw=1) | Draws tabs and spaces *([screenshot](https://user-images.githubusercontent.com/3920290/80573013-22ae5800-89f7-11ea-9895-6362a1c0abc7.png))* [`eval`](plugins/eval.lua?raw=1) | Replaces selected Lua code with its evaluated result [`gofmt`](plugins/gofmt.lua?raw=1) | Auto-formats the current go file, adds the missing imports and the missing return cases diff --git a/plugins/detectindent.lua b/plugins/detectindent.lua new file mode 100644 index 0000000..9c473b5 --- /dev/null +++ b/plugins/detectindent.lua @@ -0,0 +1,64 @@ +local core = require "core" +local command = require "core.command" +local config = require "core.config" +local DocView = require "core.docview" +local Doc = require "core.doc" + +local cache = setmetatable({}, { __mode = "k" }) + + +local function detect_indent(doc) + for _, text in ipairs(doc.lines) do + local str = text:match("^ +") + if str then return "soft", #str end + local str = text:match("^\t+") + if str then return "hard" end + end +end + + +local function update_cache(doc) + local type, size = detect_indent(doc) + if type then + cache[doc] = { type = type, size = size } + end +end + + +local new = Doc.new +function Doc:new(...) + new(self, ...) + update_cache(self) +end + +local clean = Doc.clean +function Doc:clean(...) + clean(self, ...) + update_cache(self) +end + + +local function with_indent_override(doc, fn, ...) + local c = cache[doc] + if not c then + return fn(...) + end + local type, size = config.tab_type, config.indent_size + config.tab_type, config.indent_size = c.type, c.size or config.indent_size + local r1, r2, r3 = fn(...) + config.tab_type, config.indent_size = type, size + return r1, r2, r3 +end + + +local perform = command.perform +function command.perform(...) + return with_indent_override(core.active_view.doc, perform, ...) +end + + +local draw = DocView.draw +function DocView:draw(...) + return with_indent_override(self.doc, draw, self, ...) +end + |