Skip to content

Conversation

@onk
Copy link

@onk onk commented Nov 9, 2025

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 IndexError caused by reinserting ANSI codes past string boundaries
  • Ensures ANSI color state is reapplied consistently across wrapped lines

Drawbacks

Requirements

  • Tests written & passing locally?
  • Code style checked?
  • Rebased with master branch?
  • Documentation updated?
  • Changelog updated?

onk added 3 commits November 9, 2025 15:47
Fixes an IndexError raised when an ANSI code starts at the end of a wrapped line and carries over to a shorter next line.
The carry-over kept the original column index, so insert_ansi tried to insert beyond the new string length.

Normalize carried-over ANSI entries to [code, 0] so they always reapply at the beginning of the next line.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Wrapping strings with multiple ascii color styling segements mangles string contents

1 participant