Last active
February 21, 2019 22:45
-
-
Save reagle/60aca3f41e6ea0a4e2dee926ca6322af to your computer and use it in GitHub Desktop.
Sublime Text plugin for editing emails in Thunderbird/exteditor; it unmangles MS Outlook safelinks and wraps quotes
This file contains 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
import re | |
import sublime # https://www.sublimetext.com/docs/3/api_reference.html | |
import sublime_plugin | |
import textwrap | |
import urllib | |
# | |
def unsafe_links(content): | |
"""remove annoying outlook link protection | |
""" | |
RE_SAFELINK = re.compile( | |
r""" | |
(https://na\d\d\.safelinks.+\?url=) # MS link | |
(.+) # encoded URL | |
(&data=.*?&reserved=0) # closing cruft | |
""", | |
re.VERBOSE, | |
) | |
for match in RE_SAFELINK.finditer(content): | |
# print("match = '%s'" % (match)) | |
safe_url = match.group(0) | |
# print("safe_url = '%s'" % (safe_url)) | |
encoded_url = match.groups()[1] | |
# print("encoded_url = '%s'" % (encoded_url)) | |
decoded_url = urllib.parse.unquote(encoded_url) | |
# print("decoded_url = '%s'" % (decoded_url)) | |
content = content.replace(safe_url, decoded_url) | |
return content | |
def format_email(content): | |
""" find long quoted lines and wrap; collapse empty lines | |
""" | |
new_content = [] | |
for line in content.split('\n'): | |
if line.startswith('>'): | |
line = textwrap.fill(line, 70).strip() | |
if not line.isspace(): | |
line = line.replace('\n', '\n> ') | |
new_content.append(line) | |
new_content = '\n'.join(new_content) | |
new_content = re.sub(r'\n\s*\n', '\n\n', new_content) # collapse empty | |
return(new_content) | |
class UnmangleSafelinks(sublime_plugin.TextCommand): | |
def run(self, edit): | |
# print("=====================================") | |
region = sublime.Region(0, self.view.size()) | |
text = self.view.substr(region) | |
# print("text = '%s'" % (text)) | |
unsafe_text = unsafe_links(text) | |
# print("unsafe_text = '%s'" % (unsafe_text)) | |
formatted_text = format_email(unsafe_text) | |
# print("formatted_text = '%s'" % (formatted_text)) | |
self.view.replace(edit, region, formatted_text) | |
self.view.run_command("goto_line", {"line": 7}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment