Example #1
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()
    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()
Example #3
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()
Example #4
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()
Example #5
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)
        self.tagsfile = self._decodeifneeded(options.get('tagsfile', ''))
        self.tagurlformat = self._decodeifneeded(
            options.get('tagurlformat', ''))
        self.filename = self._decodeifneeded(options.get('filename', ''))
        self.wrapcode = get_bool_opt(options, 'wrapcode', False)
        self.span_element_openers = {}
        self.debug_token_types = get_bool_opt(options, 'debug_token_types',
                                              False)

        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)

        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.linespans = options.get('linespans', '')
        self.anchorlinenos = get_bool_opt(options, '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._create_stylesheet()
Example #6
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.highlights = get_list_opt(options, 'highlights', [])
        self._create_stylesheet()
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.nowrap = get_bool_opt(options, 'nowrap', False)
     self.fontfamily = options.get('fontfamily', 'monospace')
     self.fontsize = options.get('fontsize', '14px')
     self.xoffset = get_int_opt(options, 'xoffset', 0)
     fs = self.fontsize.strip()
     if fs.endswith('px'): fs = fs[:-2].strip()
     try:
         int_fs = int(fs)
     except:
         int_fs = 20
     self.yoffset = get_int_opt(options, 'yoffset', int_fs)
     self.ystep = get_int_opt(options, 'ystep', int_fs + 5)
     self.spacehack = get_bool_opt(options, 'spacehack', True)
     self._stylecache = {}
Example #8
0
 def __init__(self, **options):
     super().__init__(**options)
     self.boundary = options.get("Multipart-Boundary")
     self.content_transfer_encoding = options.get(
         "Content_Transfer_Encoding")
     self.content_type = options.get("Content_Type", "text/plain")
     self.max_nested_level = get_int_opt(options, "MIME-max-level", -1)
Example #9
0
 def __init__(self, **options):
     Formatter.__init__(self, **options)
     self.nowrap = get_bool_opt(options, 'nowrap', False)
     self.fontfamily = options.get('fontfamily', 'monospace')
     self.fontsize = options.get('fontsize', '14px')
     self.xoffset = get_int_opt(options, 'xoffset', 0)
     fs = self.fontsize.strip()
     if fs.endswith('px'): fs = fs[:-2].strip()
     try:
         int_fs = int(fs)
     except:
         int_fs = 20
     self.yoffset = get_int_opt(options, 'yoffset', int_fs)
     self.ystep = get_int_opt(options, 'ystep', int_fs + 5)
     self.spacehack = get_bool_opt(options, 'spacehack', True)
     self._stylecache = {}
Example #10
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()
Example #11
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)
        self.tagsfile = self._decodeifneeded(options.get('tagsfile', ''))
        self.tagurlformat = self._decodeifneeded(options.get('tagurlformat', ''))
        self.filename = self._decodeifneeded(options.get('filename', ''))
        self.wrapcode = get_bool_opt(options, 'wrapcode', False)

        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)

        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.linespans = options.get('linespans', '')
        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._create_stylesheet()
Example #12
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)
        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)

        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.linespans = options.get("linespans", "")
        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._create_stylesheet()
Example #13
0
 def __init__(self, **options):
     # XXX outencoding
     Formatter.__init__(self, **options)
     self.nowrap = get_bool_opt(options, "nowrap", False)
     self.fontfamily = options.get("fontfamily", "monospace")
     self.fontsize = options.get("fontsize", "14px")
     self.xoffset = get_int_opt(options, "xoffset", 0)
     fs = self.fontsize.strip()
     if fs.endswith("px"):
         fs = fs[:-2].strip()
     try:
         int_fs = int(fs)
     except:
         int_fs = 20
     self.yoffset = get_int_opt(options, "yoffset", int_fs)
     self.ystep = get_int_opt(options, "ystep", int_fs + 5)
     self.spacehack = get_bool_opt(options, "spacehack", True)
     self._stylecache = {}
Example #14
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)
     # 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'],
                                        'PNG')
     self.image_pad = get_int_opt(options, 'image_pad', 10)
     self.line_pad = get_int_opt(options, 'line_pad', 2)
     # The fonts
     self.fonts = FontManager(options.get('font_name', ''))
     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)
     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.drawables = []
Example #15
0
 def __init__(self, **options):
     self.options = options
     self.stripnl = get_bool_opt(options, 'stripnl', True)
     self.stripall = get_bool_opt(options, 'stripall', False)
     self.tabsize = get_int_opt(options, 'tabsize', 0)
     self.encoding = options.get('encoding', 'latin1')
     # self.encoding = options.get('inencoding', None) or self.encoding
     self.filters = []
     for filter_ in get_list_opt(options, 'filters', ()):
         self.add_filter(filter_)
Example #16
0
 def __init__(self, **options):
     self.options = options
     self.stripnl = get_bool_opt(options, 'stripnl', True)
     self.stripall = get_bool_opt(options, 'stripall', False)
     self.tabsize = get_int_opt(options, 'tabsize', 0)
     self.encoding = options.get('encoding', 'latin1')
     # self.encoding = options.get('inencoding', None) or self.encoding
     self.filters = []
     for filter_ in get_list_opt(options, 'filters', ()):
         self.add_filter(filter_)
Example #17
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)
     # 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'], 'PNG')
     self.image_pad = get_int_opt(options, 'image_pad', 10)
     self.line_pad = get_int_opt(options, 'line_pad', 2)
     # The fonts
     self.fonts = FontManager(options.get('font_name', ''))
     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)
     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.drawables = []
Example #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 = []
Example #19
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.verbenvironment = options.get('verbenvironment', 'Verbatim')
        self.saveverbatimname = options.get('saveverbatimname', '')
        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)
        # New options added with cilkhilite pygments plugin
        self.inline = get_bool_opt(options, 'inline', False)
        self.hidebydefault = get_bool_opt(options, 'hidebydefault', False)
        self.reindent = get_bool_opt(options, 'reindent', False)

        self._create_stylesheet()
Example #20
0
 def __init__(self, **options):
     self.options = options
     self.stripnl = get_bool_opt(options, "stripnl", True)
     self.stripall = get_bool_opt(options, "stripall", False)
     self.ensurenl = get_bool_opt(options, "ensurenl", True)
     self.tabsize = get_int_opt(options, "tabsize", 0)
     self.encoding = options.get("encoding", "utf-8")
     # self.encoding = options.get('inencoding', None) or self.encoding
     self.filters = []
     for filter_ in get_list_opt(options, "filters", ()):
         self.add_filter(filter_)
Example #21
0
    def __init__(self, **options):
        Formatter.__init__(self, **options)

        self.monospaced = get_bool_opt(options, 'monospaced', True)
        self.linenos = get_bool_opt(options, 'linenos', False)
        self._lineno = 0
        self.wrap = get_int_opt(options, 'wrap', 0)
        self._linelen = 0

        self.styles = {}
        self._make_styles()
Example #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.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', u'Verbatim')

        self._create_stylesheet()
Example #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.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', u'Verbatim')

        self._create_stylesheet()
Example #24
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 = []
Example #25
0
 def __init__(self, **options):
     Filter.__init__(self, **options)
     for name, default in [("spaces", u"·"), ("tabs", u"»"), ("newlines", u"¶")]:
         opt = options.get(name, False)
         if isinstance(opt, string_types) and len(opt) == 1:
             setattr(self, name, opt)
         else:
             setattr(self, name, (opt and default or ""))
     tabsize = get_int_opt(options, "tabsize", 8)
     if self.tabs:
         self.tabs += " " * (tabsize - 1)
     if self.newlines:
         self.newlines += "\n"
     self.wstt = get_bool_opt(options, "wstokentype", True)
Example #26
0
 def __init__(self, **options):
     Filter.__init__(self, **options)
     for name, default in list({'spaces': '·', 'tabs': '»', 'newlines': '¶'}.items()):
         opt = options.get(name, False)
         if isinstance(opt, str) and len(opt) == 1:
             setattr(self, name, opt)
         else:
             setattr(self, name, (opt and default or ''))
     tabsize = get_int_opt(options, 'tabsize', 8)
     if self.tabs:
         self.tabs += ' '*(tabsize-1)
     if self.newlines:
         self.newlines += '\n'
     self.wstt = get_bool_opt(options, 'wstokentype', True)
Example #27
0
 def __init__(self, **options):
     Filter.__init__(self, **options)
     for name, default in list({"spaces": "·", "tabs": "»", "newlines": "¶"}.items()):
         opt = options.get(name, False)
         if isinstance(opt, str) and len(opt) == 1:
             setattr(self, name, opt)
         else:
             setattr(self, name, (opt and default or ""))
     tabsize = get_int_opt(options, "tabsize", 8)
     if self.tabs:
         self.tabs += " " * (tabsize - 1)
     if self.newlines:
         self.newlines += "\n"
     self.wstt = get_bool_opt(options, "wstokentype", True)
Example #28
0
 def __init__(self, **options):
     Filter.__init__(self, **options)
     for name, default in {'spaces': u'·', 'tabs': u'»', 'newlines': u'¶'}.items():
         opt = options.get(name, False)
         if isinstance(opt, basestring) and len(opt) == 1:
             setattr(self, name, opt)
         else:
             setattr(self, name, (opt and default or ''))
     tabsize = get_int_opt(options, 'tabsize', 8)
     if self.tabs:
         self.tabs += ' '*(tabsize-1)
     if self.newlines:
         self.newlines += '\n'
     self.wstt = get_bool_opt(options, 'wstokentype', True)
