Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

syntax highlighting: get the most out of tree-sitter #21

Open
kristoff-it opened this issue Mar 8, 2024 · 1 comment
Open

syntax highlighting: get the most out of tree-sitter #21

kristoff-it opened this issue Mar 8, 2024 · 1 comment

Comments

@kristoff-it
Copy link
Owner

This is the current code that applies syntax highlighting:

const cursor = try treez.Query.Cursor.create();
defer cursor.destroy();
cursor.execute(lang.query, tree.getRootNode());
var print_cursor: usize = 0;
while (cursor.nextMatch()) |match| {
var idx: usize = 0;
for (match.captures()) |capture| {
const capture_name = lang.query.getCaptureNameForId(capture.id);
const range = capture.node.getRange();
if (range.start_byte < print_cursor) continue;
if (range.start_byte > print_cursor) {
try writer.print("{s}", .{HtmlSafe{ .bytes = code[print_cursor..range.start_byte] }});
}
try writer.print(
\\<span class="{s}">{s}</span>
, .{
DotsToSpaces{ .bytes = capture_name },
HtmlSafe{ .bytes = code[range.start_byte..range.end_byte] },
});
print_cursor = range.end_byte;
idx += 1;
}
}

This code runs the highlights.scm query from the tree sitter parser of each language and decorates the output with appropriate class attributes.

This algorithm is a bit too simplistic because it's unable to render overlapping matches, which means that some highlighting information is lost.

A more correct solution would involve buffering changes in order to create a final set of span elements that properly represents all matches.

@kristoff-it kristoff-it removed the enhancement New feature or request label Jul 26, 2024
@kristoff-it
Copy link
Owner Author

This is currently hurting our ability to Syntax highlight SuperHTML templates correctly. They look much better in an editor than they do in a rendered code block.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant