Module: Kramdown::ANSI::Width
- Extended by:
- Term::ANSIColor
- Includes:
- Term::ANSIColor
- Included in:
- Kramdown::ANSI
- Defined in:
- lib/kramdown/ansi/width.rb
Class Method Summary collapse
-
.truncate(text, percentage: nil, length: nil, ellipsis: ?…) ⇒ String
Truncates a given string to a specified length or percentage.
-
.width(percentage: 100.0) ⇒ Integer
Returns the width of the terminal in characters, given a percentage.
-
.wrap(text, percentage: nil, length: nil) ⇒ String
Wraps text to a specified width.
Class Method Details
.truncate(text, percentage: nil, length: nil, ellipsis: ?…) ⇒ String
Truncates a given string to a specified length or percentage. If the text is longer an ellipsis sequence is added at the end of the generated string, to indicate that a truncation has been performed.
48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/kramdown/ansi/width.rb', line 48 def truncate(text, percentage: nil, length: nil, ellipsis: ?…) percentage.nil? ^ length.nil? or raise ArgumentError, "either pass percentage or length argument" percentage and length ||= width(percentage:) ellipsis_length = ellipsis.size if length < ellipsis_length +'' elsif text.size >= length + ellipsis_length text[0, length - ellipsis_length] + ellipsis else text end end |
.width(percentage: 100.0) ⇒ Integer
Returns the width of the terminal in characters, given a percentage.
14 15 16 |
# File 'lib/kramdown/ansi/width.rb', line 14 def width(percentage: 100.0) ((Float(percentage) * Tins::Terminal.columns) / 100).floor end |
.wrap(text, percentage: nil, length: nil) ⇒ String
Wraps text to a specified width.
25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/kramdown/ansi/width.rb', line 25 def wrap(text, percentage: nil, length: nil) percentage.nil? ^ length.nil? or raise ArgumentError, "either pass percentage or length argument" percentage and length ||= width(percentage:) text.gsub(/(?<!\n)\n(?!\n)/, ' ').lines.map do |line| if length >= 1 && uncolor { line }.length > length line.gsub(/(.{1,#{length}})(\s+|$)/, "\\1\n").strip else line.strip end end * ?\n end |