Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes
MoinMoin.support.pygments.formatters.html.HtmlFormatter Class Reference
Inheritance diagram for MoinMoin.support.pygments.formatters.html.HtmlFormatter:
Inheritance graph
[legend]
Collaboration diagram for MoinMoin.support.pygments.formatters.html.HtmlFormatter:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def get_style_defs
def wrap
def format_unencoded

Public Attributes

 title
 nowrap
 noclasses
 classprefix
 cssclass
 cssstyles
 prestyles
 cssfile
 noclobber_cssfile
 linenos
 linenostart
 linenostep
 linenospecial
 nobackground
 lineseparator
 lineanchors
 anchorlinenos
 hl_lines
 ttype2class
 class2style

Static Public Attributes

string name = 'HTML'
list aliases = ['html']
list filenames = ['*.html', '*.htm']

Private Member Functions

def _get_css_class
def _create_stylesheet
def _decodeifneeded
def _wrap_full
def _wrap_tablelinenos
def _wrap_inlinelinenos
def _wrap_lineanchors
def _wrap_div
def _wrap_pre
def _format_lines
def _highlight_lines

Private Attributes

 _class_cache

Detailed Description

Definition at line 105 of file html.py.


Constructor & Destructor Documentation

Definition at line 343 of file html.py.

00343 
00344     def __init__(self, **options):
00345         Formatter.__init__(self, **options)
00346         self.title = self._decodeifneeded(self.title)
00347         self.nowrap = get_bool_opt(options, 'nowrap', False)
00348         self.noclasses = get_bool_opt(options, 'noclasses', False)
00349         self.classprefix = options.get('classprefix', '')
00350         self.cssclass = self._decodeifneeded(options.get('cssclass', 'highlight'))
00351         self.cssstyles = self._decodeifneeded(options.get('cssstyles', ''))
00352         self.prestyles = self._decodeifneeded(options.get('prestyles', ''))
00353         self.cssfile = self._decodeifneeded(options.get('cssfile', ''))
00354         self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile', False)
00355 
00356         linenos = options.get('linenos', False)
00357         if linenos == 'inline':
00358             self.linenos = 2
00359         elif linenos:
00360             # compatibility with <= 0.7
00361             self.linenos = 1
00362         else:
00363             self.linenos = 0
00364         self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
00365         self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
00366         self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))
00367         self.nobackground = get_bool_opt(options, 'nobackground', False)
00368         self.lineseparator = options.get('lineseparator', '\n')
00369         self.lineanchors = options.get('lineanchors', '')
00370         self.anchorlinenos = options.get('anchorlinenos', False)
00371         self.hl_lines = set()
00372         for lineno in get_list_opt(options, 'hl_lines', []):
00373             try:
00374                 self.hl_lines.add(int(lineno))
00375             except ValueError:
00376                 pass
00377 
00378         self._class_cache = {}
00379         self._create_stylesheet()


Member Function Documentation

Definition at line 387 of file html.py.

00387 
00388     def _create_stylesheet(self):
00389         t2c = self.ttype2class = {Token: ''}
00390         c2s = self.class2style = {}
00391         cp = self.classprefix
00392         for ttype, ndef in self.style:
00393             name = cp + _get_ttype_class(ttype)
00394             style = ''
00395             if ndef['color']:
00396                 style += 'color: #%s; ' % ndef['color']
00397             if ndef['bold']:
00398                 style += 'font-weight: bold; '
00399             if ndef['italic']:
00400                 style += 'font-style: italic; '
00401             if ndef['underline']:
00402                 style += 'text-decoration: underline; '
00403             if ndef['bgcolor']:
00404                 style += 'background-color: #%s; ' % ndef['bgcolor']
00405             if ndef['border']:
00406                 style += 'border: 1px solid #%s; ' % ndef['border']
00407             if style:
00408                 t2c[ttype] = name
00409                 # save len(ttype) to enable ordering the styles by
00410                 # hierarchy (necessary for CSS cascading rules!)
00411                 c2s[name] = (style[:-2], ttype, len(ttype))

Definition at line 451 of file html.py.

00451 
00452     def _decodeifneeded(self, value):
00453         if isinstance(value, bytes):
00454             if self.encoding:
00455                 return value.decode(self.encoding)
00456             return value.decode()
00457         return value

Here is the call graph for this function:

def MoinMoin.support.pygments.formatters.html.HtmlFormatter._format_lines (   self,
  tokensource 
) [private]
Just format the tokens, without any wrapping tags.
Yield individual lines.

Definition at line 612 of file html.py.

00612 
00613     def _format_lines(self, tokensource):
00614         """
00615         Just format the tokens, without any wrapping tags.
00616         Yield individual lines.
00617         """
00618         nocls = self.noclasses
00619         lsep = self.lineseparator
00620         # for <span style=""> lookup only
00621         getcls = self.ttype2class.get
00622         c2s = self.class2style
00623 
00624         lspan = ''
00625         line = ''
00626         for ttype, value in tokensource:
00627             if nocls:
00628                 cclass = getcls(ttype)
00629                 while cclass is None:
00630                     ttype = ttype.parent
00631                     cclass = getcls(ttype)
00632                 cspan = cclass and '<span style="%s">' % c2s[cclass][0] or ''
00633             else:
00634                 cls = self._get_css_class(ttype)
00635                 cspan = cls and '<span class="%s">' % cls or ''
00636 
00637             parts = escape_html(value).split('\n')
00638 
00639             # for all but the last line
00640             for part in parts[:-1]:
00641                 if line:
00642                     if lspan != cspan:
00643                         line += (lspan and '</span>') + cspan + part + \
00644                                 (cspan and '</span>') + lsep
00645                     else: # both are the same
00646                         line += part + (lspan and '</span>') + lsep
00647                     yield 1, line
00648                     line = ''
00649                 elif part:
00650                     yield 1, cspan + part + (cspan and '</span>') + lsep
00651                 else:
00652                     yield 1, lsep
00653             # for the last line
00654             if line and parts[-1]:
00655                 if lspan != cspan:
00656                     line += (lspan and '</span>') + cspan + parts[-1]
00657                     lspan = cspan
00658                 else:
00659                     line += parts[-1]
00660             elif parts[-1]:
00661                 line = cspan + parts[-1]
00662                 lspan = cspan
00663             # else we neither have to open a new span nor set lspan
00664 
00665         if line:
00666             yield 1, line + (lspan and '</span>') + lsep

Here is the call graph for this function:

Here is the caller graph for this function:

Return the css class of this token type prefixed with
the classprefix option.

Definition at line 380 of file html.py.

00380 
00381     def _get_css_class(self, ttype):
00382         """Return the css class of this token type prefixed with
00383         the classprefix option."""
00384         if ttype in self._class_cache:
00385             return self._class_cache[ttype]
00386         return self.classprefix + _get_ttype_class(ttype)

Here is the call graph for this function:

Here is the caller graph for this function:

Highlighted the lines specified in the `hl_lines` option by
post-processing the token stream coming from `_format_lines`.

Definition at line 667 of file html.py.

00667 
00668     def _highlight_lines(self, tokensource):
00669         """
00670         Highlighted the lines specified in the `hl_lines` option by
00671         post-processing the token stream coming from `_format_lines`.
00672         """
00673         hls = self.hl_lines
00674 
00675         for i, (t, value) in enumerate(tokensource):
00676             if t != 1:
00677                 yield t, value
00678             if i + 1 in hls: # i + 1 because Python indexes start at 0
00679                 if self.noclasses:
00680                     style = ''
00681                     if self.style.highlight_color is not None:
00682                         style = (' style="background-color: %s"' %
00683                                  (self.style.highlight_color,))
00684                     yield 1, '<span%s>%s</span>' % (style, value)
00685                 else:
00686                     yield 1, '<span class="hll">%s</span>' % value
00687             else:
00688                 yield 1, value

Here is the caller graph for this function:

Definition at line 584 of file html.py.

00584 
00585     def _wrap_div(self, inner):
00586         style = []
00587         if (self.noclasses and not self.nobackground and
00588             self.style.background_color is not None):
00589             style.append('background: %s' % (self.style.background_color,))
00590         if self.cssstyles:
00591             style.append(self.cssstyles)
00592         style = '; '.join(style)
00593 
00594         yield 0, ('<div' + (self.cssclass and ' class="%s"' % self.cssclass)
00595                   + (style and (' style="%s"' % style)) + '>')
00596         for tup in inner:
00597             yield tup
00598         yield 0, '</div>\n'

Here is the caller graph for this function:

def MoinMoin.support.pygments.formatters.html.HtmlFormatter._wrap_full (   self,
  inner,
  outfile 
) [private]

Definition at line 458 of file html.py.

00458 
00459     def _wrap_full(self, inner, outfile):
00460         if self.cssfile:
00461             if os.path.isabs(self.cssfile):
00462                 # it's an absolute filename
00463                 cssfilename = self.cssfile
00464             else:
00465                 try:
00466                     filename = outfile.name
00467                     if not filename or filename[0] == '<':
00468                         # pseudo files, e.g. name == '<fdopen>'
00469                         raise AttributeError
00470                     cssfilename = os.path.join(os.path.dirname(filename),
00471                                                self.cssfile)
00472                 except AttributeError:
00473                     print >>sys.stderr, 'Note: Cannot determine output file name, ' \
00474                           'using current directory as base for the CSS file name'
00475                     cssfilename = self.cssfile
00476             # write CSS file only if noclobber_cssfile isn't given as an option.
00477             try:
00478                 if not os.path.exists(cssfilename) or not self.noclobber_cssfile:
00479                     cf = open(cssfilename, "w")
00480                     cf.write(CSSFILE_TEMPLATE %
00481                             {'styledefs': self.get_style_defs('body')})
00482                     cf.close()
00483             except IOError, err:
00484                 err.strerror = 'Error writing CSS file: ' + err.strerror
00485                 raise
00486 
00487             yield 0, (DOC_HEADER_EXTERNALCSS %
00488                       dict(title     = self.title,
00489                            cssfile   = self.cssfile,
00490                            encoding  = self.encoding))
00491         else:
00492             yield 0, (DOC_HEADER %
00493                       dict(title     = self.title,
00494                            styledefs = self.get_style_defs('body'),
00495                            encoding  = self.encoding))
00496 
00497         for t, line in inner:
00498             yield t, line
00499         yield 0, DOC_FOOTER

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 554 of file html.py.

00554 
00555     def _wrap_inlinelinenos(self, inner):
00556         # need a list of lines since we need the width of a single number :(
00557         lines = list(inner)
00558         sp = self.linenospecial
00559         st = self.linenostep
00560         num = self.linenostart
00561         mw = len(str(len(lines) + num - 1))
00562 
00563         if sp:
00564             for t, line in lines:
00565                 yield 1, '<span class="lineno%s">%*s</span> ' % (
00566                     num%sp == 0 and ' special' or '', mw,
00567                     (num%st and ' ' or num)) + line
00568                 num += 1
00569         else:
00570             for t, line in lines:
00571                 yield 1, '<span class="lineno">%*s</span> ' % (
00572                     mw, (num%st and ' ' or num)) + line
00573                 num += 1

Here is the caller graph for this function:

Definition at line 574 of file html.py.

00574 
00575     def _wrap_lineanchors(self, inner):
00576         s = self.lineanchors
00577         i = 0
00578         for t, line in inner:
00579             if t:
00580                 i += 1
00581                 yield 1, '<a name="%s-%d"></a>' % (s, i) + line
00582             else:
00583                 yield 0, line

Here is the caller graph for this function:

