diff options
author | Guldoman <giulio.lettieri@gmail.com> | 2022-06-06 16:44:03 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-06-06 10:44:03 -0400 |
commit | 7df41835bc47ca905467256e146d76dda2bb172f (patch) | |
tree | 8725f959747f07a38af79b267fdc8917f569bae6 /plugins/align_carets.lua | |
parent | d3068a44de59fe7b55a04a1fb271637670e6070a (diff) | |
download | lite-xl-plugins-7df41835bc47ca905467256e146d76dda2bb172f.tar.gz lite-xl-plugins-7df41835bc47ca905467256e146d76dda2bb172f.zip |
Add `align_carets` (#89)
Diffstat (limited to 'plugins/align_carets.lua')
-rw-r--r-- | plugins/align_carets.lua | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/plugins/align_carets.lua b/plugins/align_carets.lua new file mode 100644 index 0000000..95d64d5 --- /dev/null +++ b/plugins/align_carets.lua @@ -0,0 +1,80 @@ +-- mod-version:2 -- lite-xl 2.0 +local core = require "core" +local command = require "core.command" +local DocView = require "core.docview" + + +local function check_doc() + local av = core.active_view + return av:is(DocView) and #av.doc.selections > 4 +end + + +-- returns: +-- * if the doc has selections +-- * if the selections span multiple lines +local function doc_get_selection_status(doc) + local selections = false + for _,line1,col1,line2,col2 in doc:get_selections() do + if line1 ~= line2 then + return true, true + end + if col1 ~= col2 then + selections = true + end + end + return selections, false +end + + +local function has_selections() + if not check_doc() then return false end + local selections, has_multilines = doc_get_selection_status(core.active_view.doc) + -- we want this to be true if there are only single lines selections + return selections and not has_multilines +end + + +local function has_no_selections() + if not check_doc() then return false end + return not doc_get_selection_status(core.active_view.doc) +end + + +local function align(right) + local doc = core.active_view.doc + local max_col = 0 + local done = { } + + -- get alignment column + for _,line1,col1,_,col2 in doc:get_selections(true) do + -- only use the first caret in a line + if not done[line1] then + done[line1] = true + max_col = math.max(max_col, right and col2 or col1) + end + end + + done = { } + for idx,line1,col1,line2,col2 in doc:get_selections(true) do + -- only align the first caret in a line + if not done[line1] then + done[line1] = true + local diff = max_col - (right and col2 or col1) + if diff > 0 then + doc:insert(line1, col1, string.rep(" ", diff)) + end + doc:set_selections(idx, line1, col1 + diff, line2, col2 + diff, right) + end + end +end + + +command.add(has_no_selections, { + ["doc:align-carets"] = align, +}) + +command.add(has_selections, { + ["doc:left-align-selections"] = align, + ["doc:right-align-selections"] = function() align(true) end, +}) |