Fix IndexError in `Strings::Wrap.wrap` and correct ANSI color insertion on wrap
Describe the change
When wrapping lines, reset the insertion index of carried-over ANSI codes to 0 so that they are always applied at the start of the new line.
This probably fixes #4 and #16.
Why are we doing this?
1. Prevent IndexError
When an ANSI code appeared at the end of a line, and the wrapped remainder of the text was shorter, the code was reinserted at an out-of-range position on the next line, causing an IndexError. Resetting the insertion position resolves this issue.
Repro:
Strings::Wrap.wrap("aaaaaaa \e[31mbb", 8)
# /Users/.../strings/wrap.rb:158:in `String#insert': index 8 out of string (IndexError)
# from ... Strings::Wrap.wrap
2. Preserve ANSI stack when reapplying colors
insert_ansi kept using the original insert index from the previous line, so carry-over codes without resets were reinserted at the wrong position.
Resetting every pending entry to [code, 0] to be applied at the line start, which prevents misplaced inserts and lets nested codes line up correctly.
Repro:
Strings::Wrap.wrap("aaaa \e[31mbbbb \e[32mcc", 5)
Expected:
aaaa
\e[31mbbbb \e[0m
\e[31m\e[32mcc\e[0m\e[0m
Actual:
aaaa
bbbb
cc\e[0\e[32m\e[31mm\e[0m
Benefits
- Prevents
IndexErrorcaused by reinserting ANSI codes past string boundaries - Ensures ANSI color state is reapplied consistently across wrapped lines
Drawbacks
Requirements
- [x] Tests written & passing locally?
- [x] Code style checked?
- [x] Rebased with
masterbranch? - [x] Documentation updated?
- [x] Changelog updated?