Skip to content

Instantly share code, notes, and snippets.

@AlbertVeli
Created November 8, 2024 11:27
Show Gist options
  • Save AlbertVeli/7e60d623949014ec1b515b20099aabbc to your computer and use it in GitHub Desktop.
Save AlbertVeli/7e60d623949014ec1b515b20099aabbc to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import re
import sys
def visible_length(s):
# Remove ANSI escape sequences
ansi_escape = re.compile(r'\x1b\[[0-9;]*[mK]')
stripped = ansi_escape.sub('', s)
return len(stripped)
def wrap_line(line, max_visible_length=80):
wrapped_lines = []
visible_count = 0
current_line = ''
ansi_buffer = ''
in_escape = False
for char in line:
if char == '\x1b': # Start of escape sequence
in_escape = True
ansi_buffer += char
elif in_escape:
ansi_buffer += char
if char.isalpha(): # End of escape sequence
in_escape = False
current_line += ansi_buffer
ansi_buffer = ''
else:
# Count visible characters
current_line += char
if char not in '\x1b':
visible_count += 1
# Check if the current visible length exceeds the limit
if visible_count >= max_visible_length and not in_escape:
# TODO: only add '\xb1b[0m' if the next line starts with
# setting a color.
wrapped_lines.append(current_line + '\x1b[0m')
current_line = ''
visible_count = 0
if current_line:
wrapped_lines.append(current_line)
return '\n'.join(wrapped_lines)
def process_file(file_path):
"""
Read ANS with cp437 encoding, wrap lines, and print the output.
"""
with open(file_path, 'r', encoding='cp437') as file:
for line in file:
# Stop processing if the file contains a SAUCE record
if line.startswith('\x1aSAUCE00'):
return
wrapped = wrap_line(line.rstrip('\n'))
print(wrapped)
process_file(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment