Last active
February 20, 2024 17:20
-
-
Save dharmx/0a8de0423cd368d68a563f25591ef426 to your computer and use it in GitHub Desktop.
Sort class items inside HTML.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local T = vim.treesitter | |
local query = T.query | |
-- caps indicate config values | |
local SORTERS = {} | |
SORTERS.ASCII = function(a, b) return string.byte(a:sub(1, 1)) > string.byte(b:sub(1, 1)) end | |
-- add more | |
local SELECTED_SORTERS = { SORTERS.ASCII } -- add more | |
local FILETYPE = vim.o.filetype | |
local ALLOW = { "class" } | |
local QUERY = [[ | |
;; query | |
(attribute | |
((attribute_name) @name | |
(quoted_attribute_value | |
(attribute_value) @contents))) | |
]] | |
local language_tree = T.get_parser(0, FILETYPE) | |
local parsed_tree = language_tree:parse() | |
local parsed_query = query.parse(FILETYPE, QUERY) | |
local box = {} | |
for _, node, _ in parsed_query:iter_captures(parsed_tree[1]:root(), QUERY, 0, -1) do | |
local record = { | |
type = node:type(), | |
range = node:range(), | |
text = T.get_node_text(node, 0), | |
full_range = T.get_range(node, 0), | |
} | |
box[record.range] = vim.F.if_nil(box[record.range], {}) | |
box[record.range][record.type] = record.text | |
if record.type == "attribute_value" then | |
box[record.range].attribute_value = vim.split(record.text, " ", { plain = true }) | |
box[record.range].full_range = { | |
starting = { row = record.full_range[1], column = record.full_range[2] }, | |
ending = { row = record.full_range[4], column = record.full_range[5] }, | |
} | |
end | |
end | |
box = vim.tbl_filter(function(item) | |
return vim.tbl_contains(ALLOW, item.attribute_name) | |
end, box) | |
for index, attribute in ipairs(box) do | |
for _, sorter in ipairs(SELECTED_SORTERS) do | |
-- apply sorters | |
table.sort(box[index].attribute_value, sorter) | |
end | |
local params = { | |
0, | |
attribute.full_range.starting.row, | |
attribute.full_range.starting.column, | |
attribute.full_range.ending.row, | |
attribute.full_range.ending.column, | |
{ table.concat(box[index].attribute_value, " ") }, | |
} | |
vim.api.nvim_buf_set_text(unpack(params)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment