From d0c2b1764a6fd17b9dd39ac1c76df3feb7394835 Mon Sep 17 00:00:00 2001 From: Roberto Alsina Date: Fri, 9 Aug 2024 13:28:05 -0300 Subject: [PATCH] HTML formatter option: line_number_start / line_number_id_prefix --- src/formatters/html.cr | 38 ++++++++++++++++++++++++++++++++++---- src/main.cr | 4 +++- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/src/formatters/html.cr b/src/formatters/html.cr index 5ac115e..e552d50 100644 --- a/src/formatters/html.cr +++ b/src/formatters/html.cr @@ -13,10 +13,12 @@ module Tartrazine # property surrounding_pre : Bool = true # property wrap_long_lines : 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 base_line_number : Int32 = 1 def format(text : String, lexer : Lexer, theme : Theme) : String text = format_text(text, lexer, theme) @@ -39,11 +41,16 @@ module Tartrazine end def format_text(text : String, lexer : Lexer, theme : Theme) : String + lines = group_tokens_in_lines(lexer.tokenize(text)) output = String.build do |outp| outp << "
"
-        lexer.tokenize(text).each do |token|
-          fragment = "#{token[:value]}"
-          outp << fragment
+        lines.each_with_index(offset: line_number_start - 1) do |line, i|
+          outp << ""
+          line.each do |token|
+            fragment = "#{token[:value]}"
+            outp << fragment
+          end
+          outp << ""
         end
         outp << "
" end @@ -88,5 +95,28 @@ module Tartrazine theme.styles.has_key?(parent) }] end + + def group_tokens_in_lines(tokens : Array(Token)) : Array(Array(Token)) + split_tokens = [] of Token + tokens.each do |token| + if token[:value].includes?("\n") + values = token[:value].split("\n") + values.each_with_index do |value, index| + value += "\n" if index < values.size - 1 + split_tokens << {type: token[:type], value: value} + end + else + split_tokens << token + end + end + lines = [Array(Token).new] + split_tokens.each do |token| + lines.last << token + if token[:value].includes?("\n") + lines << Array(Token).new + end + end + lines + end end end diff --git a/src/main.cr b/src/main.cr index ab27cfd..949aa0e 100644 --- a/src/main.cr +++ b/src/main.cr @@ -4,5 +4,7 @@ lexer = Tartrazine.lexer("crystal") theme = Tartrazine.theme(ARGV[1]) formatter = Tartrazine::Html.new formatter.standalone = true -formatter.class_prefix = "tartrazine-" +formatter.class_prefix = "hl-" +formatter.line_number_id_prefix = "ln-" +formatter.line_number_start = 3 puts formatter.format(File.read(ARGV[0]), lexer, theme)