| 1 | | from slides import Lecture, Slide, Bullet, PRE, Image, SubBullet, cgi |
| 2 | | from pygments.lexers import get_lexer_by_name |
| 3 | | from pygments.formatters import get_formatter_by_name |
| 4 | | import pygments |
| | 1 | from slides import Lecture, Slide, Bullet, PRE, Image, SubBullet, CODE, PYCODE, PYCON, cgi |
| 23 | | |
| 24 | | class CODE(object): |
| 25 | | def __init__(self, code, lexer="python", formatter="html", style="default"): |
| 26 | | self.code = self._strip_indent(code) |
| 27 | | self.lexer = get_lexer_by_name(lexer) |
| 28 | | self.formatter = get_formatter_by_name(formatter, style=style) |
| 29 | | |
| 30 | | def toHTML(self): |
| 31 | | return pygments.highlight(self.code, self.lexer, self.formatter) |
| 32 | | |
| 33 | | def _strip_indent(self, code): |
| 34 | | """Remove lead and trailing blank lines and strip indents.""" |
| 35 | | itr = iter(code.split("\n")) |
| 36 | | for line in itr: |
| 37 | | if line.strip(): |
| 38 | | break |
| 39 | | indent = len(line) - len(line.lstrip()) |
| 40 | | lines = [line[indent:]] |
| 41 | | for line in itr: |
| 42 | | lines.append(line[indent:]) |
| 43 | | while lines and not lines[-1]: |
| 44 | | del lines[-1] |
| 45 | | return "\n".join(lines) |
| 46 | | |
| 47 | | class PYCODE(CODE): |
| 48 | | def __init__(self, code, formatter="html", style="default"): |
| 49 | | super(PYCODE, self).__init__(code, "python", formatter, style) |
| 50 | | |
| 51 | | class PYCON(CODE): |
| 52 | | def __init__(self, code, formatter="html", style="default"): |
| 53 | | super(PYCON, self).__init__(code, "pycon", formatter, style) |