Last active
December 4, 2017 19:19
-
-
Save bollwyvl/de3b4ca8b6ed8bb28f86 to your computer and use it in GitHub Desktop.
IPython Coffeescript magic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: ascii -*- | |
from __future__ import print_function | |
# A Coffeescript magic for IPython | |
from pygments import highlight | |
from pygments.lexers import JavascriptLexer | |
from pygments.formatters import HtmlFormatter | |
from IPython import display | |
from IPython.core.magic import ( | |
register_cell_magic, | |
Magics, | |
magics_class, | |
cell_magic, | |
) | |
from IPython.core.magic_arguments import ( | |
argument, | |
magic_arguments, | |
parse_argstring, | |
) | |
import coffeescript | |
@magics_class | |
class CoffeescriptMagics(Magics): | |
''' | |
Write and execute Coffeescript in the IPython Notebook | |
Example: | |
%%coffeescript | |
class Foo | |
constructor: -> | |
@bar = "baz" | |
''' | |
def __init__(self, shell): | |
self.lexer = JavascriptLexer() | |
super(CoffeescriptMagics, self).__init__(shell) | |
@cell_magic | |
@magic_arguments() | |
@argument("-b", "--bare", default=False, action="store_true", | |
help="Return the compiled code without wrapping in an IIFE.") | |
@argument("-v", "--verbose", default=False, action="store_true", | |
help="Show generated javascript") | |
def coffeescript(self, line, cell): | |
opts = parse_argstring(self.coffeescript, line) | |
try: | |
src = coffeescript.compile(cell, bare=opts.bare) | |
if opts.verbose: | |
pretty = highlight(src, self.lexer, HtmlFormatter(full=True)) | |
return display.HTML("%s<script>%s</script>" % (pretty, src)) | |
return display.HTML("<script>%s</script>" % src) | |
except Exception as err: | |
print(err) | |
def load_ipython_extension(ip): | |
ip = get_ipython() | |
ip.register_magics(CoffeescriptMagics) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CoffeeScript | |
pygments | |
IPython>=2.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment