Ejemplo n.º 1
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.token_map = {}
        self.styles = []

        for token, style in self.style:
            #debug("formatter: {} {}".format(token, style))

            try:
                s = {}
                if style['color']:
                    c, b = extract_color(style['color'])
                    #debug("fg color: c='{}' b='{}'".format(c, b))
                    s['fg_color'] = c
                    s['fg_bright'] = b
                if style['bold']:
                    s['bold'] = bool(style['bold'])
                if style['underline']:
                    s['underline'] = bool(style['underline'])
                if style['bgcolor']:
                    c, b = extract_color(style['bgcolor'])
                    debug("bg color: c='{}' b='{}'".format(c, b))
                    s['bg_color'] = c
                    s['bg_bright'] = b

                i = self.add_style(s) if len(s) != 0 else -1
                self.token_map[token] = i

                #debug("token_map: {}".format(self.token_map))

            except Exception as ex:
                ## use default formatting
                debug("error: style formatted wrong for {}: {}. Skipping...".format(token, ex))
                self.token_map[token] = -1
Ejemplo n.º 2
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        #XXX distinct colors must fit, actually
        if curses.can_change_color() and len(self.style) <= curses.COLORS:

            # cache of registered RGB colors
            colors = []
            def init_color(rgb):
                r, g, b = int(rgb[:2], 16), int(rgb[2:4], 16), int(rgb[4:], 16)
                curses.init_color(len(colors) + 1,
                    r * 1000 / 255, g * 1000 / 255, b * 1000 / 255)
                colors.append(rgb)
            pairs = []
            self.pairs = {}
            self.bolds = set()
            for token, style in self.style:
                #XXX bg
                fg = style['color'] or 'ffffff'
                bg = style['bgcolor']
                if fg not in colors:
                    init_color(fg)

                if style['bold']:
                    self.bolds.add(token)

                pair = (fg, bg)
                sys.stderr.write("%r gets %r\n" % (token, pair))
                if pair not in pairs:
                    curses.init_pair(len(pairs) + 1,
                        colors.index(fg)+1, -1)
                    pairs.append(pair)

                self.pairs[token] = pairs.index(pair)
Ejemplo n.º 3
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.lineseparator = options.get("lineseparator", "\n")
     self.tabwidth = get_int_opt(options, "tabwidth", 4)
     self.escapetable = _escape_html_table
     self.escapetable[ord("\t")] = "&nbsp;" * self.tabwidth
     self.noclasses = get_bool_opt(options, "noclasses", False)
     self.classprefix = options.get("classprefix", "")
     self.cssclass = options.get("cssclass", "highlight")
     self.stylebg = get_bool_opt(options, "stylebg", True)
     self.stylebgalternating = get_bool_opt(options, "stylebgalternating", True)
     self.fontfamily = options.get("fontfamily", "Courier")
     self.fontsize = options.get("fontsize", "1.2em")
     self._create_stylesheet()
     self.linecolwidth = options.get("linecolwidth", 3)
     self.tablewidth = options.get("tablewidth", "100%")
     self.showtitles = get_bool_opt(options, "showtitles", False)
     self.titles = []
     self.additionalstyles = options.get(
         "additionalstyles",
         (
             AspectStyle(name=CSSCLASS_LINENO, styles=dict(bgcolor="eeeeee", borderright="eeaaaa")),
             AspectStyle(name="bgcoloreven", styles=dict(bgcolor="fafafa")),
             AspectStyle(name="bgcoloreven2", styles=dict(bgcolor="fdfdfd")),
             AspectStyle(name="bgcolorodd", styles=dict(bgcolor="f5f5f5")),
             AspectStyle(name="bgcolorodd2", styles=dict(bgcolor="f8f8f8")),
             AspectStyle(name=CSSCLASS_TD_TITLE, styles=dict(bgcolor="eeaaaa", paddingleft="15px")),
         ),
     )
     self._create_additional_styles()
Ejemplo n.º 4
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)

        # create a dict of (start, end) tuples that wrap the
        # value of a token so that we can use it in the format
        # method later
        self.styles = {}

        # we iterate over the `_styles` attribute of a style item
        # that contains the parsed style values.
        for token, style in self.style:
            start = end = ''
            # a style item is a tuple in the following form:
            # colors are readily specified in hex: 'RRGGBB'
            if style['color']:
                start += '<font color="#%s">' % style['color']
                end = '</font>' + end
            if style['bold']:
                start += '<b>'
                end = '</b>' + end
            if style['italic']:
                start += '<i>'
                end = '</i>' + end
            if style['underline']:
                start += '<u>'
                end = '</u>' + end
            self.styles[token] = (start, end)
    def __init__(self, **options):
        Formatter.__init__(self, **options)

        # create a dict of (start, end) tuples that wrap the
        # value of a token so that we can use it in the format
        # method later
        self.styles = {}

        # we iterate over the `_styles` attribute of a style item
        # that contains the parsed style values.
        for token, style in self.style:
            start = end = ''
            if style['color']:
                sty = str(style['color'])
                if sty == "000000": start, end = '<cstyle:py_decodes>','<cstyle:>'
                if sty == "000001": start, end = '<cstyle:py_comment>','<cstyle:>'
                elif sty == "000002": start, end = '<cstyle:py_keyword>','<cstyle:>'
                elif sty == "000003": start, end = '<cstyle:py_name>','<cstyle:>'
                elif sty == "000004": start, end = '<cstyle:py_name_func>','<cstyle:>'
                elif sty == "000005": start, end = '<cstyle:py_name_class>','<cstyle:>'
                
                elif sty == "100001": start, end = '<cstyle:py_number>','<cstyle:>'   
                elif sty == "100002": start, end = '<cstyle:py_builtin>','<cstyle:>'   
                elif sty == "100003": start, end = '<cstyle:py_builtin>','<cstyle:>'  
                elif sty == "100004": start, end = '<cstyle:py_operator>','<cstyle:>'  
                
                elif sty == "999999": start, end = '<cstyle:py_string>','<cstyle:>'
                #else : start, end = '<cstyle:py_default>','<cstyle:>'
                
            self.styles[token] = (start, end)
Ejemplo n.º 6
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.nowrap = get_bool_opt(options, 'nowrap', False)
        self.noclasses = get_bool_opt(options, 'noclasses', False)
        self.classprefix = options.get('classprefix', '')
        self.cssclass = options.get('cssclass', 'highlight')
        self.cssstyles = options.get('cssstyles', '')
        self.prestyles = options.get('prestyles', '')
        self.cssfile = options.get('cssfile', '')
        linenos = options.get('linenos', False)
        if linenos == 'inline':
            self.linenos = 2
        elif linenos:
            # compatibility with <= 0.7
            self.linenos = 1
        else:
            self.linenos = 0
        self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
        self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
        self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))
        self.nobackground = get_bool_opt(options, 'nobackground', False)
        self.lineseparator = options.get('lineseparator', '\n')
        self.lineanchors = options.get('lineanchors', '')
        self.hl_lines = set()
        for lineno in get_list_opt(options, 'hl_lines', []):
            try:
                self.hl_lines.add(int(lineno))
            except ValueError:
                pass

        self._class_cache = {}
        self._create_stylesheet()
Ejemplo n.º 7
0
Archivo: bbcode.py Proyecto: 10sr/hue
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self._code = get_bool_opt(options, 'codetag', False)
        self._mono = get_bool_opt(options, 'monofont', False)

        self.styles = {}
        self._make_styles()
Ejemplo n.º 8
0
  def __init__(self, **options):
        Formatter.__init__(self, **options)
        
        if "fonts" in options:
          self.fonts = ",".join(options["fonts"])
        else:
		  self.fonts = ",".join(['consolas', 'lucida console', 'courier', 'monospace'])

        # create a dict of (start, end) tuples that wrap the
        # value of a token so that we can use it in the format
        # method later
        self.styles = {}

        # we iterate over the `_styles` attribute of a style item
        # that contains the parsed style values.
        for token, style in self.style:
            start = end = ''
            # a style item is a tuple in the following form:
            # colors are readily specified in hex: 'RRGGBB'
            if style['color']:
                start += '<span style="color:#%s">' % style['color']
                end = '</span>' + end
            if style['bold']:
                start += '<b>'
                end = '</b>' + end
            if style['italic']:
                start += '<i>'
                end = '</i>' + end
            if style['underline']:
                start += '<u>'
                end = '</u>' + end
            self.styles[token] = (start, end)
Ejemplo n.º 9
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.styles = {}
     for token, style in self.style:
         self.styles[token] = {}
         if style["color"]:
             self.styles[token]["color"] = Colors.rgb(*hex2rgb(style["color"]))
Ejemplo n.º 10
0
  def __init__(self, **options):
    Formatter.__init__(self, **options)

    self.styles = {}

    for token, style in self.style:
      start_tag = close_tag = ''

      if style['color']:
        start_tag += '<span fgcolor="#%s">' % style['color']
        close_tag = '</span>' + close_tag

      if style['bold']:
        start_tag += '<b>'
        close_tag = '</b>' + close_tag

      if style['italic']:
        start_tag += '<i>'
        close_tag = '</i>' + close_tag

      if style['underline']:
        start_tag += '<u>'
        close_tag = '</u>' + close_tag

      self.styles[token] = (start_tag, close_tag)
Ejemplo n.º 11
0
 def __init__(self, **options):
     """Initialize the style types."""
     Formatter.__init__(self, **options)
     self.styles = {}
     for token, style in self.style:
         start = ''
         end = ''
         newline_end = '\n'
         newline_start = ''
         if style['color']:
             start += newline_start + '<STATviewcolor=#%s>' % style['color'] + '\n'
             newline_start = ''
         if style['bold']:
             start += newline_start + '<STATviewb>\n'
             newline_start = ''
         if style['italic']:
             start += newline_start + '<STATviewi>\n'
             newline_start = ''
         if style['underline']:
             start += newline_start + '<STATviewu>\n'
             newline_start = ''
         if style['underline']:
             end = newline_end + end + '</STATviewu>\n'
             newline_end = ''
         if style['italic']:
             end = newline_end + end + '</STATviewi>\n'
             newline_end = ''
         if style['bold']:
             end = newline_end + end + '</STATviewb>\n'
             newline_end = ''
         if style['color']:
             end = newline_end + end + '</STATviewcolor>\n'
             newline_end = ''
         self.styles[token] = (start, end)
Ejemplo n.º 12
0
 def __init__(self, **options):
     """Extra arguments:
     
     usebold: if false, bold will be ignored and always off
             default: True
     usebg: if false, background color will always be 'default'
             default: True
     defaultfg: the default color to use for the foreground, used
         if the style does not specify.
         This is in curses format, e.g. curses.COLOR_BLACK.
         Use -1 for the terminal default, -2 for the pygments style default.
         default: -1 (terminal default)
     defaultbg: the default color to use for the background, used in blank
         space, and behind normal text when usebg = False or when
         the style does not specify a foreground color.
         This is in curses format, e.g. curses.COLOR_BLACK.
         Use -1 for the terminal default, -2 for the pygments style default.
         default: -1 (terminal default)
     colors: number of colors to use (-1 for auto, 16, 88, or 256)
             default: -1 (automatic)"""
     Formatter.__init__(self, **options)
     self.usebold = options.get('usebold',True)
     self.usebg = options.get('usebg', True)
     self.defaultbg = options.get('defaultbg', -1)
     self.defaultfg = options.get('defaultfg', -1)
     self.colors = options.get('colors', -1)
     self.style_attrs = {}
     self._tokentocolorpair = {}
     self._setup = False
Ejemplo n.º 13
0
 def __init__(self, flowdocument=True, store_code_blocks=False, **options):
     Formatter.__init__(self, **options)
     self.flowdocument = flowdocument
     self.store_code_blocks = store_code_blocks
     
     self.linenos = 0
     if flowdocument:
         self.lineseparator = '\n'
     else:
         self.lineseparator = '<LineBreak />'
     self.styles = {}
     
     for token, style in self.style:
         format_string = ''
         # a style item is a tuple in the following form:
         # colors are readily specified in hex: 'RRGGBB'
         if style['color']:
             format_string = ' Foreground="#%s"' % style['color']
         if style['bold']:
             format_string += ' FontWeight="Bold"'
         if style['italic']:
             format_string += ' FontStyle="Italic"'
         if style['underline']:
             # not used ?
             pass
         self.styles[token] = format_string
Ejemplo n.º 14
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.darkbg = get_choice_opt(options, 'bg',
                                  ['light', 'dark'], 'light') == 'dark'
     self.colorscheme = options.get('colorscheme', None) or COMMAND_COLORS
     self.linenos = options.get('linenos', False)
     self._lineno = 0
Ejemplo n.º 15
0
    def __init__(self):
        Formatter.__init__(self)
        self.data = []

        # Create a dictionary of text styles, indexed
        # by pygments token names, containing QTextCharFormat
        # instances according to pygments' description
        # of each style

        self.styles = {}
        for token, style in self.style:
            qtf = QtGui.QTextCharFormat()

            if style['color']:
                qtf.setForeground(hex2QColor(style['color']))
            if style['bgcolor']:
                qtf.setBackground(hex2QColor(style['bgcolor']))
            if style['bold']:
                qtf.setFontWeight(QtGui.QFont.Bold)
            if style['italic']:
                qtf.setFontItalic(True)
            if style['underline']:
                qtf.setFontUnderline(True)
            self.styles[str(token)] = qtf
        # missing token
        self.styles['Token.Literal.String.Name'] = self.styles['Token.Literal.String']
Ejemplo n.º 16
0
 def __init__(self, color_scheme, **options):
     self.f_strings = {}
     for k, v in theme_map.iteritems():
         self.f_strings[k] = '\x01%s' % (color_scheme[v],)
         if k is Parenthesis:
             # FIXME: Find a way to make this the inverse of the current
             # background colour
             self.f_strings[k] += 'I'
     Formatter.__init__(self, **options)
Ejemplo n.º 17
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.tagsfile = self._decodeifneeded(options.get('tagsfile', ''))
        self.tagurlformat = self._decodeifneeded(options.get('tagurlformat', ''))

        if self.tagsfile:
            if not ctags:
                raise RuntimeError('The "ctags" package must to be installed '
                                   'to be able to use the "tagsfile" feature.')
            self._ctags = ctags.CTags(self.tagsfile)
Ejemplo n.º 18
0
 def __init__(self, **options):
     """
     See the class docstring for explanation of options.
     """
     if not pil_available:
         raise PilNotAvailable(
             'Python Imaging Library is required for this formatter')
     Formatter.__init__(self, **options)
     self.encoding = 'latin1'  # let pygments.format() do the right thing
     # Read the style
     self.styles = dict(self.style)
     if self.style.background_color is None:
         self.background_color = '#fff'
     else:
         self.background_color = self.style.background_color
     # Image options
     self.image_format = get_choice_opt(
         options, 'image_format', ['png', 'jpeg', 'gif', 'bmp'],
         self.default_image_format, normcase=True)
     self.image_pad = get_int_opt(options, 'image_pad', 10)
     self.line_pad = get_int_opt(options, 'line_pad', 2)
     # The fonts
     fontsize = get_int_opt(options, 'font_size', 14)
     self.fonts = FontManager(options.get('font_name', ''), fontsize)
     self.fontw, self.fonth = self.fonts.get_char_size()
     # Line number options
     self.line_number_fg = options.get('line_number_fg', '#886')
     self.line_number_bg = options.get('line_number_bg', '#eed')
     self.line_number_chars = get_int_opt(options,
                                          'line_number_chars', 2)
     self.line_number_bold = get_bool_opt(options,
                                          'line_number_bold', False)
     self.line_number_italic = get_bool_opt(options,
                                            'line_number_italic', False)
     self.line_number_pad = get_int_opt(options, 'line_number_pad', 6)
     self.line_numbers = get_bool_opt(options, 'line_numbers', True)
     self.line_number_separator = get_bool_opt(options,
                                               'line_number_separator', True)
     self.line_number_step = get_int_opt(options, 'line_number_step', 1)
     self.line_number_start = get_int_opt(options, 'line_number_start', 1)
     if self.line_numbers:
         self.line_number_width = (self.fontw * self.line_number_chars +
                                   self.line_number_pad * 2)
     else:
         self.line_number_width = 0
     self.hl_lines = []
     hl_lines_str = get_list_opt(options, 'hl_lines', [])
     for line in hl_lines_str:
         try:
             self.hl_lines.append(int(line))
         except ValueError:
             pass
     self.hl_color = options.get('hl_color',
                                 self.style.highlight_color) or '#f90'
     self.drawables = []
    def __init__(self, **options):
        Formatter.__init__(self, **options)

        self.codename = options.get('codename', 'code')
        self.escapeopen = options.get('escapeopen', '/BTEX')
        self.escapeclose = options.get('escapeclose', '/ETEX')
        self.commandprefix = options.get('commandprefix', 'PYG')

        self.p = re.compile(r'(\s)')

        self._create_stylesheet()
Ejemplo n.º 20
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)

        # buffer regex for tab/space splitting for block code
        self.whitespace_re = re.compile(u'( {2,}|\t)', re.UNICODE)

        # create a dict of (start, end) tuples that wrap the
        # value of a token so that we can use it in the format
        # method later
        self.styles = {}

        # we iterate over the `_styles` attribute of a style item
        # that contains the parsed style values.
        for token, style in self.style:
            root_elem = None
            curr_elem = None
            # a style item is a tuple in the following form:
            # colors are readily specified in hex: 'RRGGBB'
            if style['color']:
                root_elem = curr_elem = odf_create_element('text:span')
                # pylint: disable=maybe-no-member
                curr_elem.set_style('md2odp-TColor%s' % style['color'])

            if style['bold']:
                span = odf_create_element('text:span')
                # pylint: disable=maybe-no-member
                span.set_style('md2odp-TBold')
                if root_elem is None:
                    root_elem = curr_elem = span
                else:
                    curr_elem.append(span)
                    curr_elem = span

            if style['italic']:
                span = odf_create_element('text:span')
                # pylint: disable=maybe-no-member
                span.set_style('md2odp-TItalic')
                if root_elem is None:
                    root_elem = curr_elem = span
                else:
                    curr_elem.append(span)
                    curr_elem = span

            if style['underline']:
                span = odf_create_element('text:span')
                # pylint: disable=maybe-no-member
                span.set_style('md2odp-TUnderline')
                if root_elem is None:
                    root_elem = curr_elem = span
                else:
                    curr_elem.append(span)
                    curr_elem = span

            self.styles[token] = (root_elem, curr_elem)
Ejemplo n.º 21
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.darkbg = get_choice_opt(options, 'bg',
                                  ['light', 'dark'], 'light') == 'dark'
     self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS
     self.width = options.get('width', 80)
     self.verbatim = False
     self.in_list  = False
     self.column   = 1
     self.last_was_nl = False
     return
Ejemplo n.º 22
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.docclass = options.get("docclass", "article")
        self.preamble = options.get("preamble", "")
        self.linenos = get_bool_opt(options, "linenos", False)
        self.linenostart = abs(get_int_opt(options, "linenostart", 1))
        self.linenostep = abs(get_int_opt(options, "linenostep", 1))
        self.verboptions = options.get("verboptions", "")
        self.nobackground = get_bool_opt(options, "nobackground", False)
        self.commandprefix = options.get("commandprefix", "PY")

        self._create_stylecmds()
Ejemplo n.º 23
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.docclass = options.get('docclass', 'article')
        self.preamble = options.get('preamble', '')
        self.linenos = get_bool_opt(options, 'linenos', False)
        self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
        self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
        self.verboptions = options.get('verboptions', '')
        self.nobackground = get_bool_opt(options, 'nobackground', False)
        self.commandprefix = options.get('commandprefix', 'PY')

        self._create_stylecmds()
Ejemplo n.º 24
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)

        self.xterm_colors = []
        self.best_match = {}
        self.style_string = {}

        self.usebold = 'nobold' not in options
        self.useunderline = 'nounderline' not in options

        self._build_color_table() # build an RGB-to-256 color conversion table
        self._setup_styles() # convert selected style's colors to term. colors
Ejemplo n.º 25
0
    def __init__(self, styles):
        Formatter.__init__(self)

        def style_name(item):
            name, style = item
            if name == 'Paragraph':
                style = 'SFWPParagraphStyle-%s' % str(style)
            else:
                style = 'SFWPCharacterStyle-%s' % str(style)
            return (name, style)

        self.styles = dict(map(style_name, styles.items()))
Ejemplo n.º 26
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.__tstyle = dict(options["style"])
     try:
         self.__bgcolor = options["style"].background_color
     except AttributeError:
         self.__bgcolor = None
     # end try
     self.__emit_line_numbers = options["emit_line_numbers"]
     self.__line_no = options["startline"]
     self.__line_step = options["line_step"]
     self.__output_format = options["output_format"]
     self.__new_line = True
Ejemplo n.º 27
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.compress = get_choice_opt(options, 'compress',
                                    ['', 'none', 'gz', 'bz2'], '')
     self.error_color = options.get('error_color', None)
     if self.error_color is True:
         self.error_color = 'red'
     if self.error_color is not None:
         try:
             colorize(self.error_color, '')
         except KeyError:
             raise ValueError("Invalid color %r specified" %
                              self.error_color)
Ejemplo n.º 28
0
        def __init__(self, draw, covdata, origin, **kw):
            Formatter.__init__(self, **kw)
            self.draw = draw
            self.covdata = covdata
            self.origin = origin

            #: maps Token -> r,g,b triple
            self.token_color = {}

            for (token, style) in self.style:
                if 'color' in style and style['color']:
                    c = parse_color(style['color'])
                    self.token_color[token] = c
Ejemplo n.º 29
0
    def __init__(self, **options):
        """
        Additional options accepted:

        ``fontface``
            Name of the font used. Could for example be ``'Courier New'``
            to further specify the default which is ``'\fmodern'``. The RTF
            specification claims that ``\fmodern`` are "Fixed-pitch serif
            and sans serif fonts". Hope every RTF implementation thinks
            the same about modern...
        """
        Formatter.__init__(self, **options)
        self.fontface = options.get('fontface') or ''
Ejemplo n.º 30
0
 def __init__(self, **options):
     """Extra arguments:
     
     usebold: if false, bold will be ignored and always off
             default: True
     usebg: if false, background color will always be 'default'
             default: True
     colors: number of colors to use (16, 88, or 256)
             default: 256"""
     self.usebold = options.get('usebold',True)
     self.usebg = options.get('usebg', True)
     colors = options.get('colors', 256)
     self.style_attrs = {}
     Formatter.__init__(self, **options)
Ejemplo n.º 31
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.styles = {}
     manager = TextPropertiesManager.getGlobalPtr()
     n = 1 / 255
     for token, style in self.style:
         start = end = ''
         if style['color']:
             # hex color (#FF0000) to RGB 255 (255,0,0)
             color = tuple(
                 int(style['color'][i:i + 2], 16) for i in (0, 2, 4))
             # RGB 255 to vec4 (1,0,0,1), obsolete step?
             color = (n * color[0], n * color[1], n * color[2], 1)
             tp = TextProperties()
             tp.setTextColor(color)
             manager.setProperties(str(color), tp)
             # \1tag\1 starts a TextProperties
             start += '\1%s\1' % str(color)
             # \2 resets TextProperties
             end = str('\2' + end)
         self.styles[token] = (start, end)
Ejemplo n.º 32
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.docclass = options.get('docclass', 'article')
        self.preamble = options.get('preamble', '')
        self.linenos = get_bool_opt(options, 'linenos', False)
        self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
        self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
        self.verboptions = options.get('verboptions', '')
        self.nobackground = get_bool_opt(options, 'nobackground', False)
        self.commandprefix = options.get('commandprefix', 'PY')
        self.texcomments = get_bool_opt(options, 'texcomments', False)
        self.mathescape = get_bool_opt(options, 'mathescape', False)
        self.escapeinside = options.get('escapeinside', '')
        if len(self.escapeinside) == 2:
            self.left = self.escapeinside[0]
            self.right = self.escapeinside[1]
        else:
            self.escapeinside = ''
        self.envname = options.get('envname', 'Verbatim')

        self._create_stylesheet()
Ejemplo n.º 33
0
def load_style(style):
    styles = {}
    formatter = Formatter(style=style)

    for token, params in formatter.style:
        color = parse_hex_color(params["color"]) if params["color"] else None
        # Italic and underline styles aren't supported, so just use bold for them
        bold = params["bold"] or params["italic"] or params["underline"]

        # Save style
        styles[token] = {"color": color, "bold": bold}

    return styles
Ejemplo n.º 34
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.title = self._decodeifneeded(self.title)

        # Holds fo attributes that correspond to each style type.
        self.styles = {}
        self.background_colour = self.style.background_color or '#ffffff'

        # Iterate over the style and create a list of fo attributes that describe it.
        for token, style in self.style:
            atts = []
            if style['color']:
                atts.append('color="#%s"' % style['color'])
            if style['bold']:
                atts.append('font-weight="bold"')
            if style['italic']:
                atts.append('font-style="italic"')
            if style['underline']:
                atts.append('text-decoration="underline"')

            # Save the attributes for this style
            self.styles[token] = ' '.join(atts)
Ejemplo n.º 35
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.title = self._decodeifneeded(self.title)
        self.nowrap = get_bool_opt(options, 'nowrap', False)
        self.noclasses = get_bool_opt(options, 'noclasses', False)
        self.classprefix = options.get('classprefix', '')
        self.cssclass = self._decodeifneeded(
            options.get('cssclass', 'highlight'))
        self.cssstyles = self._decodeifneeded(options.get('cssstyles', ''))
        self.prestyles = self._decodeifneeded(options.get('prestyles', ''))
        self.cssfile = self._decodeifneeded(options.get('cssfile', ''))
        self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile',
                                              False)

        linenos = options.get('linenos', False)
        if linenos == 'inline':
            self.linenos = 2
        elif linenos:
            # compatibility with <= 0.7
            self.linenos = 1
        else:
            self.linenos = 0
        self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
        self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
        self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))
        self.nobackground = get_bool_opt(options, 'nobackground', False)
        self.lineseparator = options.get('lineseparator', '\n')
        self.lineanchors = options.get('lineanchors', '')
        self.anchorlinenos = options.get('anchorlinenos', False)
        self.hl_lines = set()
        for lineno in get_list_opt(options, 'hl_lines', []):
            try:
                self.hl_lines.add(int(lineno))
            except ValueError:
                pass

        self._class_cache = {}
        self._create_stylesheet()
Ejemplo n.º 36
0
 def format(self, tokensource, outfile):
     # hack: if the output is a terminal and has an encoding set,
     # use that to avoid unicode encode problems
     if (
         not self.encoding
         and hasattr(outfile, "encoding")
         and hasattr(outfile, "isatty")
         and outfile.isatty()
         and sys.version_info < (3,)
     ):
         self.encoding = outfile.encoding
         pass
     self.outfile = outfile
     return Formatter.format(self, tokensource, outfile)
