lib/verse/wrapping.rb in verse-0.4.0 vs lib/verse/wrapping.rb in verse-0.5.0
- old
+ new
@@ -1,11 +1,11 @@
# coding: utf-8
module Verse
# A class responsible for text wrapping
class Wrapping
- DEFAULT_WIDTH = 80.freeze
+ DEFAULT_WIDTH = 80
# Initialize a Wrapping
#
# @param [String] text
# the text to be wrapped
@@ -13,13 +13,12 @@
# @param [Hash] options
# @option options [Symbol] :padding the desired spacing
#
# @api public
def initialize(text, options = {})
- @text = text
+ @text = text
@line_width = options.fetch(:line_width) { DEFAULT_WIDTH }
- @sanitizer = Sanitizer.new
end
# Wrap a text into lines no longer than wrap_at
#
# @api public
@@ -66,29 +65,29 @@
# @return [Array[String]]
# the wrapped lines
#
# @api private
def format_paragraph(paragraph, wrap_at, ansi_stack)
- cleared_para = @sanitizer.replace(paragraph)
+ cleared_para = Sanitizer.replace(paragraph)
lines = []
line = ''
- word = ''
+ word = ''
word_length = 0
line_length = 0
char_length = 0 # visible char length
text_length = display_width(cleared_para)
total_length = 0
ansi = ''
matched = nil
- UnicodeUtils.each_grapheme(cleared_para) do |char|
+ to_chars(cleared_para) do |char|
if char == ANSI # found ansi
ansi << char && next
end
if ansi.length > 0
ansi << char
- if @sanitizer.ansi?(ansi) # we found ansi let's consume
+ if Sanitizer.ansi?(ansi) # we found ansi let's consume
matched = ansi
elsif matched
ansi_stack << [matched[0...-1], line_length + word_length]
matched = nil
ansi = ''
@@ -171,13 +170,22 @@
end
ansi_stack.pop(to_remove) # remove used states
output
end
+ # @api private
+ def to_chars(text, &block)
+ if block_given?
+ UnicodeUtils.each_grapheme(text, &block)
+ else
+ UnicodeUtils.each_grapheme(text)
+ end
+ end
+
# Visible width of string
#
# @api private
def display_width(string)
- UnicodeUtils.display_width(@sanitizer.sanitize(string))
+ Unicode::DisplayWidth.of(Sanitizer.sanitize(string))
end
end # Wrapping
end # Verse