HTML formatter option: line_numbers / highlight_lines

This commit is contained in:
Roberto Alsina 2024-08-09 14:00:42 -03:00
parent d0c2b1764a
commit f98f44365f
5 changed files with 15 additions and 6 deletions

View File

@ -8,7 +8,7 @@ def abbr(line):
return "".join(c for c in line if c in string.ascii_uppercase).lower()
abbrevs = {}
tokens = set([])
tokens = {"Highlight"}
for line in sys.stdin:
if "<token" not in line:
continue

View File

@ -1,6 +1,7 @@
module Tartrazine
Abbreviations = {
"Background" => "b",
"Highlight" => "h",
"Text" => "t",
"CommentSingle" => "cs",
"CommentSpecial" => "cs",

View File

@ -12,13 +12,13 @@ module Tartrazine
# property surrounding_pre : Bool = true
# property wrap_long_lines : Bool = false
# property line_numbers : Bool = false
property? line_numbers : Bool = false
property line_number_start : Int32 = 1
property line_number_id_prefix : String = "line-"
# property line_number_in_table : Bool = false
# property linkable_line_numbers : Bool = false
# property highlight_lines : Array(Range(Int32, Int32)) = [] of Range(Int32, Int32)
property highlight_lines : Array(Range(Int32, Int32)) = [] of Range(Int32, Int32)
def format(text : String, lexer : Lexer, theme : Theme) : String
text = format_text(text, lexer, theme)
@ -45,12 +45,14 @@ module Tartrazine
output = String.build do |outp|
outp << "<pre class=\"#{get_css_class("Background", theme)}\"><code class=\"#{get_css_class("Background", theme)}\">"
lines.each_with_index(offset: line_number_start - 1) do |line, i|
outp << "<span id=\"#{line_number_id_prefix}#{i + 1}\">"
line_label = line_numbers? ? "#{i + 1}".rjust(4).ljust(5) : ""
line_class = highlighted?(i + 1) ? "class=\"#{get_css_class("Highlight", theme)}\"" : ""
outp << "<span id=\"#{line_number_id_prefix}#{i + 1}\" #{line_class}>#{line_label}</span>"
line.each do |token|
fragment = "<span class=\"#{get_css_class(token[:type], theme)}\">#{token[:value]}</span>"
outp << fragment
end
outp << "</span>"
end
outp << "</code></pre>"
end
@ -96,6 +98,10 @@ module Tartrazine
}]
end
def highlighted?(line : Int) : Bool
highlight_lines.any?(&.includes?(line))
end
def group_tokens_in_lines(tokens : Array(Token)) : Array(Array(Token))
split_tokens = [] of Token
tokens.each do |token|

View File

@ -6,5 +6,6 @@ formatter = Tartrazine::Html.new
formatter.standalone = true
formatter.class_prefix = "hl-"
formatter.line_number_id_prefix = "ln-"
formatter.line_number_start = 3
formatter.line_numbers = true
formatter.highlight_lines = [3..7, 20..30]
puts formatter.format(File.read(ARGV[0]), lexer, theme)

View File

@ -104,6 +104,7 @@ module Tartrazine
# https://github.com/mohd-akram/base16-pygments/
theme.styles["Background"] = Style.new(color: t["base05"], background: t["base00"])
theme.styles["Highlight"] = Style.new(color: t["base0D"], background: t["base01"])
theme.styles["Text"] = Style.new(color: t["base05"])
theme.styles["Error"] = Style.new(color: t["base08"])
theme.styles["Comment"] = Style.new(color: t["base03"])