Created
August 4, 2024 18:44
-
-
Save iwconfig/25fb1d81bf4f99e4938611ad5570c632 to your computer and use it in GitHub Desktop.
Wraps regular text or shell commands by a specific width. Does hard wraps, word wraps and shell wraps. Handles prefixes and suffixes, initial and subsequent. Returns a wrapped string by default.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import shlex | |
def wrap(string, width, prefix='', initial_prefix='', subsequent_prefix='', suffix='', initial_suffix='', subsequent_suffix='', word_wrap=False, cmd_wrap=False, join=True, join_with='\n'): | |
lines = [] | |
if word_wrap or cmd_wrap: | |
for line in string.strip().splitlines(): | |
line_list = [] | |
line_length = 0 | |
for word in shlex.split(line, posix=False) if cmd_wrap else line.split(): | |
if line_length + len(word) <= width: | |
line_list.append(word) | |
line_length += len(word) + 1 | |
else: | |
lines.append(' '.join(line_list)) | |
line_list = [word] | |
line_length = len(word) + 1 | |
lines.append(' '.join(line_list)) | |
else: | |
for line in string.strip().splitlines(): | |
for i in range(0, len(line), width): | |
lines.append(line[i:i+width]) | |
lines = ( | |
[initial_prefix + prefix + lines[0] + suffix + (subsequent_suffix if cmd_wrap and len(lines)>1 else '') + initial_suffix] + | |
[ | |
subsequent_prefix | |
+ prefix | |
+ line | |
+ suffix | |
+ (subsequent_suffix if cmd_wrap and i<len(lines[1:]) else '') | |
for i, line in enumerate(lines[1:], 1) | |
] | |
) | |
return lines if not join else join_with.join(lines) | |
# Example | |
import shutil | |
terminal_width = shutil.get_terminal_size().columns - 6 | |
cmd = wrap(err.cmd, terminal_width-2, subsequent_prefix=' '*9, subsequent_suffix=' \\', cmd_wrap=True) | |
stderr = wrap(err.stderr, terminal_width, initial_prefix=' ', subsequent_prefix=' '*9) | |
print(f'COMMAND: {cmd}') | |
print(f'STDERR: {stderr}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment