home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 January / maximum-cd-2011-01.iso / DiscContents / calibre-0.7.26.msi / file_2350 (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2010-10-31  |  13.8 KB  |  448 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.6)
  3.  
  4. import os
  5. import sys
  6. import StringIO
  7. from pygments.formatter import Formatter
  8. from pygments.token import Token, Text, STANDARD_TYPES
  9. from pygments.util import get_bool_opt, get_int_opt, get_list_opt, bytes
  10. __all__ = [
  11.     'HtmlFormatter']
  12.  
  13. def escape_html(text):
  14.     return text.replace('&', '&').replace('<', '<').replace('>', '>').replace('"', '"').replace("'", ''')
  15.  
  16.  
  17. def get_random_id():
  18.     random = random
  19.     import random
  20.     time = time
  21.     import time
  22.     
  23.     try:
  24.         sha = sha1
  25.         import hashlib
  26.     except ImportError:
  27.         import sha
  28.         sha = sha.new
  29.  
  30.     return sha('%s|%s' % (random(), time())).hexdigest()
  31.  
  32.  
  33. def _get_ttype_class(ttype):
  34.     fname = STANDARD_TYPES.get(ttype)
  35.     if fname:
  36.         return fname
  37.     aname = ''
  38.     while fname is None:
  39.         aname = '-' + ttype[-1] + aname
  40.         ttype = ttype.parent
  41.         fname = STANDARD_TYPES.get(ttype)
  42.         continue
  43.         fname
  44.     return fname + aname
  45.  
  46. CSSFILE_TEMPLATE = 'td.linenos { background-color: #f0f0f0; padding-right: 10px; }\nspan.lineno { background-color: #f0f0f0; padding: 0 5px 0 5px; }\npre { line-height: 125%%; }\n%(styledefs)s\n'
  47. DOC_HEADER = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"\n   "http://www.w3.org/TR/html4/strict.dtd">\n\n<html>\n<head>\n  <title>%(title)s</title>\n  <meta http-equiv="content-type" content="text/html; charset=%(encoding)s">\n  <style type="text/css">\n' + CSSFILE_TEMPLATE + '\n  </style>\n</head>\n<body>\n<h2>%(title)s</h2>\n\n'
  48. DOC_HEADER_EXTERNALCSS = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"\n   "http://www.w3.org/TR/html4/strict.dtd">\n\n<html>\n<head>\n  <title>%(title)s</title>\n  <meta http-equiv="content-type" content="text/html; charset=%(encoding)s">\n  <link rel="stylesheet" href="%(cssfile)s" type="text/css">\n</head>\n<body>\n<h2>%(title)s</h2>\n\n'
  49. DOC_FOOTER = '</body>\n</html>\n'
  50.  
  51. class HtmlFormatter(Formatter):
  52.     name = 'HTML'
  53.     aliases = [
  54.         'html']
  55.     filenames = [
  56.         '*.html',
  57.         '*.htm']
  58.     
  59.     def __init__(self, **options):
  60.         Formatter.__init__(self, **options)
  61.         self.title = self._decodeifneeded(self.title)
  62.         self.nowrap = get_bool_opt(options, 'nowrap', False)
  63.         self.noclasses = get_bool_opt(options, 'noclasses', False)
  64.         self.classprefix = options.get('classprefix', '')
  65.         self.cssclass = self._decodeifneeded(options.get('cssclass', 'highlight'))
  66.         self.cssstyles = self._decodeifneeded(options.get('cssstyles', ''))
  67.         self.prestyles = self._decodeifneeded(options.get('prestyles', ''))
  68.         self.cssfile = self._decodeifneeded(options.get('cssfile', ''))
  69.         self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile', False)
  70.         linenos = options.get('linenos', False)
  71.         if linenos == 'inline':
  72.             self.linenos = 2
  73.         elif linenos:
  74.             self.linenos = 1
  75.         else:
  76.             self.linenos = 0
  77.         self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
  78.         self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
  79.         self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))
  80.         self.nobackground = get_bool_opt(options, 'nobackground', False)
  81.         self.lineseparator = options.get('lineseparator', '\n')
  82.         self.lineanchors = options.get('lineanchors', '')
  83.         self.anchorlinenos = options.get('anchorlinenos', False)
  84.         self.hl_lines = set()
  85.         for lineno in get_list_opt(options, 'hl_lines', []):
  86.             
  87.             try:
  88.                 self.hl_lines.add(int(lineno))
  89.             continue
  90.             except ValueError:
  91.                 continue
  92.             
  93.  
  94.         
  95.         self._class_cache = { }
  96.         self._create_stylesheet()
  97.  
  98.     
  99.     def _get_css_class(self, ttype):
  100.         if ttype in self._class_cache:
  101.             return self._class_cache[ttype]
  102.         return self.classprefix + _get_ttype_class(ttype)
  103.  
  104.     
  105.     def _create_stylesheet(self):
  106.         t2c = self.ttype2class = {
  107.             Token: '' }
  108.         c2s = self.class2style = { }
  109.         cp = self.classprefix
  110.         for ttype, ndef in self.style:
  111.             name = cp + _get_ttype_class(ttype)
  112.             style = ''
  113.             if ndef['color']:
  114.                 style += 'color: #%s; ' % ndef['color']
  115.             
  116.             if ndef['bold']:
  117.                 style += 'font-weight: bold; '
  118.             
  119.             if ndef['italic']:
  120.                 style += 'font-style: italic; '
  121.             
  122.             if ndef['underline']:
  123.                 style += 'text-decoration: underline; '
  124.             
  125.             if ndef['bgcolor']:
  126.                 style += 'background-color: #%s; ' % ndef['bgcolor']
  127.             
  128.             if ndef['border']:
  129.                 style += 'border: 1px solid #%s; ' % ndef['border']
  130.             
  131.             if style:
  132.                 t2c[ttype] = name
  133.                 c2s[name] = (style[:-2], ttype, len(ttype))
  134.                 continue
  135.         
  136.  
  137.     
  138.     def get_style_defs(self, arg = None):
  139.         if arg is None:
  140.             if not 'cssclass' in self.options or '.' + self.cssclass:
  141.                 pass
  142.             arg = ''
  143.         
  144.         if isinstance(arg, basestring):
  145.             args = [
  146.                 arg]
  147.         else:
  148.             args = list(arg)
  149.         
  150.         def prefix(cls):
  151.             if cls:
  152.                 cls = '.' + cls
  153.             
  154.             tmp = []
  155.             for arg in args:
  156.                 if not arg or arg + ' ':
  157.                     pass
  158.                 tmp.append('' + cls)
  159.             
  160.             return ', '.join(tmp)
  161.  
  162.         styles = _[1]
  163.         styles.sort()
  164.         lines = [ '%s { %s } /* %s */' % (prefix(cls), style, repr(ttype)[6:]) for level, ttype, cls, style in styles ]
  165.         return '\n'.join(lines)
  166.  
  167.     
  168.     def _decodeifneeded(self, value):
  169.         if isinstance(value, bytes):
  170.             if self.encoding:
  171.                 return value.decode(self.encoding)
  172.             return value.decode()
  173.         return value
  174.  
  175.     
  176.     def _wrap_full(self, inner, outfile):
  177.         if self.cssfile:
  178.             if os.path.isabs(self.cssfile):
  179.                 cssfilename = self.cssfile
  180.             else:
  181.                 
  182.                 try:
  183.                     filename = outfile.name
  184.                     if not filename or filename[0] == '<':
  185.                         raise AttributeError
  186.                     filename[0] == '<'
  187.                     cssfilename = os.path.join(os.path.dirname(filename), self.cssfile)
  188.                 except AttributeError:
  189.                     print >>sys.stderr, 'Note: Cannot determine output file name, using current directory as base for the CSS file name'
  190.                     cssfilename = self.cssfile
  191.  
  192.             
  193.             try:
  194.                 if not os.path.exists(cssfilename) or not (self.noclobber_cssfile):
  195.                     cf = open(cssfilename, 'w')
  196.                     cf.write(CSSFILE_TEMPLATE % {
  197.                         'styledefs': self.get_style_defs('body') })
  198.                     cf.close()
  199.             except IOError:
  200.                 err = None
  201.                 err.strerror = 'Error writing CSS file: ' + err.strerror
  202.                 raise 
  203.  
  204.             yield (0, DOC_HEADER_EXTERNALCSS % dict(title = self.title, cssfile = self.cssfile, encoding = self.encoding))
  205.         else:
  206.             yield (0, DOC_HEADER % dict(title = self.title, styledefs = self.get_style_defs('body'), encoding = self.encoding))
  207.         for t, line in inner:
  208.             yield (t, line)
  209.         
  210.         yield (0, DOC_FOOTER)
  211.  
  212.     
  213.     def _wrap_tablelinenos(self, inner):
  214.         dummyoutfile = StringIO.StringIO()
  215.         lncount = 0
  216.         for t, line in inner:
  217.             if t:
  218.                 lncount += 1
  219.             
  220.             dummyoutfile.write(line)
  221.         
  222.         fl = self.linenostart
  223.         mw = len(str(lncount + fl - 1))
  224.         sp = self.linenospecial
  225.         st = self.linenostep
  226.         la = self.lineanchors
  227.         aln = self.anchorlinenos
  228.         if sp:
  229.             lines = []
  230.             for i in range(fl, fl + lncount):
  231.                 if i % st == 0:
  232.                     if i % sp == 0:
  233.                         if aln:
  234.                             lines.append('<a href="#%s-%d" class="special">%*d</a>' % (la, i, mw, i))
  235.                         else:
  236.                             lines.append('<span class="special">%*d</span>' % (mw, i))
  237.                     elif aln:
  238.                         lines.append('<a href="#%s-%d">%*d</a>' % (la, i, mw, i))
  239.                     else:
  240.                         lines.append('%*d' % (mw, i))
  241.                 i % sp == 0
  242.                 lines.append('')
  243.             
  244.             ls = '\n'.join(lines)
  245.         else:
  246.             lines = []
  247.             for i in range(fl, fl + lncount):
  248.                 if i % st == 0:
  249.                     if aln:
  250.                         lines.append('<a href="#%s-%d">%*d</a>' % (la, i, mw, i))
  251.                     else:
  252.                         lines.append('%*d' % (mw, i))
  253.                 aln
  254.                 lines.append('')
  255.             
  256.             ls = '\n'.join(lines)
  257.         yield (0, '<table class="%stable">' % self.cssclass + '<tr><td class="linenos"><div class="linenodiv"><pre>' + ls + '</pre></div></td><td class="code">')
  258.         yield (0, dummyoutfile.getvalue())
  259.         yield (0, '</td></tr></table>')
  260.  
  261.     
  262.     def _wrap_inlinelinenos(self, inner):
  263.         lines = list(inner)
  264.         sp = self.linenospecial
  265.         st = self.linenostep
  266.         num = self.linenostart
  267.         mw = len(str(len(lines) + num - 1))
  268.         if sp:
  269.             for t, line in lines:
  270.                 if not num % sp == 0 or ' special':
  271.                     pass
  272.                 if not num % st or ' ':
  273.                     pass
  274.                 yield (1, '<span class="lineno%s">%*s</span> ' % ('', mw, num) + line)
  275.                 num += 1
  276.             
  277.         else:
  278.             for t, line in lines:
  279.                 if not num % st or ' ':
  280.                     pass
  281.                 yield (1, '<span class="lineno">%*s</span> ' % (mw, num) + line)
  282.                 num += 1
  283.             
  284.  
  285.     
  286.     def _wrap_lineanchors(self, inner):
  287.         s = self.lineanchors
  288.         i = 0
  289.         for t, line in inner:
  290.             if t:
  291.                 i += 1
  292.                 yield (1, '<a name="%s-%d"></a>' % (s, i) + line)
  293.                 continue
  294.             yield (0, line)
  295.         
  296.  
  297.     
  298.     def _wrap_div(self, inner):
  299.         style = []
  300.         if self.noclasses and not (self.nobackground) and self.style.background_color is not None:
  301.             style.append('background: %s' % (self.style.background_color,))
  302.         
  303.         if self.cssstyles:
  304.             style.append(self.cssstyles)
  305.         
  306.         style = '; '.join(style)
  307.         if self.cssclass:
  308.             pass
  309.         if style:
  310.             pass
  311.         yield (0, '<div' + ' class="%s"' % self.cssclass + ' style="%s"' % style + '>')
  312.         for tup in inner:
  313.             yield tup
  314.         
  315.         yield (0, '</div>\n')
  316.  
  317.     
  318.     def _wrap_pre(self, inner):
  319.         style = []
  320.         if self.prestyles:
  321.             style.append(self.prestyles)
  322.         
  323.         if self.noclasses:
  324.             style.append('line-height: 125%')
  325.         
  326.         style = '; '.join(style)
  327.         if style:
  328.             pass
  329.         yield (0, '<pre' + ' style="%s"' % style + '>')
  330.         for tup in inner:
  331.             yield tup
  332.         
  333.         yield (0, '</pre>')
  334.  
  335.     
  336.     def _format_lines(self, tokensource):
  337.         nocls = self.noclasses
  338.         lsep = self.lineseparator
  339.         getcls = self.ttype2class.get
  340.         c2s = self.class2style
  341.         lspan = ''
  342.         line = ''
  343.         for ttype, value in tokensource:
  344.             if nocls:
  345.                 cclass = getcls(ttype)
  346.                 while cclass is None:
  347.                     ttype = ttype.parent
  348.                     cclass = getcls(ttype)
  349.                 if not cclass or '<span style="%s">' % c2s[cclass][0]:
  350.                     pass
  351.                 cspan = ''
  352.             else:
  353.                 cls = self._get_css_class(ttype)
  354.                 if not cls or '<span class="%s">' % cls:
  355.                     pass
  356.                 cspan = ''
  357.             parts = escape_html(value).split('\n')
  358.             for part in parts[:-1]:
  359.                 if line:
  360.                     if lspan != cspan:
  361.                         if lspan:
  362.                             pass
  363.                         if cspan:
  364.                             pass
  365.                         line += '</span>' + cspan + part + '</span>' + lsep
  366.                     elif lspan:
  367.                         pass
  368.                     line += part + '</span>' + lsep
  369.                     yield (1, line)
  370.                     line = ''
  371.                     continue
  372.                 if part:
  373.                     if cspan:
  374.                         pass
  375.                     yield (1, cspan + part + '</span>' + lsep)
  376.                     continue
  377.                 yield (1, lsep)
  378.             
  379.             if line and parts[-1]:
  380.                 if lspan != cspan:
  381.                     if lspan:
  382.                         pass
  383.                     line += '</span>' + cspan + parts[-1]
  384.                     lspan = cspan
  385.                 else:
  386.                     line += parts[-1]
  387.             lspan != cspan
  388.             if parts[-1]:
  389.                 line = cspan + parts[-1]
  390.                 lspan = cspan
  391.                 continue
  392.         
  393.         if line:
  394.             if lspan:
  395.                 pass
  396.             yield (1, line + '</span>' + lsep)
  397.         
  398.  
  399.     
  400.     def _highlight_lines(self, tokensource):
  401.         hls = self.hl_lines
  402.         for t, value in enumerate(tokensource):
  403.             if i + 1 in hls:
  404.                 if self.noclasses:
  405.                     style = ''
  406.                     if self.style.highlight_color is not None:
  407.                         style = ' style="background-color: %s"' % (self.style.highlight_color,)
  408.                     
  409.                     yield (1, '<span%s>%s</span>' % (style, value))
  410.                 else:
  411.                     yield (1, '<span class="hll">%s</span>' % value)
  412.                     None if t != 1 else None
  413.             self.noclasses
  414.             yield (1, value)
  415.             None if t != 1 else None
  416.         
  417.  
  418.     
  419.     def wrap(self, source, outfile):
  420.         return self._wrap_div(self._wrap_pre(source))
  421.  
  422.     
  423.     def format_unencoded(self, tokensource, outfile):
  424.         source = self._format_lines(tokensource)
  425.         if self.hl_lines:
  426.             source = self._highlight_lines(source)
  427.         
  428.         if not self.nowrap:
  429.             if self.linenos == 2:
  430.                 source = self._wrap_inlinelinenos(source)
  431.             
  432.             if self.lineanchors:
  433.                 source = self._wrap_lineanchors(source)
  434.             
  435.             source = self.wrap(source, outfile)
  436.             if self.linenos == 1:
  437.                 source = self._wrap_tablelinenos(source)
  438.             
  439.             if self.full:
  440.                 source = self._wrap_full(source, outfile)
  441.             
  442.         
  443.         for t, piece in source:
  444.             outfile.write(piece)
  445.         
  446.  
  447.  
  448.