Add fitwidth.py script

This commit is contained in:
Akemi Izuko 2023-12-23 20:13:57 -07:00
parent e7aa96a606
commit 23a9f5227f
Signed by: akemi
GPG key ID: 8DE0764E1809E9FC
2 changed files with 62 additions and 23 deletions

51
bin/fitwidth.py Executable file
View file

@ -0,0 +1,51 @@
#!/usr/bin/env python3
import argparse, sys
# Parse args
parser = argparse.ArgumentParser(prog="FitWidth v1.0.0",
description='Fit text (stdin|file) to a given character width');
parser.add_argument('-t', '--truncate', action='store_true',
help='Truncate longer lines with a "..."');
parser.add_argument('-w', '--wrap', action='store_true',
help='Wrap longer lines across two lines with a ">" at the end');
parser.add_argument('width', type=int,
help='Wrap longer lines across two lines with a ">" at the end');
parser.add_argument('file', type=argparse.FileType('r'), nargs='?',
help="File to read from, instead of stdin");
args = parser.parse_args();
# Validate args
if not args.truncate and not args.wrap:
args.truncate = True
if args.width < 10:
print("Minimum width is 10")
exit(1);
if args.file is not None:
file = args.file
elif not sys.stdin.isatty():
file = sys.stdin
else:
print("Please provide a file or pipe in text to fit")
exit(1)
# Print out file
w = args.width
for line in file:
line = line.rstrip()
if len(line) > w:
if args.truncate:
print(line[:w-3] + "...")
else:
i = w-1
print(line[:i] + ">")
while i < len(line):
print(">" + line[i:i+w-1])
i += w-1
else:
print(line)
file.close()

View file

@ -67,10 +67,6 @@ html_template_bottom = lambda title, url : f"""
</body> </body>
""" + """ """ + """
<script> <script>
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
let style = document.createElement("style"); let style = document.createElement("style");
style.textContent= ` style.textContent= `
@ -103,25 +99,17 @@ html_template_bottom = lambda title, url : f"""
font-size: 16px ; font-size: 16px ;
}`; }`;
let loadtimes = [ if (!document.querySelector("#rikaichan-window")?.shadowRoot?.appendChild(style)) {
100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, const observer = new MutationObserver(() => {
200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, if (document.querySelector("#rikaichan-window")?.shadowRoot?.appendChild(style)) {
400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, 400, observer.disconnect();
]; }
});
(async function () { observer.observe(document.body, {
for (let i = 0; true; i++) { childList: true,
try { subtree: true, // remove if the parent is a direct parent
document.querySelector('#rikaichan-window').shadowRoot.appendChild(style); });
break; }
} catch {
if (i < loadtimes.length)
await sleep(loadtimes[i]);
else
await sleep(2000);
}
}
})()
</script> </script>
</html> </html>
""" """