Small scripts for BB Code

Redglyph

proud GASP member
Joined
August 29, 2020
Messages
10,370
Location
Good old Europe
In case that helps anyone, I'll put scripts here. At least, one for now.

I hate to repeat the same procedure all the time, so when I see the content of an update with the typical format (like here):
title1
one
two

title2
one
two

I just copy the whole list in the clipboard, and execute this Python script. Since the support for the clipboard is abysmal by default in Python (Tk would freeze or drop the content), I installed pyperclip.

pip install pyperclip

(in Linux, it's best to install with your installer than with pip, so yum / apt / zypper /…)

and my clipboard_to_bb.pyw script… is in the renamed file in attachment because I can't find how to paste it here (due to the escaped characters and other things that the forum interprets). :)

It puts back the modified BB Code into the clipboard, formatting the text and removing several things including the gremlins and empty lines:

title1
  • one
  • two

title2
  • one
  • two

Or, with the linked description I gave above, it produces this.


EDIT: I found how to show the code with PHP tags ;)
PHP:
#!/usr/bin/env python
"""
Converts lists to BB-formated lists and titles.
"""

import pyperclip as clip
import re, sys

def text_to_bb(text: str):
    # removes the gremlins and makes EOLs Unix-like
    repl_dict = dict((ord(a), ord(b)) for a,b in zip('“”´‘', '""\'\''))
    text = "\n" + text.replace('\r', '').translate(repl_dict) + "\n"
    # detects the titles and make them bold, remove unnecessary empty lines
    text = re.sub("^\n\n*(.+)\n", "\n[B]\\1[/B]\n", text, flags=re.MULTILINE)
    # encloses the lines under each title with LIST
    text = re.sub(r"((?:^(?!\[).+\n)+)", "[LIST]\n\\1[/LIST]\n", text, flags=re.MULTILINE)
    # itemizes those lines with "[*]"
    text = re.sub(r"(^(?!\[).+\n)", r"[*]\1", text, flags=re.MULTILINE)
    return text.strip()

def clipboard_to_bb():
    result = False
    try:
        text_in = clip.paste()
        text_out = text_to_bb(text_in)
        clip.copy(text_out)
        result = True        
    finally:
        pass
    return result

if __name__ == "__main__":
    clipboard_to_bb()
 
Last edited:
Joined
Aug 29, 2020
Messages
10,370
Location
Good old Europe
Back
Top Bottom