#!/usr/bin/env python3 # Maintainer: Darks # Disclaimer: this script has been done as a quick n' dirty way to convert # markdown to Planète Casio's BBcode. As it, it does support only those # features: # - # H1 title # - ## H2 title # - ### H3 title # - *emphasis text* # - **strong text** # - [link](https://domain.tld) # - {{ tableofcontents }} # # More features may be added in the future, but this script is provided as it. import argparse, re, sys # Manage arguments parser = argparse.ArgumentParser( description="Convert Markdown to PC's BBcode") parser.add_argument("input", type=argparse.FileType('r'), help="input file") args = parser.parse_args() # Useful regex r_h1 = re.compile("^# (.+)$", re.I|re.M) r_h2 = re.compile("^## (.+)$", re.I|re.M) r_h3 = re.compile("^### (.+)$", re.I|re.M) r_link = re.compile("(\W)\[(.+?)\]\((.+?)\)(\W)", re.I|re.M) r_strong = re.compile("(\W|^)\*{2}(\w.+?)\*{2}(\W|$)", re.I|re.M) r_em = re.compile("(\W|^)\*(\w.+?)\*(\W|$)", re.I|re.M) # Open and extract document markdown = args.input.read().splitlines() # Manage titles table_of_contents = "" n_h1 = 0 n_h2 = 0 n_h3 = 0 output = [] # TODO: factorize this pile of shit for line in markdown: if (res := r_h1.search(line)): n_h1 += 1 n_h2 = 0 n_h3 = 0 header = res.group(1) index = f"{n_h1}" label = index.replace(".", "_") table_of_contents += f"[target={label}]{index} – {header}[/target]\n" output.append(f"[big][brown][b]{index} – {header}[/b][/brown][/big]" f"[label={index}]") elif (res := r_h2.search(line)): n_h2 += 1 n_h3 = 0 header = res.group(1) index = f"{n_h1}.{n_h2}" label = index.replace(".", "_") table_of_contents += f"    [target={label}]{index} – {header}[/target]\n" output.append(f"[brown][b]{index} – {header}[/b][/brown]" f"[label={label}]") elif (res := r_h3.search(line)): n_h3 += 1 header = res.group(1) index = f"{n_h1}.{n_h2}.{n_h3}" label = index.replace(".", "_") table_of_contents += f"        [target={label}]{index} – {header}[/target]\n" output.append(f"[b]{index} – {header}[/b]" f"[label={label}]") else: res = r_link.sub( lambda m: f"{m.group(1)}[url={m.group(3)}]{m.group(2)}[/url]{m.group(4)}", line) res = r_strong.sub( lambda m: f"{m.group(1)}[b]{m.group(2)}[/b]{m.group(3)}", res) res = r_em.sub( lambda m: f"{m.group(1)}[i]{m.group(2)}[/i]{m.group(3)}", res) output.append(res) # Add table of content output = '\n'.join(output) output = re.sub("{{ tableofcontents }}", table_of_contents, output) # Print output on stdout print(output)