Method: Strings::Wrap.format_line

Defined in:
lib/strings/wrap.rb

.format_line(text_line, wrap_at, ansi_stack) ⇒ Array[String]

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Format line to be maximum of wrap_at length

Parameters:

  • text_line (String)

    the line to format

  • wrap_at (Integer)

    the maximum length to wrap the line

Returns:

  • (Array[String])

    the wrapped lines



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/strings/wrap.rb', line 46

def format_line(text_line, wrap_at, ansi_stack)
  lines = []
  line  = []
  word  = []
  ansi  = []
  ansi_matched = false
  word_length = 0
  line_length = 0
  char_length = 0 # visible char length
  text_length = display_width(text_line)
  total_length = 0

  UnicodeUtils.each_grapheme(text_line) do |char|
    # we found ansi let's consume
    if char == Strings::ANSI::CSI || ansi.length > 0
      ansi << char
      if Strings::ANSI.only_ansi?(ansi.join)
        ansi_matched = true
      elsif ansi_matched
        ansi_stack << [ansi[0...-1].join, line_length + word_length]
        ansi_matched = false

        if ansi.last == Strings::ANSI::CSI
          ansi = [ansi.last]
        else
          ansi = []
        end
      end
      next if ansi.length > 0
    end

    char_length = display_width(char)
    total_length += char_length
    if line_length + word_length + char_length <= wrap_at
      if char == SPACE || total_length == text_length
        line << word.join + char
        line_length += word_length + char_length
        word = []
        word_length = 0
      else
        word << char
        word_length += char_length
      end
      next
    end

    if char == SPACE # ends with space
      lines << insert_ansi(line.join, ansi_stack)
      line = []
      line_length = 0
      word << char
      word_length += char_length
    elsif word_length + char_length <= wrap_at
      lines << insert_ansi(line.join, ansi_stack)
      line = [word.join + char]
      line_length = word_length + char_length
      word = []
      word_length = 0
    else # hyphenate word - too long to fit a line
      lines << insert_ansi(word.join, ansi_stack)
      line_length = 0
      word = [char]
      word_length = char_length
    end
  end
  lines << insert_ansi(line.join, ansi_stack) unless line.empty?
  lines << insert_ansi(word.join, ansi_stack) unless word.empty?
  lines
end