Make line wrapping a command line argument (since it breaks color)

This commit is contained in:
Andrej Antunovikj 2020-03-06 09:54:29 +04:00
parent 6c017f3b96
commit 5e4f844770
1 changed files with 27 additions and 17 deletions

44
av98.py
View File

@ -68,8 +68,9 @@ _MIME_HANDLERS = {
"text/gemini": "cat %s",
}
def fix_ipv6_url(url):
if not url.count(":") > 2: # Best way to detect them?
if not url.count(":") > 2: # Best way to detect them?
return url
# If there's a pair of []s in there, it's probably fine as is.
if "[" in url and "]" in url:
@ -84,12 +85,13 @@ def fix_ipv6_url(url):
else:
schema, schemaless = None, url
if "/" in schemaless:
netloc, rest = schemaless.split("/",1)
netloc, rest = schemaless.split("/", 1)
schemaless = "[" + netloc + "]" + "/" + rest
if schema:
return schema + "://" + schemaless
return schemaless
standard_ports = {
"gemini": 1965,
"gopher": 70,
@ -97,6 +99,7 @@ standard_ports = {
"https": 443,
}
class GeminiItem():
def __init__(self, url, name=""):
@ -209,6 +212,7 @@ class GeminiClient(cmd.Cmd):
"timeout" : 10,
"gopher_proxy" : "localhost:1965",
"width" : 80,
"wraplines" : False,
"auto_follow_redirects" : True,
}
@ -344,10 +348,10 @@ Slow internet connection? Use 'set timeout' to be more patient.""")
body = f.read()
# Save the result in a temporary file
## Delete old file
# Delete old file
if self.tmp_filename:
os.unlink(self.tmp_filename)
## Set file mode
# Set file mode
if mime.startswith("text/"):
mode = "w"
encoding = mime_options.get("charset", "UTF-8")
@ -359,7 +363,7 @@ Slow internet connection? Use 'set timeout' to be more patient.""")
else:
mode = "wb"
encoding = None
## Write
# Write
tmpf = tempfile.NamedTemporaryFile(mode, encoding=encoding, delete=False)
size = tmpf.write(body)
tmpf.close()
@ -414,7 +418,7 @@ Slow internet connection? Use 'set timeout' to be more patient.""")
context.options | ssl.OP_NO_SSLv3
context.options | ssl.OP_NO_SSLv2
context.set_ciphers("AES+DHE:AES+ECDHE:CHACHA20+DHE:CHACHA20+ECDHE:!SHA1:@STRENGTH")
#print(context.get_ciphers())
# print(context.get_ciphers())
s = context.wrap_socket(s, server_hostname = gi.host)
try:
s.connect(address[4])
@ -488,7 +492,10 @@ Slow internet connection? Use 'set timeout' to be more patient.""")
except:
self._debug("Skipping possible link: %s" % line)
else:
tmpf.write(textwrap.fill(line, self.options["width"]) + "\n")
if(self.options["wraplines"]):
tmpf.write(textwrap.fill(line, self.options["width"]) + "\n")
else:
tmpf.write(line + "\n")
tmpf.close()
self.lookup = self.index
@ -574,7 +581,7 @@ Slow internet connection? Use 'set timeout' to be more patient.""")
self.index_index = n
self._go_to_gi(gi)
### Settings
# Settings
def do_set(self, line):
"""View or set various options."""
if not line.strip():
@ -615,6 +622,8 @@ Slow internet connection? Use 'set timeout' to be more patient.""")
except ValueError:
pass
self.options[option] = value
def do_wraplines(self, line):
self.options["wraplines"] = True
def do_handler(self, line):
"""View or set handler commands for different MIME types."""
@ -634,7 +643,7 @@ Slow internet connection? Use 'set timeout' to be more patient.""")
if "%s" not in handler:
print("Are you sure you don't want to pass the filename to the handler?")
### Stuff for getting around
# Stuff for getting around
def do_go(self, line):
"""Go to a gemini URL or marked item."""
line = line.strip()
@ -755,7 +764,7 @@ Think of it like marks in vi: 'mark a'='ma' and 'go a'=''a'."""
else:
print("Invalid mark, must be one letter")
### Stuff that modifies the lookup table
# Stuff that modifies the lookup table
def do_ls(self, line):
"""List contents of current index.
Use 'ls -l' to see URLs."""
@ -788,7 +797,7 @@ Use 'ls -l' to see URLs."""
self._show_lookup(offset=i, end=i+10)
self.page_index += 10
### Stuff that does something to most recently viewed item
# Stuff that does something to most recently viewed item
@needs_gi
def do_cat(self, *args):
"""Run most recently visited item through "cat" command."""
@ -893,7 +902,7 @@ Use 'ls -l' to see URLs."""
"""Print URL of most recently visited item."""
print(self.gi.url)
### Bookmarking stuff
# Bookmarking stuff
@needs_gi
def do_add(self, line):
"""Add the current URL to the bookmarks menu.
@ -914,7 +923,7 @@ Bookmarks are stored in the ~/.av98-bookmarks.txt file."""
gi = GeminiItem("localhost/" + bm_file)
self._handle_index(body, gi)
### Help
# Help
def do_help(self, arg):
"""ALARM! Recursion detected! ALARM! Prepare to eject!"""
if arg == "!":
@ -924,7 +933,7 @@ Bookmarks are stored in the ~/.av98-bookmarks.txt file."""
else:
cmd.Cmd.do_help(self, arg)
### Flight recorder
# Flight recorder
def do_blackbox(self, *args):
"""Display contents of flight recorder, showing statistics for the
current gemini browsing session."""
@ -956,7 +965,7 @@ current gemini browsing session."""
for key, value in lines:
print(key.ljust(24) + str(value).rjust(8))
### The end!
# The end!
def do_quit(self, *args):
"""Exit AV-98."""
# Clean up after ourself
@ -988,8 +997,8 @@ def main():
help='start with your list of bookmarks')
parser.add_argument('url', metavar='URL', nargs='*',
help='start with this URL')
parser.add_argument('--wraplines', '-w', action='store_true', help='Wrap long lines (breaks color, off by default)')
args = parser.parse_args()
# Instantiate client
gc = GeminiClient()
@ -1026,7 +1035,8 @@ def main():
url = "gemini://" + url
gc.cmdqueue.append("tour %s" % url)
gc.cmdqueue.append("tour")
elif args.wraplines:
gc.cmdqueue.append("wraplines")
# Endless interpret loop
while True:
try: