Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save sitedyno/3f7bafae5bccb0f83c03aba2d4fc25f9 to your computer and use it in GitHub Desktop.
Save sitedyno/3f7bafae5bccb0f83c03aba2d4fc25f9 to your computer and use it in GitHub Desktop.
This snippet shows how you can detect CSS classes in html and display diagnostics about them if desired. See comments for credits (not me).
-- https://linktr.ee/TymekDev
-- Alright, I got the HTML -> classes -> diagnostics part. Now all that's left is:
-- 1. Parse CSS file(s) for selectors
-- 2. ~~Intersect~~ Get set difference of class names and selectors
-- 3. Run this stuff on save (?)
-- Anyone wants to take this home? <@216716701973217290>?
-- Demo: https://asciinema.org/a/VQEt82360Kugo0gkg33fVYe57
-- Code:
local query = [[(
(attribute_name) @name (#eq? @name "class")
(quoted_attribute_value
(attribute_value) @classes)
)]]
local get_root = function(bufnr)
local parser = vim.treesitter.get_parser(bufnr, 'html', {})
local tree = parser:parse()[1]
return tree:root()
end
local get_classes = function(bufnr)
local ts_query = vim.treesitter.query.parse('html', query)
local result = {}
for id, node, _ in ts_query:iter_captures(get_root(bufnr), bufnr) do
if ts_query.captures[id] == 'classes' then
local start_row, start_col, _, _ = vim.treesitter.get_node_range(node)
local text = vim.treesitter.get_node_text(node, bufnr)
local offset = 0
for class in string.gmatch(text, '[^%s]+') do
table.insert(result, {
bufnr = bufnr,
lnum = start_row,
col = start_col + offset,
message = "Unused class '" .. class .. "'",
})
offset = offset + #class + 1
end
end
end
return result
end
local show_diagnostics = function(bufnr)
local ns = vim.api.nvim_create_namespace 'HTML Classes Linter'
vim.diagnostic.set(ns, bufnr, get_classes(bufnr))
end
local bufnr = 1
show_diagnostics(bufnr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment