Skip to content

Instantly share code, notes, and snippets.

@Mr-Destructive
Last active July 23, 2022 11:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mr-Destructive/752d52c7485bcb31ca822b25bddffe34 to your computer and use it in GitHub Desktop.
Save Mr-Destructive/752d52c7485bcb31ca822b25bddffe34 to your computer and use it in GitHub Desktop.
import re
import sys
# Usage
# script with the markdown file name
# hard_wrap.py sample.md
def hard_to_soft_wraps(content):
# pre= re.findall(r'\n---\n(.*?)\n```.*$', content, re.DOTALL)
# mid = re.findall(r'\n```\n(.*?)\n```(.*?)',content, re.DOTALL)
# post = re.findall(r'\n```\n\n(.*$)', content, re.DOTALL)
# get all fenced code block
fences = re.findall(r"\n```.*?```\n", content, re.DOTALL)
# get the frontmatter data
frontmatter = re.findall(r"---.*?---\n", content, re.DOTALL)
for fence in fences:
# set the new line character as some value //r to identify later
content = content.replace(fence, fence.replace("\n", "\\r"))
for attrib in frontmatter:
content = content.replace(attrib, attrib.replace("\n", "\\r"))
# Replace the new paragraph as a special character \\r
content = content.replace("\n\n", "\\r\\r")
# Replace the new heading with the special character
content = content.replace("\n#", "\\r\\r")
# Split the text for iterating over the contents
content = re.split("\\r\\r", content)
for w in content:
# replace the newline character which is a hard wrap into a whitespace
# then replace the special character with new line character
content = w.replace("\n", " ").replace("\\r", "\n")
# returned soft wrapped content
return content
filename = sys.argv[1]
with open(filename, 'r') as f:
content = f.read()
# content is the original text of the markdown file
# new_content as the converted text as soft wrapped
new_content = hard_to_soft_wraps(content)
print(new_content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment