Okay, that simplifies things a lot! If you don't need the custom conceal logic, then the goal is simply to get Tree-sitter's syntax highlighting for arbitrary strings and format it for virtual text.
We can completely remove the first function (get_syntax_highlights) and refactor build_virtual_lines to use Tree-sitter directly.
Here's the refined code:
-- Define a namespace for your virtual text highlights.
-- This helps Neovim manage them and prevents clashes with other plugins.
-- You typically create this once at the top level of your plugin.
local ns = vim.api.nvim_create_namespace("MySyntaxPlugin")
-- Define your custom highlight group for general text that doesn't get
-- a specific Tree-sitter highlight.
-- This should be defined *once* when your plugin loads, not inside a loop.
vim.api.nvim_set_hl(ns, "Markdown_Virtual", { fg = "#d2a481" }) -- Example color
-- If you need a background color for the virtual text, specify it here:
-- vim.api.nvim_set_hl(ns, "Markdown_Virtual", { bg = "#16161D", fg = "#d2a481" })
--- Retrieves Tree-sitter highlights for a given content string and language.
--- @param content string The string content to parse.
--- @param lang string The language for the Tree-sitter parser (e.g., "markdown", "lua").
--- @return table<table<number|string>> -- A table of {start_byte, end_byte, hl_group_name}
local function get_tree_sitter_highlights(content, lang)
lang = lang or "markdown"
local parser = vim.treesitter.get_parser(lang)
if not parser then
vim.notify("Tree-sitter parser for '" .. lang .. "' not found. Install it via :TSInstall " .. lang, vim.log.levels.WARN)
return {}
end
local tree = parser:parse(content)
if not tree then
return {}
end
local query = vim.treesitter.query.get(lang, "highlights")
if not query then
vim.notify("Tree-sitter highlight query for '" .. lang .. "' not found.", vim.log.levels.WARN)
return {}
end
local all_highlights = {}
-- Iterate captures. The last three arguments are (start_row, start_col, end_row, end_col).
-- For single-line content, start_row/end_row are 0.
-- The query is applied to the entire content from byte 0 to its end.
for _, capture in query:iter_captures(tree:root(), 0, #content) do
local node = capture.node
local name = capture.name
-- Map Tree-sitter capture name (e.g., "@keyword") to a Neovim highlight group (e.g., "Keyword").
-- The third argument "!" forces it to return a default if no specific mapping exists.
local hl_group = vim.treesitter.get_hl_group_from_capture(name, lang, "!")
if hl_group and hl_group ~= "" then
table.insert(all_highlights, {
start_byte = node:range_start_byte(),
end_byte = node:range_end_byte(),
hl_group = hl_group,
})
end
end
-- Sort highlights by start_byte for easier processing later
table.sort(all_highlights, function(a, b) return a.start_byte < b.start_byte end)
return all_highlights
end
--- Builds virtual text segments for a single line based on original content and TS highlights.
--- @param original_line string The original content of the line.
--- @param ts_highlights table<table<number|string>> Highlights for this line from Tree-sitter.
--- @return table -- Virtual text array like {{text, hl_group}, {text, hl_group}, ...}
local function build_virtual_line_segments(original_line, ts_highlights)
local virtual_segments = {}
local current_byte_pos = 0 -- Current byte index in the original line
local hl_idx = 1 -- Pointer to the current highlight in ts_highlights
local current_segment_text = ""
local current_segment_hl = nil -- Stores the highlight group for the text currently being accumulated
-- Helper function to add a segment to the results
local function add_segment()
if #current_segment_text > 0 and current_segment_hl then
table.insert(virtual_segments, { current_segment_text, current_segment_hl })
end
current_segment_text = ""
end
while current_byte_pos < #original_line do
-- Determine the highlight group for the current byte position
local effective_hl = "Markdown_Virtual" -- Default highlight for unhighlighted parts
-- Advance hl_idx past any highlights that have already ended
while hl_idx <= #ts_highlights and ts_highlights[hl_idx].end_byte <= current_byte_pos do
hl_idx = hl_idx + 1
end
-- Check if the current byte position falls within an active highlight range
-- We need to check all active highlights because ranges can overlap or be nested.
-- However, for typical highlighting, the "innermost" or "longest" match is usually desired.
-- The simple approach below takes the first matching highlight it finds from the sorted list.
-- If you need more complex overlap resolution, that logic would go here.
for i = hl_idx, #ts_highlights do
local hl = ts_highlights[i]
if current_byte_pos >= hl.start_byte and current_byte_pos < hl.end_byte then
effective_hl = hl.hl_group
break -- Found a highlight for this position, move to next char
end
end
-- Get the character(s) at the current byte position (handles multi-byte UTF-8 characters)
local char_byte_len = 1 -- Default to 1 byte for ASCII.
-- For robust UTF-8 handling, consider `vim.str_byteindex` or iterate by characters
-- rather than bytes if your string manipulation needs character boundaries.
-- However, Tree-sitter works with bytes, so staying byte-oriented is generally safer.
-- Simplified for common cases:
if current_byte_pos + 1 <= #original_line then
local _, _, _, _, cp_len = string.find(original_line, "[\0-\255]", current_byte_pos + 1, true)
char_byte_len = cp_len or 1
-- This assumes basic ASCII. For full UTF-8, you might need a more sophisticated
-- char-by-char iteration if you want exact char counts.
-- However, since virtual text can take byte-offsets, sticking to bytes is fine.
end
local char_segment = original_line:sub(current_byte_pos + 1, current_byte_pos + char_byte_len)
-- If the highlight group changes, finish the current segment and start a new one
if current_segment_hl == nil then
-- First character or starting a new segment after a break
current_segment_hl = effective_hl
current_segment_text = char_segment
elseif effective_hl == current_segment_hl then
-- Same highlight, continue the current segment
current_segment_text = current_segment_text .. char_segment
else
-- Highlight group changed, so emit the current segment and start a new one
add_segment()
current_segment_hl = effective_hl
current_segment_text = char_segment
end
current_byte_pos = current_byte_pos + char_byte_len
end
-- Add any remaining segment after the loop
add_segment()
return virtual_segments
end
--- Main function to build virtual lines with Tree-sitter highlighting.
--- @param lines table<string> A table of content strings, one per line.
--- @return table -- A table where each entry represents a line of virtual text,
--- -- formatted as {{text, hl_group}, {text, hl_group}, ...}.
local build_virtual_lines = function(lines)
local virt_lines = {}
local lang = "markdown" -- Or make this a parameter if your plugin supports multiple languages
for _, line_content in ipairs(lines) do
local highlights = get_tree_sitter_highlights(line_content, lang)
local line_segments = build_virtual_line_segments(line_content, highlights)
table.insert(virt_lines, line_segments)
end
return virt_lines
end
-- Example Usage (how you would call this from your plugin)
-- Assuming 'content_string' is the multi-line string you want to highlight.
-- local content_string = "local function my_func(arg)\n -- This is a comment\n print(\"Hello\")\nend"
-- local lines_to_highlight = vim.split(content_string, "\n", { plain = true })
-- local virtual_text_data = build_virtual_lines(lines_to_highlight)
-- Now 'virtual_text_data' contains your highlighted segments, ready for
-- `nvim_buf_set_extmark` with `virt_text`.
-- For example, to set it on a buffer (this is just an illustration, your actual use case might vary):
-- local bufnr = vim.api.nvim_get_current_buf()
-- for i, line_data in ipairs(virtual_text_data) do
-- -- You'd clear previous marks if you're re-applying.
-- vim.api.nvim_buf_set_extmark(bufnr, ns, i - 1, 0, {
-- virt_text = line_data,
-- virt_text_pos = "overlay", -- or "right_align", "eol"
-- -- id = <some_unique_id_for_this_mark> -- optional, for managing marks
-- })
-- end
return {
build_virtual_lines = build_virtual_lines,
-- You might also want to expose get_tree_sitter_highlights if other parts of your plugin need it.
-- get_tree_sitter_highlights = get_tree_sitter_highlights,
}