| | 253 | # |
| | 254 | # Syntax highlighting for code using pygments. |
| | 255 | # |
| | 256 | |
| | 257 | class CODE(object): |
| | 258 | """Syntax highlight code using pygments. |
| | 259 | |
| | 260 | Imports pygments inside methods so that slides |
| | 261 | can function without pygments. |
| | 262 | """ |
| | 263 | |
| | 264 | def __init__(self, code, lexer="python", formatter="html", style="default"): |
| | 265 | self.code = self._strip_indent(code) |
| | 266 | self.lexer = self._lexer(lexer) |
| | 267 | self.formatter = self._formatter(formatter, style) |
| | 268 | |
| | 269 | def toHTML(self): |
| | 270 | import pygments |
| | 271 | return pygments.highlight(self.code, self.lexer, self.formatter) |
| | 272 | |
| | 273 | def _strip_indent(self, code): |
| | 274 | """Remove lead and trailing blank lines and strip indents.""" |
| | 275 | itr = iter(code.split("\n")) |
| | 276 | for line in itr: |
| | 277 | if line.strip(): |
| | 278 | break |
| | 279 | indent = len(line) - len(line.lstrip()) |
| | 280 | lines = [line[indent:]] |
| | 281 | for line in itr: |
| | 282 | lines.append(line[indent:]) |
| | 283 | while lines and not lines[-1]: |
| | 284 | del lines[-1] |
| | 285 | return "\n".join(lines) |
| | 286 | |
| | 287 | def _lexer(self, lexer_name): |
| | 288 | """Fetch a pygments lexer by name.""" |
| | 289 | from pygments.lexers import get_lexer_by_name |
| | 290 | return get_lexer_by_name(lexer_name) |
| | 291 | |
| | 292 | def _formatter(self, formatter_name, style_name): |
| | 293 | """Fetch a pygments formatter using formatter and style names.""" |
| | 294 | from pygments.formatters import get_formatter_by_name |
| | 295 | return get_formatter_by_name(formatter_name, style=style_name) |
| | 296 | |
| | 297 | class PYCODE(CODE): |
| | 298 | """Syntax hightlight Python code.""" |
| | 299 | def __init__(self, code, formatter="html", style="default"): |
| | 300 | super(PYCODE, self).__init__(code, "python", formatter, style) |
| | 301 | |
| | 302 | class PYCON(CODE): |
| | 303 | """Syntax highlight Python console sessions.""" |
| | 304 | def __init__(self, code, formatter="html", style="default"): |
| | 305 | super(PYCON, self).__init__(code, "pycon", formatter, style) |