You can add support for new output formats (like HTML, Markdown, or custom terminal emulators) by subclassing Style and defining a __str__ method.
To implement a new style, you should:
- Define
attribute_names as a dictionary mapping attribute keys to their output tags. - Define an
end string for closing styles. - Implement
__str__ to handle the logic for foreground (self.fg), background (self.bg), and attributes (self.attributes).
Example implementation for HTML:
class HTMLStyle(Style):
attribute_names = dict(bold='b', li='li', code='code')
end = '<br/>\n'
def __str__(self):
result = ''
if self.bg and not self.bg.reset:
result += f'<span style="background-color: {self.bg.hex_code}">'
if self.fg and not self.fg.reset:
result += f'<font color="{self.fg.hex_code}">'
for attr in sorted(self.attributes):
if self.attributes[attr]:
result += '<' + self.attribute_names[attr] + '>'
for attr in reversed(sorted(self.attributes)):
if not self.attributes[attr]:
result += '</' + self.attribute_names[attr].split()[0] + '>'
if self.fg and self.fg.reset:
result += '</font>'
if self.bg and self.bg.reset:
result += '</span>'
return result
htmlcolors = StyleFactory(HTMLStyle)
class HTMLStyle(Style):
attribute_names = dict(bold='b', li='li', code='code')
end = '<br/>\n'
def __str__(self):
result = ''
if self.bg and not self.bg.reset:
result += f'<span style="background-color: {self.bg.hex_code}">'
if self.fg and not self.fg.reset:
result += f'<font color="{self.fg.hex_code}">'
for attr in sorted(self.attributes):
if self.attributes[attr]:
result += '<' + self.attribute_names[attr] + '>'
for attr in reversed(sorted(self.attributes)):
if not self.attributes[attr]:
result += '</' + self.attribute_names[attr].split()[0] + '>'
if self.fg and self.fg.reset:
result += '</font>'
if self.bg and self.bg.reset:
result += '</span>'
return result
htmlcolors = StyleFactory(HTMLStyle)