#!/usr/bin/env python
###############################################################################
# PyBBCodePreview 1.0 - PyBBCodePreview.py
# Copyright (c) 2006 Andrew J. Bennieston
# Released under the terms of the BSD license
# http://www.opensource.org/licenses/bsd-license.php
###############################################################################
import re, string, sys
# Replacements which can be made directly, without context or regexp groups
simple_replacements = [ ('<', '<'),
('>', '>'),
(r'\[b]', ""),
(r'\[/b]', ""),
(r'\[i]', ""),
(r'\[/i]', ""),
(r'\[u]', ""),
(r'\[/u]', ""),
(r'\[list]', "
"),
(r'\[img]', ''),
(r'\[\*]', "- "),
(r'\[code]', '
'),
(r'\[/code]', '
'),
('\n', '
\n')
]
def urlreplace1(m):
return '' + m.group(2) + ''
def urlreplace2(m):
return '' + m.group(1) + ''
def listreplace(m):
retstr = ""
if m.group(1) == "[list=a]":
retstr = ''
else:
retstr = ''
retstr += m.group(2)
retstr += '
'
return retstr
def sizereplace(m):
# Use to make replacements. It isn't the tidiest way of doing
# things, but it works
retstr = '' + m.group(2) + ''
return retstr
def colorreplace(m):
# Use to make replacements. It isn't the tidiest way of doing
# things, but it works
retstr = ''
retstr += m.group(2) + ''
return retstr
# Open the file specified in argv[1], read contents, and close it
if len(sys.argv) != 3:
print "Usage: " + sys.argv[0] + " infile outfile"
sys.exit(1)
infile = open(sys.argv[1], "r")
bbcode = infile.read()
infile.close()
# First make the simple replacements
for pattern in simple_replacements:
obj = re.compile(pattern[0], re.IGNORECASE | re.MULTILINE)
bbcode = obj.sub(pattern[1], bbcode)
# Replace lists
obj = re.compile(r'(\[list=\w])(.+?)\[/list]', re.IGNORECASE | re.MULTILINE)
bbcode = obj.sub(listreplace, bbcode)
# Replace sizes
obj = re.compile(r'\[size=(\d\d?)](.+?)\[/size]', re.IGNORECASE | re.MULTILINE)
bbcode = obj.sub(sizereplace, bbcode)
# Replace colours
obj = re.compile(r'\[color=(.+?)](.+?)\[/color]', re.IGNORECASE | re.MULTILINE)
bbcode = obj.sub(colorreplace, bbcode)
# Replace URLs
obj = re.compile(r'\[url=(.+?)](.+?)\[/url]', re.IGNORECASE | re.MULTILINE)
bbcode = obj.sub(urlreplace1, bbcode)
obj = re.compile(r'\[url](.+?)\[/url]', re.IGNORECASE | re.MULTILINE)
bbcode = obj.sub(urlreplace2, bbcode)
# Open output file, write bbcode string, close file
outfile = open(sys.argv[2], "w")
header = """
BBCode Preview
This preview was generated using PyBBCodePreview 1.0
Some formatting may not appear exactly as on the destination forum.
"""
footer = """
PyBBCodePreview 1.0 is released under the BSD License.
"""
outfile.write(header)
outfile.write(bbcode)
outfile.write(footer)
outfile.close()