public async Task <string> EvaluateBlockAsync(RCodeBlock block, CancellationToken ct) { block.State = CodeBlockState.Created; await TaskUtilities.SwitchToBackgroundThread(); try { ct.ThrowIfCancellationRequested(); var session = await EvalSession.StartSessionAsync(ct); var callback = EvalSession.SessionCallback; session.Output += OnSessionOutput; await ExecuteAndCaptureOutputAsync(session, block.Text, ct); if (callback.PlotResult != null) { block.Result = Invariant($"<img src='data:image/gif;base64, {Convert.ToBase64String(callback.PlotResult)}' style='display:block; margin: 0 auto; text-align: center;' />"); callback.PlotResult = null; } else if (_output != null && _output.Length > 0) { block.Result = block.DisplayMessages ? HtmlFormatter.FormatCode(_output.ToString()) : string.Empty; } else if (_errors != null && _errors.Length > 0) { block.Result = block.DisplayMessages && block.DisplayErrors ? FormatError(_errors.ToString()) : string.Empty; } } catch (Exception ex) when(!ex.IsCriticalException()) { _output = _errors = null; block.Result = FormatError(ex.Message); } finally { if (EvalSession.RSession != null) { EvalSession.RSession.Output -= OnSessionOutput; } SignalActivity(); } block.State = CodeBlockState.Evaluated; return(block.Result); }
protected override void Write(HtmlRenderer renderer, CodeBlock codeBlock) { renderer.EnsureLine(); var fencedCodeBlock = codeBlock as FencedCodeBlock; if (codeBlock.Column > 0 || fencedCodeBlock?.Info == null) { if (codeBlock.Span.Length > 0) { var text = new string(' ', codeBlock.Column) + _documentText.Substring(codeBlock.Span.Start, codeBlock.Span.Length); renderer.Write(HtmlFormatter.FormatCode(text, "background-color: rgba(0, 0, 0, 0.04);")); } return; } // For R blocks indent count must be zero (no whitespace before ```{r} if (MarkdownUtility.GetRCodeBlockSeparatorLength(fencedCodeBlock.Info, out int start)) { var text = fencedCodeBlock.GetText(); var rCodeBlock = new RCodeBlock(_blockNumber, text, fencedCodeBlock.Arguments); var result = GetCachedResult(_blockNumber, rCodeBlock.Hash, fencedCodeBlock); if (result != null) { renderer.Write(result); } else { var elementId = rCodeBlock.HtmlElementId; _blocks.Add(rCodeBlock); // Write placeholder first. We will insert actual data when the evaluation is done. renderer.Write(GetBlockPlaceholder(elementId, text)); } _blockNumber++; } }
private string FormatError(string error) => HtmlFormatter.FormatCode(error, "color: red;");
private static string GetCodeHtml(string code) => HtmlFormatter.FormatCode(code, "background-color: rgba(0, 0, 0, 0.04);");