Example #29
0
    def __init__(self, **options):
        r"""
        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 ''
        self.fontsize = get_int_opt(options, 'fontsize', 0)
Example #30
0
 def __init__(self, **options):
     Filter.__init__(self, **options)
     for name, default in [('spaces', '·'), ('tabs', '»'),
                           ('newlines', '¶')]:
         opt = options.get(name, False)
         if isinstance(opt, str) and len(opt) == 1:
             setattr(self, name, opt)
         else:
             setattr(self, name, (opt and default or ''))
     tabsize = get_int_opt(options, 'tabsize', 8)
     if self.tabs:
         self.tabs += ' ' * (tabsize - 1)
     if self.newlines:
         self.newlines += '\n'
     self.wstt = get_bool_opt(options, 'wstokentype', True)
 def __init__(self, **options):
     Filter.__init__(self, **options)
     for name, default in [('spaces',   u'·'),
                           ('tabs',     u'»'),
                           ('newlines', u'¶')]:
         opt = options.get(name, False)
         if isinstance(opt, string_types) and len(opt) == 1:
             setattr(self, name, opt)
         else:
             setattr(self, name, (opt and default or ''))
     tabsize = get_int_opt(options, 'tabsize', 8)
     if self.tabs:
         self.tabs += ' ' * (tabsize - 1)
     if self.newlines:
         self.newlines += '\n'
     self.wstt = get_bool_opt(options, 'wstokentype', True)
Example #32
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)
     # 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 = []
Example #33
0
    def test_getoptions(self):
        raises = self.assertRaises
        equals = self.assertEquals

        equals(util.get_bool_opt({}, 'a', True), True)
        equals(util.get_bool_opt({}, 'a', 1), True)
        equals(util.get_bool_opt({}, 'a', 'true'), True)
        equals(util.get_bool_opt({}, 'a', 'no'), False)
        raises(util.OptionError, util.get_bool_opt, {}, 'a', [])
        raises(util.OptionError, util.get_bool_opt, {}, 'a', 'foo')

        equals(util.get_int_opt({}, 'a', 1), 1)
        raises(util.OptionError, util.get_int_opt, {}, 'a', [])
        raises(util.OptionError, util.get_int_opt, {}, 'a', 'bar')

        equals(util.get_list_opt({}, 'a', [1]), [1])
        equals(util.get_list_opt({}, 'a', '1 2'), ['1', '2'])
        raises(util.OptionError, util.get_list_opt, {}, 'a', 1)
Example #34
0
    def test_getoptions(self):
        raises = self.assertRaises
        equals = self.assertEqual

        equals(util.get_bool_opt({}, "a", True), True)
        equals(util.get_bool_opt({}, "a", 1), True)
        equals(util.get_bool_opt({}, "a", "true"), True)
        equals(util.get_bool_opt({}, "a", "no"), False)
        raises(util.OptionError, util.get_bool_opt, {}, "a", [])
        raises(util.OptionError, util.get_bool_opt, {}, "a", "foo")

        equals(util.get_int_opt({}, "a", 1), 1)
        raises(util.OptionError, util.get_int_opt, {}, "a", [])
        raises(util.OptionError, util.get_int_opt, {}, "a", "bar")

        equals(util.get_list_opt({}, "a", [1]), [1])
        equals(util.get_list_opt({}, "a", "1 2"), ["1", "2"])
        raises(util.OptionError, util.get_list_opt, {}, "a", 1)
Example #35
0
    def test_getoptions(self):
        raises = self.assertRaises
        equals = self.assertEqual

        equals(util.get_bool_opt({}, 'a', True), True)
        equals(util.get_bool_opt({}, 'a', 1), True)
        equals(util.get_bool_opt({}, 'a', 'true'), True)
        equals(util.get_bool_opt({}, 'a', 'no'), False)
        raises(util.OptionError, util.get_bool_opt, {}, 'a', [])
        raises(util.OptionError, util.get_bool_opt, {}, 'a', 'foo')

        equals(util.get_int_opt({}, 'a', 1), 1)
        raises(util.OptionError, util.get_int_opt, {}, 'a', [])
        raises(util.OptionError, util.get_int_opt, {}, 'a', 'bar')

        equals(util.get_list_opt({}, 'a', [1]), [1])
        equals(util.get_list_opt({}, 'a', '1 2'), ['1', '2'])
        raises(util.OptionError, util.get_list_opt, {}, 'a', 1)
def test_getoptions():
    assert util.get_bool_opt({}, 'a', True) is True
    assert util.get_bool_opt({}, 'a', 1) is True
    assert util.get_bool_opt({}, 'a', 'true') is True
    assert util.get_bool_opt({}, 'a', 'no') is False
    assert raises(util.OptionError, util.get_bool_opt, {}, 'a', [])
    assert raises(util.OptionError, util.get_bool_opt, {}, 'a', 'foo')

    assert util.get_int_opt({}, 'a', 1) == 1
    assert raises(util.OptionError, util.get_int_opt, {}, 'a', [])
    assert raises(util.OptionError, util.get_int_opt, {}, 'a', 'bar')

    assert util.get_list_opt({}, 'a', [1]) == [1]
    assert util.get_list_opt({}, 'a', '1 2') == ['1', '2']
    assert raises(util.OptionError, util.get_list_opt, {}, 'a', 1)

    assert util.get_choice_opt({}, 'a', ['foo', 'bar'], 'bar') == 'bar'
    assert util.get_choice_opt({}, 'a', ['foo', 'bar'], 'Bar', True) == 'bar'
    assert raises(util.OptionError, util.get_choice_opt, {}, 'a',
                  ['foo', 'bar'], 'baz')
Example #37
0
def pyg(outfile, outencoding, n, opts, extra_opts, text, usedstyles, inline_delim = ''):
    try:
        lexer = get_lexer_by_name(opts['lang'])
    except ClassNotFound as err:
        sys.stderr.write('Error: ')
        sys.stderr.write(str(err))
        return ""

    # global _fmter
    _fmter = EnhancedLatexFormatter()

    escapeinside = opts.get('escapeinside', '')
    if len(escapeinside) == 2:
        left = escapeinside[0]
        right = escapeinside[1]
        _fmter.escapeinside = escapeinside
        _fmter.left = left
        _fmter.right = right
        lexer = LatexEmbeddedLexer(left, right, lexer)

    gobble = abs(get_int_opt(opts, 'gobble', 0))
    if gobble:
        lexer.add_filter('gobble', n=gobble)

    tabsize = abs(get_int_opt(opts, 'tabsize', 0))
    if tabsize:
        lexer.tabsize = tabsize

    lexer.encoding = ''
    # _fmter.encoding = outencoding

    stylename = opts['sty']

    honorspacewidth = False
    if stylename in ('candombe', 'candombefix', 'candombediagram', 'nostylediagram'):
        _fmter.style = NoStyle if stylename == 'nostylediagram' else CandombeStyle
        honorspacewidth = stylename in ('candombefix', 'candombediagram', 'nostylediagram')
    else:
        _fmter.style = get_style_by_name(stylename)

    _fmter._create_stylesheet()

    _fmter.texcomments = get_bool_opt(opts, 'texcomments', False)
    _fmter.mathescape = get_bool_opt(opts, 'mathescape', False)


    if stylename not in usedstyles:
        styledefs = _fmter.get_style_defs() \
            .replace('#', '##') \
            .replace(r'\##', r'\#') \
            .replace(r'\makeatletter', '') \
            .replace(r'\makeatother', '') \
            .replace('\n', '%\n')
        outfile.write(
            '\\def\\PYstyle{0}{{%\n{1}%\n}}%\n'.format(stylename, styledefs))
        usedstyles.append(stylename)

    x = highlight(text, lexer, _fmter)

    m = re.match(r'\\begin\{Verbatim}(.*)\n([\s\S]*?)\n\\end\{Verbatim}(\s*)\Z',
                 x)
    if m:
        linenos = get_bool_opt(opts, 'linenos', False)
        linenostart = abs(get_int_opt(opts, 'linenostart', 1))
        linenostep = abs(get_int_opt(opts, 'linenostep', 1))
        lines0 = m.group(2).split('\n')
        numbers = []
        lines = []
        counter = linenostart
        for line in lines0:
            line = re.sub(r'^ ', r'\\makebox[0pt]{\\phantom{Xy}} ', line)
            line = re.sub(r' ', '~', line)
            if linenos:
                if (counter - linenostart) % linenostep == 0:
                    line = r'\pygmented@lineno@do{' + str(counter) + '}' + line
                    numbers.append(str(counter))
                counter = counter + 1
            lines.append(line)
        if inline_delim:
            outfile.write(INLINE_SNIPPET_TEMPLATE %
                dict(number    = n,
                     style     = stylename,
                     options   = extra_opts,
                     body      = '\\newline\n'.join(lines)))
        else:
            if linenos:
                template = DISPLAY_LINENOS_SNIPPET_TEMPLATE
            else:
                template = DISPLAY_SNIPPET_TEMPLATE

            # The '~' is a special Latex character that means an
            # unbreakable space and it is used by Pygments to type the
            # spaces.
            # Unfortunately the width of each space character is smaller
            # than the size of the rest of the characters and while it
            # is ok for normal source code, it is not ok when doing an
            # ASCII diagram
            #
            # The fix is to replace all the ~ by a horizontal phantom
            # space which width will be the same of the width of the
            # given character (in this case a 'm').
            #
            # This should be safe even if the source code has a ~
            # because Pygments will replace them with \PYZti{} before
            # so we should be replacing only the ~ that represent
            # spaces.
            #
            # https://github.com/pygments/pygments/blob/master/pygments/formatters/latex.py
            # https://tex.stackexchange.com/questions/74353/what-commands-are-there-for-horizontal-spacing
            if honorspacewidth:
                lines = [l.replace('~',r'\hphantom{m}') for l in lines]

            outfile.write(template %
                dict(number      = n,
                     style       = stylename,
                     options     = extra_opts,
                     linenosep   = opts['linenosep'],
                     linenumbers = ','.join(numbers),
                     body        = '\\newline\n'.join(lines)))
Example #38
0
 def __init__(self, **options):
     Filter.__init__(self, **options)
     self.n = get_int_opt(options, 'n', 0)
Example #39
0
def pyg(outfile, outencoding, n, opts, extra_opts, text, usedstyles, inline_delim = ''):
    try:
        lexer = get_lexer_by_name(opts['lang'])
    except ClassNotFound as err:
        sys.stderr.write('Error: ')
        sys.stderr.write(str(err))
        return ""

    # global _fmter
    _fmter = EnhancedLatexFormatter()

    escapeinside = opts.get('escapeinside', '')
    if len(escapeinside) == 2:
        left = escapeinside[0]
        right = escapeinside[1]
        _fmter.escapeinside = escapeinside
        _fmter.left = left
        _fmter.right = right
        lexer = LatexEmbeddedLexer(left, right, lexer)

    gobble = abs(get_int_opt(opts, 'gobble', 0))
    if gobble:
        lexer.add_filter('gobble', n=gobble)

    tabsize = abs(get_int_opt(opts, 'tabsize', 0))
    if tabsize:
        lexer.tabsize = tabsize

    lexer.encoding = ''
    # _fmter.encoding = outencoding

    stylename = opts['sty']

    _fmter.style = get_style_by_name(stylename)
    _fmter._create_stylesheet()

    _fmter.texcomments = get_bool_opt(opts, 'texcomments', False)
    _fmter.mathescape = get_bool_opt(opts, 'mathescape', False)

    if stylename not in usedstyles:
        styledefs = _fmter.get_style_defs() \
            .replace('#', '##') \
            .replace(r'\##', r'\#') \
            .replace(r'\makeatletter', '') \
            .replace(r'\makeatother', '') \
            .replace('\n', '%\n')
        outfile.write(
            '\\def\\PYstyle{0}{{%\n{1}%\n}}%\n'.format(stylename, styledefs))
        usedstyles.append(stylename)

    x = highlight(text, lexer, _fmter)

    m = re.match(r'\\begin\{Verbatim}(.*)\n([\s\S]*?)\n\\end\{Verbatim}(\s*)\Z',
                 x)
    if m:
        linenos = get_bool_opt(opts, 'linenos', False)
        linenostart = abs(get_int_opt(opts, 'linenostart', 1))
        linenostep = abs(get_int_opt(opts, 'linenostep', 1))
        lines0 = m.group(2).split('\n')
        numbers = []
        lines = []
        counter = linenostart
        for line in lines0:
            line = re.sub(r'^ ', r'\\makebox[0pt]{\\phantom{Xy}} ', line)
            line = re.sub(r' ', '~', line)
            if linenos:
                if (counter - linenostart) % linenostep == 0:
                    line = r'\pygmented@lineno@do{' + str(counter) + '}' + line
                    numbers.append(str(counter))
                counter = counter + 1
            lines.append(line)
        if inline_delim:
            outfile.write(INLINE_SNIPPET_TEMPLATE %
                dict(number    = n,
                     style     = stylename,
                     options   = extra_opts,
                     body      = '\\newline\n'.join(lines)))
        else:
            if linenos:
                template = DISPLAY_LINENOS_SNIPPET_TEMPLATE
            else:
                template = DISPLAY_SNIPPET_TEMPLATE
            outfile.write(template %
                dict(number      = n,
                     style       = stylename,
                     options     = extra_opts,
                     linenosep   = opts['linenosep'],
                     linenumbers = ','.join(numbers),
                     body        = '\\newline\n'.join(lines)))
Example #40
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))
Example #41
0
 def __init__(self, **options):
     Filter.__init__(self, **options)
     self.n = get_int_opt(options, 'n', 0)
Example #42
0
 def __init__(self, **options):
   Filter.__init__(self, **options)
   self.tabsize = get_int_opt(options, 'tabsize', 4)
   self.repl = re.compile(r'^\t+')
Example #43
0
def pyg(outfile, n, opts, extra_opts, text, usedstyles, inline_delim = ''):
    try:
        lexer = get_lexer_by_name(opts['lang'])
    except ClassNotFound as err:
        sys.stderr.write('Error: ')
        sys.stderr.write(str(err))
        return ""

    # global _fmter
    _fmter = EnhancedLatexFormatter()

    escapeinside = opts.get('escapeinside', '')
    if len(escapeinside) == 2:
        left = escapeinside[0]
        right = escapeinside[1]
        _fmter.escapeinside = escapeinside
        _fmter.left = left
        _fmter.right = right
        lexer = LatexEmbeddedLexer(left, right, lexer)

    gobble = abs(get_int_opt(opts, 'gobble', 0))
    if gobble:
        lexer.add_filter('gobble', n=gobble)

    tabsize = abs(get_int_opt(opts, 'tabsize', 0))
    if tabsize:
        lexer.tabsize = tabsize

    encoding = opts['encoding']
    if encoding == 'guess':
        try:
            import chardet
        except ImportError:
            try:
                text = text.decode('utf-8')
                if text.startswith(u'\ufeff'):
                    text = text[len(u'\ufeff'):]
                    encoding = 'utf-8'
            except UnicodeDecodeError:
                text = text.decode('latin1')
                encoding = 'latin1'
        else:
            encoding = chardet.detect(text)['encoding']
            text = text.decode(encoding)
    else:
        text = text.decode(encoding)

    lexer.encoding = ''
    _fmter.encoding = encoding

    stylename = opts['sty']

    _fmter.style = get_style_by_name(stylename)
    _fmter._create_stylesheet()

    _fmter.texcomments = get_bool_opt(opts, 'texcomments', False)
    _fmter.mathescape = get_bool_opt(opts, 'mathescape', False)

    if stylename not in usedstyles:
        styledefs = _fmter.get_style_defs() \
            .replace('#', '##') \
            .replace(r'\##', r'\#') \
            .replace(r'\makeatletter', '') \
            .replace(r'\makeatother', '') \
            .replace('\n', '%\n')
        outfile.write(
            '\\def\\PYstyle{0}{{%\n{1}%\n}}%\n'.format(stylename, styledefs))
        usedstyles.append(stylename)

    x = highlight(text, lexer, _fmter)

    m = re.match(r'\\begin\{Verbatim}(.*)\n([\s\S]*?)\n\\end\{Verbatim}(\s*)\Z',
                 x)
    if m:
        linenos = get_bool_opt(opts, 'linenos', False)
        linenostart = abs(get_int_opt(opts, 'linenostart', 1))
        linenostep = abs(get_int_opt(opts, 'linenostep', 1))
        lines0 = m.group(2).split('\n')
        numbers = []
        lines = []
        counter = linenostart
        for line in lines0:
            line = re.sub(r'^ ', r'\\makebox[0pt]{\\phantom{Xy}} ', line)
            line = re.sub(r' ', '~', line)
            if linenos:
                if (counter - linenostart) % linenostep == 0:
                    line = r'\pygmented@lineno@do{' + str(counter) + '}' + line
                    numbers.append(str(counter))
                counter = counter + 1
            lines.append(line)
        if inline_delim:
            outfile.write(INLINE_SNIPPET_TEMPLATE %
                dict(number    = n,
                     style     = stylename,
                     options   = extra_opts,
                     body      = '\\newline\n'.join(lines)))
        else:
            if linenos:
                template = DISPLAY_LINENOS_SNIPPET_TEMPLATE
            else:
                template = DISPLAY_SNIPPET_TEMPLATE
            outfile.write(template %
                dict(number      = n,
                     style       = stylename,
                     options     = extra_opts,
                     linenosep   = opts['linenosep'],
                     linenumbers = ','.join(numbers),
                     body        = '\\newline\n'.join(lines)))
Example #44
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()
Example #45
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))