summaryrefslogtreecommitdiff
path: root/lib
diff options
context:
space:
mode:
authorGuilherme Carreiro <[email protected]>2024-10-11 00:52:54 +0200
committergit <[email protected]>2024-10-23 00:58:50 +0000
commit5aa8b9e3b53fbac7667c6d8ee9a3e85992380321 (patch)
tree3b10f7b562a1fbde2c025a5eb66cefac4e64b2e5 /lib
parentb39b998a17e1f943f42d47f21bc08ae54fab8424 (diff)
[ruby/error_highlight] Handle very long lines
https://github.com/ruby/error_highlight/commit/383490a4b4
Diffstat (limited to 'lib')
-rw-r--r--lib/error_highlight/formatter.rb43
1 files changed, 43 insertions, 0 deletions
diff --git a/lib/error_highlight/formatter.rb b/lib/error_highlight/formatter.rb
index 20ca78d468..b4fce93e55 100644
--- a/lib/error_highlight/formatter.rb
+++ b/lib/error_highlight/formatter.rb
@@ -3,6 +3,8 @@ module ErrorHighlight
def self.message_for(spot)
# currently only a one-line code snippet is supported
if spot[:first_lineno] == spot[:last_lineno]
+ spot = truncate(spot)
+
indent = spot[:snippet][0...spot[:first_column]].gsub(/[^\t]/, " ")
marker = indent + "^" * (spot[:last_column] - spot[:first_column])
@@ -11,6 +13,47 @@ module ErrorHighlight
""
end
end
+
+ def self.viewport_size
+ Ractor.current[:__error_highlight_viewport_size__] || terminal_columns
+ end
+
+ def self.viewport_size=(viewport_size)
+ Ractor.current[:__error_highlight_viewport_size__] = viewport_size
+ end
+
+ private
+
+ def self.truncate(spot)
+ ellipsis = '...'
+ snippet = spot[:snippet]
+ diff = snippet.size - (viewport_size - ellipsis.size)
+
+ # snippet fits in the terminal
+ return spot if diff.negative?
+
+ if spot[:first_column] < diff
+ snippet = snippet[0...snippet.size - diff]
+ {
+ **spot,
+ snippet: snippet + ellipsis + "\n",
+ last_column: [spot[:last_column], snippet.size].min
+ }
+ else
+ {
+ **spot,
+ snippet: ellipsis + snippet[diff..-1],
+ first_column: spot[:first_column] - (diff - ellipsis.size),
+ last_column: spot[:last_column] - (diff - ellipsis.size)
+ }
+ end
+ end
+
+ def self.terminal_columns
+ # lazy load io/console in case viewport_size is set
+ require "io/console"
+ IO.console.winsize[1]
+ end
end
def self.formatter