Sphinx inline code highlight

前端 未结 6 1604
暖寄归人
暖寄归人 2021-02-07 11:03

I use Sphinx to make a website that contains code samples. I\'m successful using the .. code-block directive to get syntax highlighting. But I can\'t get inline syn

6条回答
  •  醉酒成梦
    2021-02-07 11:34

    OK I used this workaround: I generate a css file that contains both short and long names. I'm still interested in the "good" answer.

    #!/usr/bin/env python
    
    """Generate a css file thanks to pygments that will contain both short
    and long class names."""
    
    
    import subprocess
    import sys
    
    
    PYGMENTIZE = 'pygmentize'
    
    
    def parse_command_line():
        import argparse
        parser = argparse.ArgumentParser(description=__doc__)
        parser.add_argument('-s', '--style', default='colorful')
        parser.add_argument('-p', '--prefix', default='.highlight')
        return parser.parse_args()
    
    
    def pygmentize(style, prefix='.highlight'):
        cmd = '{0} -f html -S {1} -a {2}'.format(PYGMENTIZE, style, prefix)
        # This will fail if pygmentize does not exist.
        try:
            p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
        except OSError:
            print >> sys.stderr, '{0}: command not found'.format(PYGMENTIZE)
            exit(1)
    
        out, err = p.communicate()
        if p.returncode != 0:
            exit(p.returncode)
        return out
    
    
    def main():
        args = parse_command_line()
        style = args.style
        prefix = args.prefix
    
        # Print new css header.
        header = """\
    /* 
     * This is pygment css style {0} generated with
     *     {1}
     */""".format(style, ' '.join(sys.argv))
        print header
    
        # Parse pygmentize output.
        # Find long names based on comments.
        content = pygmentize(style, prefix)
        s = content.splitlines()
        out = ''
        for line in s:
            start = line.find("/* ") + 3
            end = line.find(" */")
            # if line has a comment
            if start != 2:
                comment = line[start:end]
                name = '.' + comment.lower()
                arg = line[line.find('{ '): start - 4]
                out += '%(prefix)s %(name)s %(arg)s\n' % vars()
    
        print content
        print out
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题