styles.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/python3
  2. import argparse
  3. import re
  4. from pygments.styles import get_all_styles
  5. from pygments.formatters import HtmlFormatter
  6. from os.path import exists as file_exists
  7. #docs.python.org/3/library/argparse.html#formatter-class
  8. 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.
  9. It also adds one extra class to each rule.
  10. Files are never overwritten but renamed until unique.
  11. These options apply:""",formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  12. parser.add_argument("-p", type=str, default='@import "../_common.css";', help="string to prepend to each css file's content")
  13. parser.add_argument("-c", type=str, default="pcpg",help="the class added to each css rule")
  14. parser.add_argument("-f", type=str, default="custom-",help="prefix each filename with this")
  15. parser.add_argument("-l", default=False, action="store_true", help="only list style names")
  16. args = parser.parse_args()
  17. styles=sorted(list(get_all_styles()))
  18. if(args.l == True):
  19. for style in styles:
  20. print(style)
  21. else:
  22. def complementaryColor(my_hex):
  23. """Returns complementary RGB color
  24. Example:
  25. >>>complementaryColor('FFFFFF')
  26. '000000'
  27. """
  28. rgb = (my_hex[0:2], my_hex[2:4], my_hex[4:6])
  29. comp = ['%02X' % (255 - int(a, 16)) for a in rgb]
  30. return ''.join(comp)
  31. for style in styles:
  32. fn = '%s%s' % (args.f,style)
  33. while file_exists(fn+'.css'):
  34. fn=fn+'_'
  35. fn=fn+'.css'
  36. with open(fn,'x') as f:
  37. print('Writing ' + fn)
  38. f.write(args.p + '\n')
  39. css = HtmlFormatter(style=style).get_style_defs('.'+args.c)
  40. # remove lines containing "line-height:" or ".linenos"
  41. css = "\n".join([x.strip() for x in css.splitlines() if "line-height:" not in x and ".linenos" not in x])
  42. bg=re.findall('\n\.'+args.c+' +\{ *background: *#(......); *}',css) # Can we find a rule that defines the default background only, but not the foreground?
  43. if bg: # If yes, we add the foreground as a complementary color of the background:
  44. comp=complementaryColor(bg[0])
  45. css=re.sub('\n\.'+args.c+' +\{ *background: *#'+bg[0]+'; *}','\n.'+args.c+' {background:#'+bg[0]+';color:#'+comp+';} /* Modified by '+__file__.split('/')[-1]+' */',css,1)
  46. css = re.sub("\n\."+args.c+" +\{","\npre."+args.c+", code."+args.c+" {",css,1)
  47. f.write(css)
  48. f.close()