12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- #!/usr/bin/python3
- import argparse
- import re
- from pygments.styles import get_all_styles
- from pygments.formatters import HtmlFormatter
- from os.path import exists as file_exists
- #docs.python.org/3/library/argparse.html#formatter-class
- parser = argparse.ArgumentParser(description="""This script gets style definitions from Pygments and prints them into CSS files. If the rule for the default element - the code block itself - has none defined, it adds a foreground color complementary to the background color.
- It also adds one extra class to each rule.
- Files are never overwritten but renamed until unique.
- These options apply:""",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
- parser.add_argument("-p", type=str, default='@import "../_common.css";', help="string to prepend to each css file's content")
- parser.add_argument("-c", type=str, default="pcpg",help="the class added to each css rule")
- parser.add_argument("-f", type=str, default="custom-",help="prefix each filename with this")
- parser.add_argument("-l", default=False, action="store_true", help="only list style names")
- args = parser.parse_args()
- styles=sorted(list(get_all_styles()))
- if(args.l == True):
- for style in styles:
- print(style)
- else:
- def complementaryColor(my_hex):
- """Returns complementary RGB color
- Example:
- >>>complementaryColor('FFFFFF')
- '000000'
- """
- rgb = (my_hex[0:2], my_hex[2:4], my_hex[4:6])
- comp = ['%02X' % (255 - int(a, 16)) for a in rgb]
- return ''.join(comp)
- for style in styles:
- fn = '%s%s' % (args.f,style)
- while file_exists(fn+'.css'):
- fn=fn+'_'
- fn=fn+'.css'
- with open(fn,'x') as f:
- print('Writing ' + fn)
- f.write(args.p + '\n')
- css = HtmlFormatter(style=style).get_style_defs('.'+args.c)
- # remove lines containing "line-height:" or ".linenos"
- css = "\n".join([x.strip() for x in css.splitlines() if "line-height:" not in x and ".linenos" not in x])
- bg=re.findall('\n\.'+args.c+' +\{ *background: *#(......); *}',css) # Can we find a rule that defines the default background only, but not the foreground?
- if bg: # If yes, we add the foreground as a complementary color of the background:
- comp=complementaryColor(bg[0])
- css=re.sub('\n\.'+args.c+' +\{ *background: *#'+bg[0]+'; *}','\n.'+args.c+' {background:#'+bg[0]+';color:#'+comp+';} /* Modified by '+__file__.split('/')[-1]+' */',css,1)
- css = re.sub("\n\."+args.c+" +\{","\npre."+args.c+", code."+args.c+" {",css,1)
- f.write(css)
- f.close()
|