Ejemplo n.º 37
0
    def __init__(self):
        Formatter.__init__(self)
        self.data = []

        # Create a dictionary of text styles, indexed
        # by pygments token names, containing QTextCharFormat
        # instances according to pygments' description
        # of each style

        self.styles = {}
        for token, style in self.style:
            qtf = QtGui.QTextCharFormat()

            if style['color']:
                qtf.setForeground(hex2QColor(style['color']))
            if style['bgcolor']:
                qtf.setBackground(hex2QColor(style['bgcolor']))
            if style['bold']:
                qtf.setFontWeight(QtGui.QFont.Bold)
            if style['italic']:
                qtf.setFontItalic(True)
            if style['underline']:
                qtf.setFontUnderline(True)
            self.styles[str(token)] = qtf
Ejemplo n.º 38
0
 def __init__(self, style='default'):
     Formatter.__init__(self, style=style)
     self.styles = {}
     for token, style in self.style:
         start = []
         end = []
         # a style item is a tuple in the following form:
         # colors are readily specified in hex: 'RRGGBB'
         if style['color']:
             start.append('38' + color_as_sgr(parse_sharp(style['color'])))
             end.append('39')
         if style['bold']:
             start.append('1')
             end.append('22')
         if style['italic']:
             start.append('3')
             end.append('23')
         if style['underline']:
             start.append('4')
             end.append('24')
         if start:
             start = '\033[{}m'.format(';'.join(start))
             end = '\033[{}m'.format(';'.join(end))
         self.styles[token] = start or '', end or ''
Ejemplo n.º 39
0
    def __init__(self, parent):
        QSyntaxHighlighter.__init__(self, parent)

        self.formatter = Formatter()
        self.lexer = PythonLexer()
        self.style = {}
        for token, style in self.formatter.style:
            char_format = QTextCharFormat()
            if style['color']:
                char_format.setForeground(QColor("#" + style['color']))
            if style['bgcolor']:
                char_format.setBackground(QColor("#" + style['bgcolor']))
            if style['bold']:
                char_format.setFontWeight(QFont.Bold)
            if style['italic']:
                char_format.setFontItalic(True)
            if style['underline']:
                char_format.setFontUnderline(True)

            char_format.setFontStyleHint(QFont.Monospace)
            self.style[token] = char_format
Ejemplo n.º 40
0
 def __init__(self, presentation, **options):
     Formatter.__init__(self, **options)
     self.presentation = presentation
Ejemplo n.º 41
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.darkbg = get_choice_opt(options, 'bg', ['light', 'dark'],
                                  'light') == 'dark'
     self.colorscheme = options.get('colorscheme', None) or TERMINAL_COLORS
Ejemplo n.º 42
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     if self.encoding is not None and self.encoding != 'utf-8':
         raise ValueError("Only None and utf-8 are allowed encodings.")
Ejemplo n.º 43
0
 def __init__(self, listener, **options):
     Formatter.__init__(self, **options)
     self.listener = listener
     self.styles = dict(self.style)
Ejemplo n.º 44
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.colorscheme = (options.get("colorscheme", None)
                         or ASCIIMATIC_COLORS)
     self.linenos = options.get("linenos", False)
Ejemplo n.º 45
0
 def __init__(self, style):
     Formatter.__init__(self)
     self.style = style
Ejemplo n.º 46
0
 def __init__(subself, **options):  # noqa: N805, E501 # pylint: disable=no-self-argument
     Formatter.__init__(subself, **options)
     subself.current_line = ""
     subself.current_attr = []
     subself.lineno = 1
Ejemplo n.º 47
0
 def format(self, tokensource, outfile):
     self.encoding = outfile.encoding
     return Formatter.format(self, tokensource, outfile)
Ejemplo n.º 48
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.colorscheme = get_colorscheme()
Ejemplo n.º 49
0
 def __init__(self):
     Formatter.__init__(self)
     self._annotation_list = []
Ejemplo n.º 50
0
 def __init__(subself, **options):  # noqa: N805
     Formatter.__init__(subself, **options)
     subself.current_line = ""
     subself.current_attr = []
     subself.lineno = 1
Ejemplo n.º 51
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     #if self.encoding != 'utf-8':
     #    print >>sys.stderr, "NOTICE: Forcing encoding to utf-8, as all Pygments source is"
     if self.encoding is not None and self.encoding != 'utf-8':
         raise ValueError("Only None and utf-u are allowed encodings.")
Ejemplo n.º 52
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)
        self.title = self._decodeifneeded(self.title)
        # 语言
        self.language = self._decodeifneeded(options.get('language', ''))
        self.nowrap = get_bool_opt(options, 'nowrap', False)
        self.noclasses = get_bool_opt(options, 'noclasses', False)
        self.classprefix = options.get('classprefix', '')
        self.cssclass = self._decodeifneeded(
            options.get('cssclass', 'highlight'))
        self.cssstyles = self._decodeifneeded(options.get('cssstyles', ''))
        self.prestyles = self._decodeifneeded(options.get('prestyles', ''))
        self.cssfile = self._decodeifneeded(options.get('cssfile', ''))
        self.noclobber_cssfile = get_bool_opt(options, 'noclobber_cssfile',
                                              False)
        self.tagsfile = self._decodeifneeded(options.get('tagsfile', ''))
        self.tagurlformat = self._decodeifneeded(
            options.get('tagurlformat', ''))
        self.filename = self._decodeifneeded(options.get('filename', ''))

        # 关于ul和li添加的属性
        # 一开始就显示行号
        self.shownum = get_bool_opt(options, 'shownum', True)
        # 代码是否折行,默认为True
        self.linefeed = get_bool_opt(options, 'linefeed', True)
        # ul自定义的class,默认为ul-wrap
        self.ulclass = self._decodeifneeded(
            options.get('ulclass', 'highlight-ul'))
        # ul自定义的style
        self.ulstyles = self._decodeifneeded(options.get('ulstyles', ''))
        # 需要行号的ul的class,默认为numbered
        self.ulnumclass = self._decodeifneeded(
            options.get('ulnumclass', 'numbered'))

        # li自定义的class,默认为li-wrap
        self.liclass = self._decodeifneeded(options.get('liclass', 'li-wrap'))
        # li自定义的style
        self.listyles = self._decodeifneeded(options.get('listyles', ''))
        # 需要行号的li的class,默认为numbered,该选项用在并不是所有行都需要行号的情况下
        self.linumclass = self._decodeifneeded(
            options.get('linumclass', 'numbered'))

        # 检查ctags相关,这里的ctags是import的
        if self.tagsfile:
            if not ctags:
                raise RuntimeError('The "ctags" package must to be installed '
                                   'to be able to use the "tagsfile" feature.')
            # 生成ctags
            self._ctags = ctags.CTags(self.tagsfile)

        # 行号模式
        linenos = 'ul'  # options.get('linenos', 'ul')
        if linenos == 'inline':
            self.linenos = 2  # inline为2
        elif linenos == 'ul':
            self.linenos = 3  # ul为3
        elif linenos == 'table':
            # compatibility with <= 0.7
            self.linenos = 1
        else:
            self.linenos = 0  # 如果没有指定默认为0

        # 获取各种选项
        self.linenostart = abs(get_int_opt(options, 'linenostart', 1))
        self.linenostep = abs(get_int_opt(options, 'linenostep', 1))
        self.linenospecial = abs(get_int_opt(options, 'linenospecial', 0))
        self.nobackground = get_bool_opt(options, 'nobackground', False)
        self.lineseparator = options.get('lineseparator', '\n')
        self.lineanchors = options.get('lineanchors', '')
        self.linespans = options.get('linespans', '')
        self.anchorlinenos = options.get('anchorlinenos', False)
        self.hl_lines = set()

        # 高亮行号存起来
        hl_lines = self._decodeifneeded(options.get('hl_lines', '{}'))
        self.hl_line_nums = []
        try:
            self.hl_lines = json.loads(hl_lines)
            for index, color in self.hl_lines.items():
                try:
                    self.hl_line_nums.append(int(index))
                except ValueError:
                    pass
        except Exception:
            if isinstance(hl_lines, (str, )):
                self.hl_lines = hl_lines.split()
            elif isinstance(hl_lines, (list, tuple)):
                self.hl_lines = list(hl_lines)
            else:
                raise ValueError(
                    'Invalid type `hl_lines`; you must give a list or json serialize value'
                )
            self.hl_line_nums = [int(x) for x in self.hl_lines]

        # 生成style样式
        self._create_stylesheet()
Ejemplo n.º 53
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.show_line_numbers = get_bool_opt(options, 'show_line_numbers',
                                           True)
     self.first_line_number = abs(
         get_int_opt(options, 'first_line_number', 1))
Ejemplo n.º 54
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.compress = get_choice_opt(options, 'compress',
                                    ['', 'none', 'gz', 'bz2'], '')
Ejemplo n.º 55
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
Ejemplo n.º 56
0
 def __init__(self, color_scheme, **options):
     self.f_strings = {}
     for k, v in color_scheme.iteritems():
         self.f_strings[k] = '\x01%s' % (v, )
     Formatter.__init__(self, **options)
Ejemplo n.º 57
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.styles = {}
     for token, style in self.style:
         self.styles[token] = style
     self.output = []
Ejemplo n.º 58
0
 def format(self, tokensource, outfile):
     return Formatter.format(self, tokensource, outfile)