microsoft/qdk
Publicmirrored from https://github.com/microsoft/qdkAvailable
pip/qsharp/_ipython.py
46lines · modecode
| 1 | # Copyright (c) Microsoft Corporation. |
| 2 | # Licensed under the MIT License. |
| 3 | |
| 4 | from IPython.display import display, Javascript, Pretty |
| 5 | from IPython.core.magic import register_cell_magic |
| 6 | from ._native import QSharpError |
| 7 | from ._qsharp import _interpreter |
| 8 | import pathlib |
| 9 | |
| 10 | |
| 11 | def register_magic(): |
| 12 | @register_cell_magic |
| 13 | def qsharp(line, cell): |
| 14 | """Cell magic to interpret Q# code in Jupyter notebooks.""" |
| 15 | |
| 16 | def callback(output): |
| 17 | display(output) |
| 18 | |
| 19 | try: |
| 20 | return _interpreter.interpret(cell, callback) |
| 21 | except QSharpError as e: |
| 22 | display(Pretty(str(e))) |
| 23 | |
| 24 | |
| 25 | def enable_classic_notebook_codemirror_mode(): |
| 26 | """ |
| 27 | Registers %%qsharp cells with MIME type text/x-qsharp |
| 28 | and defines a CodeMirror mode to enable syntax highlighting. |
| 29 | This only works in "classic" Jupyter notebooks, not Notebook v7. |
| 30 | """ |
| 31 | js_to_inject = open( |
| 32 | pathlib.Path(__file__) |
| 33 | .parent.resolve() |
| 34 | .joinpath(".data", "qsharp_codemirror.js"), |
| 35 | mode="r", |
| 36 | encoding="utf-8", |
| 37 | ).read() |
| 38 | |
| 39 | # Extend the JavaScript display helper to print nothing when used |
| 40 | # in a non-browser context (i.e. IPython console) |
| 41 | class JavaScriptWithPlainTextFallback(Javascript): |
| 42 | def __repr__(self): |
| 43 | return "" |
| 44 | |
| 45 | # This will run the JavaScript in the context of the frontend. |
| 46 | display(JavaScriptWithPlainTextFallback(js_to_inject)) |
| 47 | |