Rivista/rivista/gmi/markdown.py

53 lines
1.8 KiB
Python
Raw Normal View History

#!/usr/bin/python
# -*- coding: utf-8 -*-
class GmiMarkdown:
def convert_to_gmi(markdown_text):
lines = markdown_text.splitlines()
footnotes = []
footnote_counter = 1
output_lines = []
for line in lines:
# Process links in the format [text](url)
while True:
start_bracket = line.find('[')
if start_bracket == -1:
break # No more links in this line
end_bracket = line.find(']', start_bracket)
if end_bracket == -1:
break # Malformed link; exit loop
start_parenthesis = line.find('(', end_bracket)
if start_parenthesis == -1:
break # Malformed link; exit loop
end_parenthesis = line.find(')', start_parenthesis)
if end_parenthesis == -1:
break # Malformed link; exit loop
link_text = line[start_bracket + 1:end_bracket]
url = line[start_parenthesis + 1:end_parenthesis]
# Add footnote
footnotes.append(f" [{footnote_counter}]: {link_text}{url}")
footnote_marker = f"{link_text}[{footnote_counter}]"
footnote_counter += 1
# Replace link with footnote marker
line = line[:start_bracket] + footnote_marker + line[end_parenthesis + 1:]
# Remove Markdown header markers
if line.startswith('#'):
line = line.lstrip('# ').strip()
output_lines.append(line.strip())
# Combine output lines and footnotes
output_text = "\n".join(output_lines).strip()
footnotes_text = "\n".join(footnotes)
return f"{output_text}\n\n{footnotes_text}" if footnotes else output_text