microsoft/qdk

Public

mirrored from https://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
bbf4bcfa2137a21a1dc31bfc90f1a08ceebb03ce

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

pip/qsharp/_ipython.py

55lines · modecode

1# Copyright (c) Microsoft Corporation.
2# Licensed under the MIT License.
3
4from ._qsharp import (_interpret_with_outputs, QSharpException)
5import pathlib
6
7from IPython.core.magic import (register_cell_magic)
8from IPython.display import display, Javascript
9
10
11def register_magic():
12 @register_cell_magic
13 def qsharp(line, cell):
14 "interpret q# code"
15 try:
16 (value, out) = _interpret_with_outputs(cell)
17 return DisplayableOutput(out, value)
18 except QSharpException as ex:
19 for diagnostic in ex.diagnostics:
20 print("\x1b[31m" + diagnostic.message + "\x1b[0m")
21
22
23class DisplayableOutput:
24 def __init__(self, outputs, value):
25 self.outputs = outputs
26 self.value = value
27
28 def _repr_html_(self):
29 val = ""
30 for output in self.outputs:
31 val += output._repr_html_()
32
33 val += "<p>"
34 val += self.value.__repr__()
35 val += "</p>"
36 return val
37
38
39def enable_classic_notebook_codemirror_mode():
40 """
41 Registers %%qsharp cells with MIME type text/x-qsharp
42 and defines a CodeMirror mode to enable syntax highlighting.
43 This only works in "classic" Jupyter notebooks, not Notebook v7.
44 """
45 js_to_inject = open(pathlib.Path(__file__).parent.resolve().joinpath(
46 ".data", "qsharp_codemirror.js"), mode="r", encoding="utf-8").read()
47
48 # Extend the JavaScript display helper to print nothing when used
49 # in a non-browser context (i.e. IPython console)
50 class JavaScriptWithPlainTextFallback(Javascript):
51 def __repr__(self):
52 return ""
53
54 # This will run the JavaScript in the context of the frontend.
55 display(JavaScriptWithPlainTextFallback(js_to_inject))
56