Definition at line 599 of file html.py.

00599 
00600     def _wrap_pre(self, inner):
00601         style = []
00602         if self.prestyles:
00603             style.append(self.prestyles)
00604         if self.noclasses:
00605             style.append('line-height: 125%')
00606         style = '; '.join(style)
00607 
00608         yield 0, ('<pre' + (style and ' style="%s"' % style) + '>')
00609         for tup in inner:
00610             yield tup
00611         yield 0, '</pre>'

Here is the caller graph for this function:

Definition at line 500 of file html.py.

00500 
00501     def _wrap_tablelinenos(self, inner):
00502         dummyoutfile = StringIO.StringIO()
00503         lncount = 0
00504         for t, line in inner:
00505             if t:
00506                 lncount += 1
00507             dummyoutfile.write(line)
00508 
00509         fl = self.linenostart
00510         mw = len(str(lncount + fl - 1))
00511         sp = self.linenospecial
00512         st = self.linenostep
00513         la = self.lineanchors
00514         aln = self.anchorlinenos
00515         if sp:
00516             lines = []
00517 
00518             for i in range(fl, fl+lncount):
00519                 if i % st == 0:
00520                     if i % sp == 0:
00521                         if aln:
00522                             lines.append('<a href="#%s-%d" class="special">%*d</a>' %
00523                                          (la, i, mw, i))
00524                         else:
00525                             lines.append('<span class="special">%*d</span>' % (mw, i))
00526                     else:
00527                         if aln:
00528                             lines.append('<a href="#%s-%d">%*d</a>' % (la, i, mw, i))
00529                         else:
00530                             lines.append('%*d' % (mw, i))
00531                 else:
00532                     lines.append('')
00533             ls = '\n'.join(lines)
00534         else:
00535             lines = []
00536             for i in range(fl, fl+lncount):
00537                 if i % st == 0:
00538                     if aln:
00539                         lines.append('<a href="#%s-%d">%*d</a>' % (la, i, mw, i))
00540                     else:
00541                         lines.append('%*d' % (mw, i))
00542                 else:
00543                     lines.append('')
00544             ls = '\n'.join(lines)
00545 
00546         # in case you wonder about the seemingly redundant <div> here: since the
00547         # content in the other cell also is wrapped in a div, some browsers in
00548         # some configurations seem to mess up the formatting...
00549         yield 0, ('<table class="%stable">' % self.cssclass +
00550                   '<tr><td class="linenos"><div class="linenodiv"><pre>' +
00551                   ls + '</pre></div></td><td class="code">')
00552         yield 0, dummyoutfile.getvalue()
00553         yield 0, '</td></tr></table>'

Here is the caller graph for this function:

def MoinMoin.support.pygments.formatters.html.HtmlFormatter.format_unencoded (   self,
  tokensource,
  outfile 
)
The formatting process uses several nested generators; which of
them are used is determined by the user's options.

Each generator should take at least one argument, ``inner``,
and wrap the pieces of text generated by this.

Always yield 2-tuples: (code, text). If "code" is 1, the text
is part of the original tokensource being highlighted, if it's
0, the text is some piece of wrapping. This makes it possible to
use several different wrappers that process the original source
linewise, e.g. line number generators.

Definition at line 697 of file html.py.

00697 
00698     def format_unencoded(self, tokensource, outfile):
00699         """
00700         The formatting process uses several nested generators; which of
00701         them are used is determined by the user's options.
00702 
00703         Each generator should take at least one argument, ``inner``,
00704         and wrap the pieces of text generated by this.
00705 
00706         Always yield 2-tuples: (code, text). If "code" is 1, the text
00707         is part of the original tokensource being highlighted, if it's
00708         0, the text is some piece of wrapping. This makes it possible to
00709         use several different wrappers that process the original source
00710         linewise, e.g. line number generators.
00711         """
00712         source = self._format_lines(tokensource)
00713         if self.hl_lines:
00714             source = self._highlight_lines(source)
00715         if not self.nowrap:
00716             if self.linenos == 2:
00717                 source = self._wrap_inlinelinenos(source)
00718             if self.lineanchors:
00719                 source = self._wrap_lineanchors(source)
00720             source = self.wrap(source, outfile)
00721             if self.linenos == 1:
00722                 source = self._wrap_tablelinenos(source)
00723             if self.full:
00724                 source = self._wrap_full(source, outfile)
00725 
00726         for t, piece in source:
00727             outfile.write(piece)

Here is the call graph for this function:

Here is the caller graph for this function:

Return CSS style definitions for the classes produced by the current
highlighting style. ``arg`` can be a string or list of selectors to
insert before the token type classes.

Definition at line 412 of file html.py.

00412 
00413     def get_style_defs(self, arg=None):
00414         """
00415         Return CSS style definitions for the classes produced by the current
00416         highlighting style. ``arg`` can be a string or list of selectors to
00417         insert before the token type classes.
00418         """
00419         if arg is None:
00420             arg = ('cssclass' in self.options and '.'+self.cssclass or '')
00421         if isinstance(arg, basestring):
00422             args = [arg]
00423         else:
00424             args = list(arg)
00425 
00426         def prefix(cls):
00427             if cls:
00428                 cls = '.' + cls
00429             tmp = []
00430             for arg in args:
00431                 tmp.append((arg and arg + ' ' or '') + cls)
00432             return ', '.join(tmp)
00433 
00434         styles = [(level, ttype, cls, style)
00435                   for cls, (style, ttype, level) in self.class2style.iteritems()
00436                   if cls and style]
00437         styles.sort()
00438         lines = ['%s { %s } /* %s */' % (prefix(cls), style, repr(ttype)[6:])
00439                  for (level, ttype, cls, style) in styles]
00440         if arg and not self.nobackground and \
00441            self.style.background_color is not None:
00442             text_style = ''
00443             if Text in self.ttype2class:
00444                 text_style = ' ' + self.class2style[self.ttype2class[Text]][0]
00445             lines.insert(0, '%s { background: %s;%s }' %
00446                          (prefix(''), self.style.background_color, text_style))
00447         if self.style.highlight_color is not None:
00448             lines.insert(0, '%s.hll { background-color: %s }' %
00449                          (prefix(''), self.style.highlight_color))
00450         return '\n'.join(lines)

Here is the caller graph for this function:

def MoinMoin.support.pygments.formatters.html.HtmlFormatter.wrap (   self,
  source,
  outfile 
)
Wrap the ``source``, which is a generator yielding
individual lines, in custom generators. See docstring
for `format`. Can be overridden.

Definition at line 689 of file html.py.

00689 
00690     def wrap(self, source, outfile):
00691         """
00692         Wrap the ``source``, which is a generator yielding
00693         individual lines, in custom generators. See docstring
00694         for `format`. Can be overridden.
00695         """
00696         return self._wrap_div(self._wrap_pre(source))

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Definition at line 377 of file html.py.

Definition at line 340 of file html.py.

Definition at line 369 of file html.py.

Definition at line 389 of file html.py.

Definition at line 348 of file html.py.

Definition at line 349 of file html.py.

Definition at line 352 of file html.py.

Definition at line 350 of file html.py.

Definition at line 341 of file html.py.

Definition at line 370 of file html.py.

Definition at line 368 of file html.py.

Definition at line 357 of file html.py.

Definition at line 365 of file html.py.

Definition at line 363 of file html.py.

Definition at line 364 of file html.py.

Definition at line 367 of file html.py.

Definition at line 339 of file html.py.

Definition at line 366 of file html.py.

Definition at line 347 of file html.py.

Definition at line 353 of file html.py.

Definition at line 346 of file html.py.

Definition at line 351 of file html.py.

Definition at line 345 of file html.py.

Definition at line 388 of file html.py.


The documentation for this class was generated from the following file: