GithubHelp home page GithubHelp logo

gpoore / codebraid Goto Github PK

View Code? Open in Web Editor NEW
362.0 14.0 13.0 767 KB

Live code in Pandoc Markdown

License: BSD 3-Clause "New" or "Revised" License

Python 100.00%
reproducible-research reproducible-workflows reproducible-analysis markdown pandoc-markdown pandoc-filter literate-programming julia-language python rust

codebraid's Introduction

Codebraid – live code in Pandoc Markdown

Codebraid is a Python program that enables executable code in Pandoc Markdown documents. Using Codebraid can be as simple as adding a class to your code blocks' attributes, and then running codebraid rather than pandoc to convert your document from Markdown to another format. codebraid supports almost all of pandoc's options and passes them to pandoc internally. See Codebraid Preview for VS Code for editor support. See the Codebraid website for additional examples and documentation.

Codebraid provides two options for executing code. It includes a built-in code execution system that currently supports Python 3.7+, Julia, Rust, R, Bash, JavaScript, GAP and SageMath. Code can also be executed using Jupyter kernels, with support for rich output like plots.

Development: https://github.com/gpoore/codebraid

Citing Codebraid: "Codebraid: Live Code in Pandoc Markdown", Geoffrey M. Poore, Proceedings of the 18th Python in Science Conference, 2019, 54-61.

View example HTML output, or see the Markdown source or raw HTML (the Python and Rust examples demonstrate more advanced features at the end):

Simple example

Markdown source test.md:

```{.python .cb-run}
var = 'Hello from Python!'
var += ' $2^8 = {}$'.format(2**8)
```

```{.python .cb-run}
print(var)
```

Run codebraid (to save the output, add something like -o test_out.md, and add --overwrite if it already exists):

codebraid pandoc --from markdown --to markdown test.md

Output:

Hello from Python! $2^8 = 256$

As this example illustrates, variables persist between code blocks; by default, code is executed within a single session. Code output is also cached by default so that code is only re-executed when modified.

Features

Comparison with Jupyter, knitr, and Pweave

Codebraid Jupyter Notebook knitr Pweave
multiple programming languages per document ✓* ✓† ✓*
multiple independent sessions per language
inline code execution within paragraphs
no out-of-order code execution ✓‡
no markdown preprocessor or custom syntax
minimal diffs for easy version control
insert code output anywhere in a document
can divide code into incomplete snippets
support for literate programming
compatible with any text editor

* One primary language from the Jupyter kernel. The IPython kernel supports additional languages via %%script magics. There is no continuity between %%script cells, because each cell is executed in a separate process. Some magics, such as those provided by PyJulia and rpy2, provide more advanced capabilities.
† knitr only provides continuity between code chunks for R, and more recently Python and Julia. Code chunks in other languages are executed individually in separate processes.
‡ Out-of-order execution is possible with R Markdown notebooks.


The table above summarizes Codebraid features in comparison with Jupyter notebooks (without extensions), knitr (R Markdown), and Pweave, emphasizing Codebraid's unique features. Here are some additional points to consider:

Jupyter notebooks — Notebooks have a dedicated, browser-based graphical user interface. Jupyter kernels typically allow the code in a cell to be executed without re-executing any preceding code, providing superior interactivity. Codebraid has advantages for projects that are more focused on creating a document than on exploratory programming.

knitr — R Markdown documents have a dedicated user interface in R Studio. knitr provides superior support for R, as well as significant Python and Julia support that includes R integration. Codebraid offers continuity between code chunks for all supported languages, as well as multiple independent sessions per language. It also provides unique options for displaying code and its output.

More about key features

Easy debugging — By default, stderr is shown automatically in the document whenever there is an error, right next to the code that caused it. It is also possible to monitor code output in real time during execution via --live-output.

Simple language support — Codebraid supports Jupyter kernels. It also has a built-in system for executing code. Adding support for a new language with this system can take only a few minutes. Just create a config file that tells Codebraid which program to run, which file extension to use, and how to write to stdout and stderr. See languages/ for examples.

No preprocessor — Unlike many approaches to making code in Markdown executable, Codebraid is not a preprocessor. Rather, Codebraid acts on the abstract syntax tree (AST) that Pandoc generates when parsing a document. Preprocessors often fail to disable commented-out code blocks because the preprocessor doesn't recognize Markdown comments. Preprocessors can also fail due to the finer points of Markdown parsing. None of this is an issue for Codebraid, because Pandoc does the Markdown parsing.

No custom syntax — Codebraid introduces no additional Markdown syntax. Making a code block or inline code executable uses Pandoc's existing syntax for defining code attributes.

Installation and requirements

Installation: pip3 install codebraid or pip install codebraid

Manual installation: python3 setup.py install or python setup.py install

Requirements:

  • Pandoc 2.4+ (2.17.1.1+ recommended for commonmark_x).

  • Python 3.7+ with setuptools, and bespon 0.6 (bespon installation is typically managed by pip/setup.py)

  • For Jupyter support, jupyter_client and language kernels

  • For YAML metadata support, ruamel.yaml (can be ruamel_yaml for Anaconda installations)

Converting a document

Simply run codebraid pandoc <normal pandoc options>. Codebraid currently supports Pandoc Markdown (--from markdown) and CommonMark with Pandoc extensions (--from commonmark_x) as input formats.

Note that --overwrite is required to overwrite existing files. If you are using a defaults file, --from, --to, and --output must be given explicitly and cannot be inherited from the defaults file. If you are using a defaults file and converting to a standalone Pandoc Markdown document, --standalone should be given explicitly rather than being inherited from the defaults file.

codebraid should typically be run in the same directory as the document, so that the default working directory for code is the document directory.

If you are converting from Pandoc Markdown to Pandoc Markdown with --standalone (basically using codebraid to preprocess Markdown documents), note that the following YAML metadata fields and command-line options are ignored in that situation:

  • header-includes and --include-in-header
  • include-before and --include-before-body
  • include-after and --include-after-body
  • toc/table-of-contents and --toc/--table-of-contents

This is typically what you want. Usually, "include" and a table of contents are desired in a final output format like HTML or PDF, not in a Pandoc Markdown file. In the rare cases where "includes" and a table of contents are needed in Markdown documents, this can be accomplished by piping the output of codebraid through pandoc.

Additional non-Pandoc command-line options

  • --live-output — Show code output (stdout and stderr) live in the terminal during code execution. For Jupyter kernels, also show errors and a summary of rich output. Output still appears in the document as normal.

    Individual sessions can override this by setting live_output=false in the document.

  • --no-execute — Disables code execution. Only use available cached output.

  • --only-code-output={format} — Write code output in JSON Lines format to stdout as soon as it is available, and do not create a document.

    This is intended for use with Codebraid Preview, so that document previews can be updated during code execution. Currently, the only supported format is codebraid_preview. One JSON data object followed by a newline is written to stdout for each code chunk. In some cases, the data for a chunk will be resent later if the data relevant for a chunk changes (for example, if code execution fails after the first chunk runs, but in such a way that an error message needs to be attached to the first chunk). Data for a chunk is sent as soon as it is available from code processing, from cache, or from code execution (as soon as the chunk completes, typically before the session completes). Additional JSON data may be sent to provide tracking of code execution progress or information such as metadata. The JSON data provided for format codebraid_preview may change between minor versions.

Caching

By default, code output is cached, and code is only re-executed when it is modified. The default cache location is a _codebraid directory in the working directory (directory where codebraid is run, typically the document directory). This can be modified using --cache-dir. Multiple documents can share a single cache location. A cache directory can be synced between different operating systems (such as Windows and Linux) while retaining full functionality so long as documents are in equivalent locations under the user's home directory (as resolved by os.path.expanduser()).

When multiple documents share the same cache location, each document will automatically clean up its own unused, outdated files. However, if a document is deleted or renamed, it may leave behind unused files in the cache, so it may be worth manually deleting and regenerating the cache in those circumstances. Future cache enhancements should be able to detect all unused files, making this unnecessary.

If you are working with external data that changes, you should run codebraid with --no-cache or delete the cache as necessary to prevent the cache from becoming out of sync with your data. Future releases will allow external dependencies to be specified so that caching will work correctly in these situations.

YAML metadata

Some document-wide settings can be given in the Markdown YAML metadata. Codebraid settings must be under either a codebraid or codebraid_ key in the metadata. Pandoc will ignore codebraid_ so it will not be available to filters; this distinction should not typically be important.

To use Jupyter kernels automatically for all sessions, simply set jupyter: true. For example,

---
codebraid:
  jupyter: true
---

It is also possible to set a default kernel and/or default timeout. For example,

---
codebraid:
  jupyter:
    kernel: python3
    timeout: 120
---

A Jupyter kernel and/or timeout can still be set in the first code chunk for a given session, and will override the document-wide default.

It is also possible to set live_output: <bool> in the metadata. Additional metadata settings will be added in future releases.

Code options

Commands (Classes)

Code is made executable by adding a Codebraid class to its Pandoc attributes. For example, `code`{.python} becomes `code`{.python .cb-run}.

When code is executed, the output will depend on whether the built-in code execution system or a Jupyter kernel is used.

When code is executed with the built-in system, the output is equivalent to collecting all code for each session of each language, saving it to a file, and then executing it (with an added compile step for some languages). For example, running Python code is equivalent to saving it to file.py and then running python file.py, while running R code is equivalent to saving it to file.R and then running Rscript file.R. Code is not executed as it would be in an interactive session (like running python or R at the command prompt). As a result, some output that would be present in an interactive session is absent. For example, in interactive sessions for some languages, simply entering a variable returns a string representation without explicit printing, and plotting opens a separate image window or displays an image inline. Such output is absent in Codebraid unless it is also produced when code is executed as a script rather than in an interactive session. The .cb-expr command is provided for when an inline string representation of a variable is desired.

An option for interactive-style code execution with the built-in system is planned for a future release. In the meantime, many interactive-style features are available between the .cb-expr command and Jupyter kernels.

When code is executed with a Jupyter kernel, the default output will be equivalent to executing it in a Jupyter notebook. Rich output such plots, images, and LaTeX math will be displayed automatically by default. This can be customized by using the show and hide options.

All classes for making code executable are listed below. These all have the form .cb-<command>. Classes with the form .cb.<command> (period rather than hyphen) are supported for Pandoc Markdown (--from markdown), but not for commonmark_x since it has a more restricted class syntax. The forms shown below (.cb-<command>) should be preferred for compatibility across Markdown variants supported by Pandoc.

  • .cb-code — Insert code verbatim, but do not run it. This is primarily useful when combined with other features like naming and then copying code chunks.

  • .cb-expr — Evaluate an expression and interpret the result as Markdown. Only works with inline code. This is not currently compatible with Jupyter kernels.

  • .cb-nb — Execute code in notebook mode. For inline code, this is equivalent to .cb-expr with verbatim output unless a Jupyter kernel is used, in which case rich output like plots or LaTeX will be displayed. For code blocks, this inserts the code verbatim, followed by any printed output (stdout) verbatim. If stderr exists, it is also inserted verbatim. When a Jupyter kernel is used, rich output like plots or LaTeX is also displayed.

  • .cb-paste — Insert code and/or output copied from one or more named code chunks. The copy keyword is used to specify chunks to be copied. This does not execute any code. Unless show is specified, display options are inherited from the first copied code chunk.

    If content is copied from multiple code chunks that are executed, all code chunks must be in the same session and must be in sequential order without any omitted chunks. This ensures that what is displayed is always consistent with what was executed.

    If content is copied from another cb-paste code chunk, only a single code chunk can be copied. This reduces the indirection that is possible when displaying the output of code that has been executed. This restriction may be removed in the future.

  • .cb-run — Run code and interpret any printed content (stdout) as Markdown. Also insert stderr verbatim if it exists. When a Jupyter kernel is used, rich output like plots or LaTeX is also displayed.

Keyword arguments

Pandoc code attribute syntax allows keyword arguments of the form key=value, with spaces (not commas) separating subsequent keys. value can be unquoted if it contains only letters and some symbols; otherwise, double quotation marks "value" are required. For example,

{.python key1=value1 key2=value2}

Codebraid adds support for additional keyword arguments. In some cases, multiple keywords can be used for the same option. This is primarily for Pandoc compatibility.

First chunk settings

These are only permitted for the first code chunk in a session (or the first chunk for a language, if a session is not specified and thus the default session is in use).

  • executable={string} — Executable to use for running or compiling code, instead of the default. This only applies to Codebraid's built-in code execution system.

  • executable_opts={string} — Command-line options passed to executable. This only applies to Codebraid's built-in code execution system.

  • args={string} — Command-line arguments passed to code during execution. For example, this could be used to add values to sys.argv for Python. This only applies to Codebraid's built-in code execution system.

  • jupyter_kernel={string} — Jupyter kernel to use for executing code instead of Codebraid's built-in code execution system. Multiple Jupyter kernels can be used within a single document, and multiple sessions are possible per kernel. Except when otherwise specified, Jupyter kernels should be usable just like the built-in code execution system.

  • jupyter_timeout={int} — Jupyter kernel timeout per code chunk in seconds. The default is 60.

  • live_output={true, false} — Show code output (stdout and stderr) live in the terminal during code execution. For Jupyter kernels, also show errors and a summary of rich output. Output still appears in the document as normal. Showing output can also be enabled via the command-line option --live-output.

    When live_output=false is set for a session, this setting takes precedence over the command-line option --live-output, and output will not be shown for that session.

    All output is written to stderr, so stdout only contains the document when --output is not specified. Output is interspersed with delimiters marking the start of each session and the start of each code chunk. The delimiters for the start of each code chunk include source names and line numbers.

    With Codebraid's built-in code execution system, the output for a code chunk may be delayed until all code in the chunk has finished executing, unless code output is line buffered or code manually flushes stdout and stderr. For example, with Python you may want to use print functions like print("text", flush=True). Another option is to use Python in line-buffered mode by setting executable_opts="-u" in the first code chunk of a session.

    With Jupyter kernels, the output for a code chunk will be delayed until all code in the chunk has finished executing.

Execution

  • complete={true, false} — By default, code chunks must contain complete units of code (function definitions, loops, expressions, and so forth). With complete=false, this is not required. Any stdout from code chunks with complete=false is accumulated until the next code chunk with complete=true (the default value), or until the end of the session, whichever comes first.

    Setting complete is incompatible with outside_main=true, since the complete status of code chunks with outside_main=true is inferred automatically.

  • outside_main={true, false} — This allows code chunks to overwrite the Codebraid template code when code is executed with Codebraid's built-in code execution system. It is primarily useful for languages like Rust, in which code is inserted by default into a main() template. In that case, if a session starts with one or more code chunks with outside_main=true, these are used instead of the beginning of the main() template. Similarly, if a session ends with one or more code chunks with outside_main=true, these are used instead of the end of the main() template. If there are any code chunks in between that lack outside_main (that is, default outside_main=false), then these will have their stdout collected on a per-chunk basis like normal. Having code chunks that lack outside_main is not required; if there are none, the total accumulated stdout for a session belongs to the last code chunk in the session.

    outside_main=true is incompatible with explicitly setting complete. The complete status of code chunks with outside_main=true is inferred automatically.

  • session={identifier-style string} — By default, all code for a given language is executed in a single, shared session so that data and variables persist between code chunks. This option allows code to be separated into multiple independent sessions. Session names must be Python-style identifiers.

Display

  • first_number/startFrom/start-from/start_from={integer or next} — Specify the first line number for code when line numbers are displayed. next means continue from the last code in the current session.

  • hide={markup, copied_markup, code, stdout, stderr, expr, rich_output, all} — Hide some or all of the elements that are displayed by default. Elements can be combined. For example, hide=stdout+stderr. Note that expr only applies to .cb-expr or .cb-nb with inline code using Codebraid's built-in code execution system, since only these evaluate an expression. rich_output is currently only relevant for Jupyter kernels.

  • hide_markup_keys={key(s)} — Hide the specified code chunk attribute key(s) in the Markdown source displayed via markup or copied_markup. Multiple keys can be specified via hide_markup_keys=key1+key2.

    hide_markup_keys only applies to the code chunk in which it is used, to determined the markup for that code chunk. Thus, it only affects copied_markup indirectly.

  • line_numbers/numberLines/number-lines/number_lines={true, false} — Number code lines in code blocks.

  • show={markup, copied_markup, code, stdout, stderr, expr, rich_output, none} — Override the elements that are displayed by default. expr only applies to .cb-expr and to .cb-nb with inline code using Codebraid's built-in code execution system, since only these evaluate an expression. Elements can be combined. For example, show=code+stdout.

    Each element except rich_output can optionally specify a format from raw, verbatim, or verbatim_or_empty. For example, show=code:verbatim+stdout:raw.

    • raw means interpreted as Markdown.
    • verbatim produces inline code or a code block, depending on context. Nothing is produced if there is no content (for example, nothing in stdout.)
    • verbatim_or_empty produces inline code containing a single non-breaking space or a code block containing a single empty line in the event that there is no content. It is useful when a placeholder is desired, or a visual confirmation that there is indeed no output.

    For rich_output, the format is specified as one or more abbreviations for the mime types of the output to be displayed. For example, rich_output:plain will display text/plain output if it exists, and otherwise nothing. rich_output:png|plain will display a PNG image if it exists, or otherwise will fall back to plain text if available. The following formats are currently supported:

    • latex (corresponds to text/latex)
    • html (text/html)
    • markdown (text/markdown)
    • plain (text/plain)
    • png (image/png)
    • jpg and jpeg (image/jpeg)
    • svg (image/svg+xml)
    • pdf (application/pdf)

    For rich_output formats with a text/* mime type (latex, html, markdown, plain), it is possible to specify whether they are displayed raw, verbatim, or verbatim_or_empty. For example, show=rich_output:latex:raw and show=rich_output:latex:verbatim. raw treats latex and html as raw content with those formats embedded within Markdown. raw treats markdown and plain as Markdown. When a display style is not specified, all rich_output formats with a text/* mime type are displayed raw by default, except for plain which is displayed verbatim.

    markup displays the Markdown source for the inline code or code block. Because the Markdown source is not available in the Pandoc AST but rather must be recreated from it, the Markdown source displayed with markup may use a different number of backticks, quote attribute values slightly differently, or contain other insignificant differences from the original document.

    copied_markup displays the Markdown source for code chunks copied via copy.

    expr defaults to raw if a format is not specified. rich_output defaults to latex|markdown|png|jpg|svg|plain. All others default to verbatim.

  • example={bool} — Insert a code block containing the Markdown source of the code chunk, followed by the rest of the output as normal. This is only valid for inline code if the code is in a paragraph by itself. This option is currently not compatible with --only-code-output and Codebraid Preview. This option is intended primarily for documentation about Codebraid.

Copying

  • copy={chunk name(s)} — Copy one or more named code chunks. When copy is used with a command like .cb-run that executes code, only the code is copied, and it is executed as if it had been entered directly. When copy is used with .cb-code, only the code is copied and nothing is executed. When copy is used with .cb-paste, both code and output are copied, and nothing is executed. Multiple code chunks may be copied; for example, copy=name1+name2. In that case, the code from all chunks is concatenated, as is any output that is copied. Because copy brings in code from other code chunks, the actual content of a code block or inline code using copy is discarded. As a result, this must be empty, or a space or underscore can be used as a placeholder.

  • name={identifier-style string} — Name a code chunk so that it can later be copied by name. Names must be Python-style identifiers.

Including external files

  • include_file={path} — Include the specified file. A leading ~/ or ~<user>/ is expanded to the user's home directory under all operating systems, including under Windows with both slashes and backslashes.

    When include_file is used with a command like .cb-run that executes code, the file is included and executed as part of the current session just as if the file contents had been entered directly. When include_file is used with .cb-code, the file is included and displayed just as if it had been entered directly. Because include_file brings in code from another file, the actual content of a code block or inline code using include_file is discarded. As a result, this must be empty, or a space or underscore can be used as a placeholder.

  • include_encoding={encoding} — Encoding for included file. The default encoding is UTF-8.

  • include_lines={lines/line ranges} — Include the specified lines or line ranges. For example, 1-3,5,7-9,11-. Line numbers are one-indexed. Line ranges are inclusive, so 1-3 is 1 up to and including 3. If a range ends with a hyphen, like 11-, then everything is included from the line through the end of the file.

    Cannot be combined with other include options that specify what is to be included.

  • include_regex={regex} — Include the first segment of the file that matches the provided regular expression.

    Keep in mind that Pandoc's key-value attributes evaluate backslash escapes in values whether or not the values are quoted with double quotation marks, so two levels of backslash-escaping are always necessary (one for Pandoc's strings, one for the regex itself; there are no raw strings). Regular expressions use multiline mode, so ^/$ match the start/end of a line, and \A/\Z can be used to match the start/end of the file. Regular expressions use dotall mode, so . matches anything including the newline \n; use [^\n] when this is not desired.

    Cannot be combined with other include options that specify what is to be included.

  • include_start_string={string} — Include everything from the first occurrence of this string onward.

    Can only be combined with other include options that specify the end of what is to be included.

  • include_start_regex={regex} — Include everything from the first match of this regex onward.

    Can only be combined with other include options that specify the end of what is to be included. See include_regex for notes on regex usage.

  • include_after_string={string} — Include everything after the first occurrence of this string onward.

    Can only be combined with other include options that specify the end of what is to be included.

  • include_after_regex={regex} — Include everything after the first match of this regex onward.

    Can only be combined with other include options that specify the end of what is to be included. See include_regex for notes on regex usage.

  • include_before_string={string} — Include everything before the first occurrence of this string.

    Can only be combined with other include options that specify the start of what is to be included. If the start is specified, then the first occurrence after this point is used, rather than the first occurrence in the overall file.

  • include_before_regex={regex} — Include everything before the first match of this regex.

    Can only be combined with other include options that specify the start of what is to be included. If the start is specified, then the first match after this point is used, rather than the first match in the overall file. See include_regex for notes on regex usage.

  • include_end_string={string} — Include everything through the first occurrence of this string.

    Can only be combined with other include options that specify the start of what is to be included. If the start is specified, then the first occurrence after this point is used, rather than the first occurrence in the overall file.

  • include_end_regex={regex} — Include everything through the first match of this regex.

    Can only be combined with other include options that specify the start of what is to be included. If the start is specified, then the first match after this point is used, rather than the first match in the overall file. See include_regex for notes on regex usage.

codebraid's People

Contributors

chrisjefferson avatar datadavev avatar gpoore avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

codebraid's Issues

`--project=@.` for Julia and support for flags based on version

Julia support may need --project=@. or possibly a way to add custom --project. This only exists for Julia >=v0.7.

This raises the question of whether there should be a system for adding user-supplied flags to the run_command template, or allowing the user to override run_command completely. It also suggests that version-conditional run_command might be useful in some cases (even if it is ultimately avoided for Julia by dropping support for <v0.7).

Related PythonTeX issue: gpoore/pythontex#158

where should I put pandoc.exe?

pandoc.exe is in one directory of my PATH environmental variant, so I can run pandoc.exe under any directory in the dos console
however, codebraid can not find pandoc.exe. So where should I put pandoc.exe? Or should codebraid consider PATH?

thanks

Use of inline html code characters appears to break source file parsing

Markdown files with html coded characters result in a StopIteration error from codebraid.

Minimal reproducing example

$ echo "I need &#36;20." > foo.md
$ cat foo.md
I need &#36;20.
$ pandoc --from markdown --to html foo.md -o foo.html  # Works as expected
$ cat foo.html
<p>I need $20.</p>
$ codebraid pandoc --from markdown --to html foo.md -o foo.html
Traceback (most recent call last):
  File "/home/ross/.virtualenvs/elegant-scipy/bin/codebraid", line 8, in <module>
    sys.exit(main())
  File "/home/ross/.virtualenvs/elegant-scipy/lib/python3.9/site-packages/codebraid/cmdline.py", line 107, in main
    args.func(args)
  File "/home/ross/.virtualenvs/elegant-scipy/lib/python3.9/site-packages/codebraid/cmdline.py", line 153, in pandoc
    converter.code_braid()
  File "/home/ross/.virtualenvs/elegant-scipy/lib/python3.9/site-packages/codebraid/converters/base.py", line 1198, in code_braid
    self._extract_code_chunks()
  File "/home/ross/.virtualenvs/elegant-scipy/lib/python3.9/site-packages/codebraid/converters/pandoc.py", line 1124, in _extract_code_chunks
    self._load_and_process_initial_ast(source_string=source_string, single_source_name=source_name)
  File "/home/ross/.virtualenvs/elegant-scipy/lib/python3.9/site-packages/codebraid/converters/pandoc.py", line 994, in _load_and_process_initial_ast
    source_name, line, line_number = next(source_name_line_and_number_iter)
StopIteration

It seems this is tangentially related to other issues re: handling escape characters e.g. #36. The discussions there and in #38 nicely explain how the StopIteration exception itself comes about.

Version info

Python: 3.9.2
codebraid: 0.5.0
pandoc: 2.13

Code block tab indentation error (Python)

When running python with tabs instead of spaces for scope, codebraid does not compile the document.
This will fail

```{.python .cb.run}
for i in range(5):
	print(i)

While this will run

```{.python .cb.run}
for i in range(5):
    print(i)

AttributeError and TypeError in normal use

Hi,
This looks like a really nice project, and I really wanted to give it a try but unfortunately it crashes badly. First, invoking simply codebraid (without any args) results in:

Traceback (most recent call last):
  File "/home/<user>/venv/pyactr/bin/codebraid", line 11, in <module>
    sys.exit(main())
  File "/home/<user>/venv/pyactr/lib/python3.6/site-packages/codebraid/cmdline.py", line 57, in main
    args.func(args)
AttributeError: 'Namespace' object has no attribute 'func'

And using codebraid pandoc rep.md -o rep.pdfreturns:

Traceback (most recent call last):
  File "/home/<user>/venv/pyactr/bin/codebraid", line 11, in <module>
    sys.exit(main())
  File "/home/<user>/venv/pyactr/lib/python3.6/site-packages/codebraid/cmdline.py", line 57, in main
    args.func(args)
  File "/home/<user>/venv/pyactr/lib/python3.6/site-packages/codebraid/cmdline.py", line 78, in pandoc
    other_pandoc_args=other_pandoc_args)
  File "/home/<user>/venv/pyactr/lib/python3.6/site-packages/codebraid/converters/pandoc.py", line 1143, in convert
    raise TypeError
TypeError

Do you know what could be wrong?

Integration with jupytext

It would beneficial to integrate with jupytext and hence jupyter notebooks. Jupyter can indeed become an interactive editor for codebraid.

To be able do so a seamless conversion from codebraid to ipynb is required. I believe a pandoc filter could achieve that.

@gpoore Would you be interested in such an approach?

Non-zero exit code when exceptions were issued?

Could you please consider adding a feature of returning non-zero exit codes if one or more exceptions were issued? It would help e.g in using codebraid in Makefiles.

Currently we are to grep the output documents for magic words from stack traces which is a bit fragile.

Workflow Suggestions

Just wanted to get your thoughts on how you use codebraid for your work.

My current workflow is to write the markdown in VSCode and then run the codebraid command every time I want a new version of my document but it's a bit cumbersome.

What's your set up when you write with codebraid? Do you have any recommendations on software?

Using in static website generators

This isn't really a codebraid issue, but do you know if any static website generator (pelican? jekyll? Hugo?) easily supports codebraid?

If anyone knows of integration it would be nice to add to the readme, and I'll switch to any system which let's me easily use it :)

Option to redirect stdout/stderr to user shell?

Hi. I'm using codebraid to run machine-learning experiments which sometimes take long time to complete and tend to show lots of rich debug output like gaudges and progress bars (wget tool prints similar thing).

Currently, I put long-running code in separate blocks and hide rich output by adding {hide=stdout+stderr}. Ideally, it would be nice to include only the final state of progress bars, but I think it is not that important. More useful would be to bypass certain output to the client shell as-is to be able to monitor the progress of experiment.

Could you please consider adding an option which would redirect stout/stderr of a block into the user shell when enabled?

`codebraid` can't handle raw latex

When writing in markdown, codebraid throws an error if you write in raw latex:

## My document

This is text

\newpage

This is text on a new page

Reading from stdin

It would be useful if codebraid could read directly from stdin.
This would allow for piping the output of a pandoc command into codebraid e.g.:

pandoc --filter <filter> --to markdown | codebraid pandoc ...

A common way to implement this in argparse is to use - to specify reading from stdin e.g.:

pandoc --filter <filter> --to markdown | codebraid pandoc - -o result.md

Plots in output

Hi,

First off, thank you for this awesome project.

Your python example in GitHub shows that matplotlib plots needed to be inserted through markdown after being created in python, but your Scipy 2019 article has the figure being created without that step. Does that have something to do with calling the Jupyter kernel option? Can you have that output display as png so that it can be used with pandoc-fignos?

Thank you

How to use the Julia jupyter kernel to generate plots in output

I was trying to understand how to generate plots in a codebraid file with julia codeblocks. Julia has its own jupyter kernel, usually called IJulia.

Would something like this work, or does codebraid not yet support Julia jupyter kernels? Also, usually Julia jupyter kernels are attached to a Julia virtual environment. I think codebraid designed to pick the Julia environment that is in the same directory as the pandoc markdown file--as per the changelog and the addition of the --project=@. flag. So would this set then allow me to call the local IJulia jupyter kernel from the local Julia environment--as opposed to the global environment, etc.

I tried the following code:


```{.julia .cb-nb jupyter_kernel=julia session=random example=true}
using Plots
x = 1:10; y = rand(10); # These are the plotting data
plot(x, y)

While there are no errors, the file does not show the actual plot. I also attached the original file and the pdf.
julia_output.pdf
julia-braid-test.md

StopIteration error with latex gather environments

I've come up to a problem where if I include a \gather environment in my markdown file, I believe that codebraid interprets it as code and fails when running it. Here's a minimal example that doesn't run on my system (backslashes added to python code cell so github showed the whole snippet):

---
title: Midterm
geometry: margin=1in
output: pdf_document
---

\```{.python .cb.nb jupyter_kernel=python3 show=code:verbatim+stdout:raw}
print("hello")
\```
Table: My Table

\begin{gather}
X_{1i} = a_0 + a_1 X_{2i} + \hat{v}_i \\
Y_i = b_0 + b_1 \hat{v}_i + e_i
\end{gather}

Am I doing something wrong?

Jupyter Kernel timeout Option

I'm creating some tables in codebraid and it takes a while, but after a minute, I get the error:

Jupyter kernel "python3" timed out during execution

I checked the code and I think it might have something to do with:

msg = jupyter_client.iopub_channel.get_msg(timeout=60)

Would it be possible to let the jupyter kernel timeout be an option set when running codebraid? I can open a pull request, but I'm not sure whether you would want it exposed in Converter or somewhere else?

lint embedded code

I currently have separated doc linted with markdown-lint and scripts linted with shellcheck. I would like to merge the 2 to avoid doc maintenance.

Is there a way to run shellcheck with codebraid to lint the embedded code and not break the execution afterward ?

Thanks.

Search path for Python executable on Windows

I'm using Python 3.8 in a virtual environment provided by Poetry running on Windows 10. I find that the Python executable called by Codeweave does not respect the Windows PATH environment variable. Instead of calling the Python executable of the currently activated virtual environment (that Codebraid itself is running in), it calls a Windows system Python. By default, this produces a message referring you to the Microsoft store, and this message appears in the output HTML!

I tracked the issue down to the calls to subprocess.run in _subproc_default. There is a known issue with subprocess:
https://bugs.python.org/issue15451

From this Stack Overflow answer I was able to fix the problem by inserting the following at the beginning of _subproc_default

args = [shutil.which(args[0])] + args[1:]

Thank you for Codebraid!

Pandoc Version Read Incorrectly

Pandoc version 2.10 is read as 2.1

$ codebraid pandoc --from markdown --to markdown notebook.md
Traceback (most recent call last):
  File "/home/removed/.local/bin/codebraid", line 8, in <module>
    sys.exit(main())
  File "/home/removed/.local/lib/python3.8/site-packages/codebraid/cmdline.py", line 62, in main
    args.func(args)
  File "/home/removed/.local/lib/python3.8/site-packages/codebraid/cmdline.py", line 80, in pandoc
    converter = converters.PandocConverter(paths=args.files,
  File "/home/removed/.local/lib/python3.8/site-packages/codebraid/converters/pandoc.py", line 569, in __init__
    raise RuntimeError('Pandoc at "{0}" is version {1}, but >= 2.4 is required'.format(pandoc_path, float(pandoc_version_match.group())))
RuntimeError: Pandoc at "pandoc" is version 2.1, but >= 2.4 is required
$ pandoc -v
pandoc 2.10.1
Compiled with pandoc-types 1.21, texmath 0.12.0.3, skylighting 0.8.5
Default user data directory: /home/removed/.local/share/pandoc or /home/removed/.pandoc
Copyright (C) 2006-2020 John MacFarlane
Web:  https://pandoc.org
This is free software; see the source for copying conditions.
There is no warranty, not even for merchantability or fitness
for a particular purpose.

Codebraid breaks on pandoc citations.

Minimal example:

[@test]

Fails with:

$ codebraid pandoc /tmp/test.md 
Traceback (most recent call last):
  File "/nix/store/n1nd5j5m583llfbbmqm379kmg98335zg-codebraid-0.4.0/bin/.codebraid-wrapped", line 9, in <module>
    sys.exit(main())
  File "/nix/store/n1nd5j5m583llfbbmqm379kmg98335zg-codebraid-0.4.0/lib/python3.7/site-packages/codebraid/cmdline.py", line 62, in main
    args.func(args)
  File "/nix/store/n1nd5j5m583llfbbmqm379kmg98335zg-codebraid-0.4.0/lib/python3.7/site-packages/codebraid/cmdline.py", line 85, in pandoc
    converter.code_braid()
  File "/nix/store/n1nd5j5m583llfbbmqm379kmg98335zg-codebraid-0.4.0/lib/python3.7/site-packages/codebraid/converters/base.py", line 1161, in code_braid
    self._extract_code_chunks()
  File "/nix/store/n1nd5j5m583llfbbmqm379kmg98335zg-codebraid-0.4.0/lib/python3.7/site-packages/codebraid/converters/pandoc.py", line 1146, in _extract_code_chunks
    self._load_and_process_initial_ast(source_string=source_string, single_source_name=source_name)
  File "/nix/store/n1nd5j5m583llfbbmqm379kmg98335zg-codebraid-0.4.0/lib/python3.7/site-packages/codebraid/converters/pandoc.py", line 1007, in _load_and_process_initial_ast
    node_type = node['t']
KeyError: 't'

Markdown-to-Markdown gives raw elements

This was discovered in looking into #25.

Input:

```{.python .cb.run}
print('''
|   Name    |  SST-2  |  MRPC  |
|-----------|---------|--------|
| accuracy  |  0.868  | 0.757  |
| buildtime | 781.831 | 50.946 |
''')
```

Convert -t markdown with Pandoc 2.9.2.1:

```{=markdown}
|   Name    |  SST-2  |  MRPC  |
|-----------|---------|--------|
| accuracy  |  0.868  | 0.757  |
| buildtime | 781.831 | 50.946 |
```

The ```{=markdown} shouldn't be there, so there is probably an incompatibility with something changed in a recent version of Pandoc.

Support for Altair plots in Jupyter mode

Hi. I hoped that I can display Altair plots in Jupyter mode just like we plot Matplotlib. Unfortunately, I can't get a working solution up to this moment.

For example, the code

 ```{.python .cb.nb jupyter_kernel=python3}
import altair as alt
alt.renderers.enable('notebook')
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
%matplotlib inline

df=DataFrame({'step':[0,1,2,3], 'value':[0,1,2,3]})
x=alt.Chart(df).mark_line().encode(x='step', y='value')
x.display() # Not sure, putting just `x` here produces the same result
```

outputs just

<vega.vegalite.VegaLite at 0x7fe448947fd0>

but not an image.

Could you please comment on what may be wrong and do we have a chance to make this work?

Note, I'm using current HEAD version pip install git+https://github.com/gpoore/codebraid@011464539bfb09b8611c8aef0d543532cea958bf

Custom executable / custom language

Hey,
Thanks for this project, seems to nearly fill exactly what I was looking for.

I am getting stuck on one thing - I'm writing shell code cells, but I'm wanting to use a custom executable/shell for these. For this example let's say I want to use /usr/bin/fish, but full disclosure, what I really want is to get codebraid to run its stuff in a container, by passing the executable podman run -it docker.io/ubuntu:21.10.

When passing executable= to the shell session block as per docs, I get an "executable not found" error:

```{.bash .cb-nb session=dock executable="podman run --name mine -v .:/demo -it ubuntu:21.10"}
set -e
cd /demo/demo
pwd
```
``` {.error .sysConfigError}
SYS CONFIG ERROR in "post.md" near line 88:
Could not find executable "podman run --name mine -v .:/demo -it ubuntu:21.10"
```

When passing executable= to the shell session block as a list because I'm guessing it might get send to subprocess.run, that block doesn't run and future blocks use bash directly.

```{.bash .cb-nb session=dock executable=["podman", "run", "--name", "mine", "-v" ".:/demo", "-it", "ubuntu:21.10"]}
set -e
cd /demo/demo
pwd
ls -l # does not run
```

```{.bash .cb-nb session=dock}
curl -sL https://nixos.org/nix/install | bash -s -- --no-daemon
pwd
ls -l # executes outside container
```

Is there some permutation like the above that's meant to work with shell blocks?

If not, is there a way I can set up a new language by writing the config file in my project, without needing to fork codebraid locally?

Simple answer to both might be "no", no worries if so :)

Thanks!

Markdown tables rendered incorrectly

The following code

```{.python .cb.run}
print('''
|   Name    |  SST-2  |  MRPC  |
|-----------|---------|--------|
| accuracy  |  0.868  | 0.757  |
| buildtime | 781.831 | 50.946 |
''')
```

produces correct output documents of html format (<table>...</table>) but for markdown documents the result is

  Name        SST-2     MRPC
  ----------- --------- --------
  accuracy    0.868     0.757
  buildtime   781.831   50.946

i.e. 1) Strange double-space at the start of every line and 2) no | characters mark table borders. As a result, Github doesn't parse such text as tables. Please, consider checking!

I run codebraid with teh following command:

codebraid pandoc \
  -f markdown -t markdown --no-cache --overwrite --standalone \
  --self-contained -o out.md inp.md.in

Retain language-specific syntax highlighting in conversions

Currently using

python{.python .cb.run show=code+stdout}
var = 'Hello from Python!'
print(var)

(ie syntax specific markdown) in a markdown file and executing it using codebraid with the '--to markdown' flag causes an error. Just using {.python .cb.run show=code+stdout} results in

{.python .numberLines startFrom="1"}
var = 'Hello from Python!'
print(var)

Would it be possible to implement a feature whereby language-specific syntax highlighting is preserved during execution?

Code restructuring and collaboration

@gpoore

I went through the code, please find below some suggestions. My goal is not to criticize at all the time and work that you have dedicated to the project. Codebraid is filling a very useful niche and am grateful for your efforts. I think a "novice" friendlier code base might attract more people to contribute. Please let me know what you think.

  1. Some functions are very long e.g. the function _run. It would helpful to have more modules and smaller functions, cf. Unix philosophy
  2. Related to above, it seems that a lot effort is spent to read and process the cell configuration. It looks like an DSL, maybe one can have that in a separate module
  3. It would be helpful to use type hinting
  4. pandoc json/AST might not be ideal to process. Maybe one can use another parser/format (marked, cmark have nicer ASTs) to pre-process and execute the code
  5. It would be helpful to remove pandoc from the code base: codebraid would only convert from input-markdown to executed-markdown
  6. Maybe consider to support just jupyter kernels to leverage their capabilities. Don't know the implications in terms of performance

Error when using header-includes in front matter

I get an error when I try to convert from markdown to pdf with latex commands defined in header-includes in font matter.

File test.md

---
header-includes: |
    \newcommand{\Ker}{\mathrm{Ker}}
---

# Title

$\Ker$

Command run

codebraid pandoc --from markdown --to pdf test.md -o test.pdf

Error

! LaTeX Error: Command \Ker already defined.

I don't get any error if I try to convert from markdown to markdown with codebraid or when I convert from markdown to pdf directly with pandoc :

pandoc --from markdown --to pdf test.md -o test.pdf

Working with multiple source files w/ .cb.nb

I recently experienced an issue with working with multiple source files that would then be combined into one larger document, e.g. multiple files representing book chapters. If the files are set up to run individually with the notebook executor (i.e. .cb.nb) then execution will fail silently when trying to execute and combine the files into a single document.

Minimal reproducing example

Say you have two source files ch1.md and ch2.md that you want to execute+compile into book.pdf:

Contents of ch1.md:

# Ch. 1 - Uniform distribution

A histogram of uniformly-distributed random numbers.

```{.python .cb.nb jupyter_kernel=python3}
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng()
plt.hist(rng.uniform(size=1000))
```

Contents of ch2.md

# Ch 2. - Normal Distribution

A histogram of normally-distributed random numbers.

```{.python .cb.nb jupyter_kernel=python3}
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng()
plt.hist(rng.standard_normal(size=1000))
```

Executing/converting the files individually works as expected:

$ codebraid pandoc --from markdown --to pdf ch1.md --standalone -o book.pdf

However, if you try to compile both documents into a single book, neither document is executed, though no warning or error are given on the command line:

$ codebraid pandoc --from markdown --to pdf ch1.md ch2.md --standalone -o book.pdf

In the latter case, if you look at the output book.pdf you will find an error printed:

SOURCE ERROR in "ch2.md" near line 6:
Some options are only valid for the first code chunk in a session: "jupyter_kernel"

IMO it would be helpful to the user if this error were raised at the command line rather than (or in addition to being) embedded in the output document. In my actual use-case with much larger chapters, it was a very long time before I noticed this in the output book.

The error in book.pdf seems to suggest that the problem lies with the "special" metadata jupyter_kernel, which is only supposed to be supplied in the first code cell. This suggests that an author would have to modify source file metadata if they wanted to switch between building individual chapters and the entire book. I hadn't noticed this mentioned in the docs before - if it's not there, then it would be an improvement if this behavior were documented.

Perhaps this can be avoided if .cb.run is used instead of .cb.nb? Is there a preferred way of using codebraid to have flexible outputs w/ multiple source files?

Executing python code within $...$? [enhancement: add cb.sub command]

In knitr, one could have something like this

```{r include = FALSE}
var = 123
```

Note that $\sqrt{`r var`} =`r sqrt(var)`$.

The last line will get rendered to html as
Note that \(\sqrt{123} = 11.0905365\).

Does CodeBraid allow executing the python code within $...$ to accomplish the same thing? My initial experiment suggests that it doesn't. Any help is greatly appreciated.

[feature request] convert string, and store the result in a string variant

In my case, I convert a markdown file to HTML which then is rendered with QT. The main code is

webView = QWebEngineView()
webView.setHtml(pageSource)

as you may have noticed, the contain pageSource is used here. If an HTML file is used, an extra step has to be performed

pageSource = open('page.html').read()

So what I suggest is

pageSource = codebraid.convert('web.cbmd', from='markdown', to='markdown',  ignorePandoc=True)

and in this case, I think pandoc is not necessary, so I set ignorePandoc=True

Thanks

--citeproc Pandoc option

Is there a reason that --citeproc is omitted from PANDOC_OPTIONS? I got it working along with --bibliography by adding

('-C', '--citeproc'): 0

to PANDOC_OPTIONS.

Proposal for adding developer oriented Makefile example

My dream is to use codebraid to write README.md files for all my
projects.

To achieve this I have come up with a Makefile to convert all .cbmd
files in a repository. This makes it much easier to get up and running
with a more automated workflow. I feel it is a must to convince all my
programmer friends that using Codebraid for this purpose is awesome. I
would love to see literate programming reach a wider audience.

I have been exploring the possibilites in this repo if you are curious.

Would you be interested in a PR with an example for this workflow?
Perhaps as a subfolder in the examples directory.

Makefile:

CODEBRAID_DOCS := $(shell find . -name '*.cbmd')
MARKDOWN_DOCS = $(CODEBRAID_DOCS:.cbmd=.md)

.PHONY: cbmd watch

# Must cd into the target file directory so Pandoc and Codebraid are
# able to use relative paths as one would expect
%.md : %.cbmd
	cd $(@D); codebraid pandoc --from markdown --to gfm --filter=mermaid-filter --output $(notdir $@) --overwrite $(notdir $^)

cbmd : $(MARKDOWN_DOCS)

watch :
	find . -name '*.cbmd' | entr make cbmd

Integration with VS Code using a VS Code extension

Would it be possible to have a VS code extension that runs codebraid? I see there's a similar open issue with Spyder integration (#17). The main motivation would be to make it easier and more user-friendly to run codebraid (in my experience, not everyone is comfortable using the command line).

Failure when specifying local MathJax

I'm trying to use codebraid with a standalone MathJax installation. Currently I can run Pandoc without any errors:

pandoc --mathjax=$MJPATH -t revealjs -s -i index.md -o docs/index.html

where MJPATH is the path to MathJax.js in a MathJax@2 installation. But if I try to run essentially the same line with the same markdown file through codebraid:

codebraid pandoc --mathjax=$MJPATH -t revealjs -s -i index.md -o docs/index.html

I get this error:

Traceback (most recent call last):
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/package-dev/lib/python3.8/site-packages/codebraid/converters/pandoc.py", line 773, in _run_pandoc
    proc = subprocess.run(cmd_list,
  File "/Users/j260381/.pyenv/versions/3.8.7/lib/python3.8/subprocess.py", line 512, in run
    raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['pandoc', '--from', 'json', '--to', 'revealjs', '--standalone', '--preserve-tabs', '--output', 'docs/index.html', '--variable', 'theme:simple', '--incremental', '--css', 'style.css', '--mathjax', '/Users/j260381/Projects/Training/pkg-dev-week1/node_modules/mathjax/MathJax.js']' returned non-zero exit status 64.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/j260381/.pyenv/versions/package-dev/bin/codebraid", line 8, in <module>
    sys.exit(main())
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/package-dev/lib/python3.8/site-packages/codebraid/cmdline.py", line 107, in main
    args.func(args)
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/package-dev/lib/python3.8/site-packages/codebraid/cmdline.py", line 159, in pandoc
    converter.convert(to_format=args.to_format, standalone=args.standalone,
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/package-dev/lib/python3.8/site-packages/codebraid/converters/pandoc.py", line 1244, in convert
    converted_bytes, stderr_bytes = self._run_pandoc(input=json.dumps(self._final_ast),
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/package-dev/lib/python3.8/site-packages/codebraid/converters/pandoc.py", line 788, in _run_pandoc
    raise PandocError(message)
codebraid.converters.pandoc.PandocError: Failed to run Pandoc:
JSON parse error: Error in $: Failed reading: not a valid json value at '*'

It doesn't seem to make a difference what's actually in the markdown file. Using --mathjax without a path works just fine, though, so that makes it a somewhat academic exercise (as grabbing it from the CDN works well enough for my use case).

I'm using:

Python 3.8.7
macOS 10.15.7
codebraid 0.5.0
MathJax 2.7.9
Pandoc 2.13

.cb.run behaves inconsistently between languages in respect to implicit printing.

According to the current state oif the documentation, .cb.run should give "raw" output. This does not happen with "implicit" output, i. e. the result of an evaluation without explicit printing: in this case, most of the interpreters print the result to their stanrd output.

Nothing is printed when an inline expression in Python, Sage and Julia ; however, both R and bash give their raw output. When exported to markdown, the following code :

Language `run`                       `nb`                        `expr`                       `run`+print
------- --------------------------- ---------------------       -----------------------      ------------------------------------
Python   `1+2`{.python .cb.run}      `1+2`{.python .cb.nb}       `1+2`{.python .cb.expr}      `print(1+2)`{.python .cb.run}
Sage     `1+2`{.sage .cb.run}        `1+2`{.sage .cb.nb}         `1+2`{.sage .cb.expr}        `print(1+2)`{.sage .cb.run}
Julia    `1+2`{.julia .cb.run}       `1+2`{.julia .cb.nb}        `1+2`{.julia .cb.expr}       `print(1+2)`{.julia .cb.run}
R        `1+2`{.R .cb.run}           `1+2`{.R .cb.nb}            `1+2`{.R .cb.expr}           `print(1+2)`{.R .cb.run}
bash     `expr 1 + 2`{.bash .cb.run} `expr 1 + 2`{.bash .cb.nb}` `expr 1 + 2`{.bash .cb.expr} `echo $(expr 1 + 2)`{.bash .cb.run}

results in

  Language     `run`        `nb`       `expr`   `run`+print
  ---------- --------- -------------- -------- -------------
  Python                 `3`{.expr}      3           3
  Sage                   `3`{.expr}      3           3
  Julia                  `3`{.expr}      3           3
  R           \[1\] 3    `3`{.expr}      3        \[1\] 3
  bash           3      `3`{.expr}\`     3           3

And the export to PDF via latex gives "teletype" printing in the nb column and normal (i. e. roman) printing in the other columns.

Similarly, the following code:

## Block syntax

### Python

```{.python .cb.run}
1+2
```
### Sage

```{.sage .cb.run}
1+2
```

### Julia

```{.julia .cb.run}
1+2
```

### R

```{.R .cb.run}
1+2
```

### Bash

```{.bash .cb.run}
expr 1 + 2
```

Gives the following result:

Block syntax
------------

### Python

### Sage

### Julia

### R

\[1\] 3

### Bash

3

In both cases (inline and block), Python's, Sage's and Julia's implicit printings do not get in the output, whereas bash's and R's do.

This inconsistency should be fixed or, to the least, documented.

The same problem exists for the implicit printing of figures created by R or Sage. This should at least be documented...

can't run codebraid with new version of jupyter-client

I have the following markdown:

% example
% Jay Cunningham
% 22 April 2021

# What's happening?

```{.python .cb.nb jupyter_kernel=python3 example=false session=foo}
print("hello, world")

I'm running the following command to create slides:

codebraid pandoc -f markdown example.md -t revealjs -s -i -o example.html

If I install jupyter-client==6.1.12, it works fine. If I upgrade it to the most-current jupyter-client==6.2.0, I (usually?) get the following error:

Traceback (most recent call last):
  File "/Users/j260381/.pyenv/versions/kayday-deep-dive/bin/codebraid", line 8, in <module>
    sys.exit(main())
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/kayday-deep-dive/lib/python3.8/site-packages/codebraid/cmdline.py", line 107, in main
    args.func(args)
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/kayday-deep-dive/lib/python3.8/site-packages/codebraid/cmdline.py", line 153, in pandoc
    converter.code_braid()
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/kayday-deep-dive/lib/python3.8/site-packages/codebraid/converters/base.py", line 1199, in code_braid
    self._process_code_chunks()
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/kayday-deep-dive/lib/python3.8/site-packages/codebraid/converters/base.py", line 1213, in _process_code_chunks
    cp.process()
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/kayday-deep-dive/lib/python3.8/site-packages/codebraid/codeprocessors/base.py", line 603, in process
    self._run_jupyter(session)
  File "/Users/j260381/.pyenv/versions/3.8.7/envs/kayday-deep-dive/lib/python3.8/site-packages/codebraid/codeprocessors/base.py", line 1384, in _run_jupyter
    if msg['parent_header'].get('msg_id') != cc_jupyter_id:
TypeError: 'coroutine' object is not subscriptable
sys:1: RuntimeWarning: coroutine 'ZMQSocketChannel.get_msg' was never awaited

It sometimes works the first time I run codebraid after installing 6.2.0, but it always fails the second or further times I run it after making a change to the markdown.

Errors with pandoc 2.11

I'm getting errors with pandoc 2.11. Codebraid complains about this version with the error message that pandoc version >= 2.4 is required...

cannot loop through arrays in bash

When I try to run the below code as a block in codebraid with options .bash .cb.run I get an error that appears to be related to formatting. However I cannot figure out what the issue is.

array=( one two three )
for i in "${array[@]}"
do
	echo ${i}
done

Error:

codebraid pandoc --from markdown --to markdown test_for.md
Traceback (most recent call last):
  File "/Users/aguang/miniconda3/bin/codebraid", line 10, in <module>
    sys.exit(main())
  File "/Users/aguang/miniconda3/lib/python3.6/site-packages/codebraid/cmdline.py", line 62, in main
    args.func(args)
  File "/Users/aguang/miniconda3/lib/python3.6/site-packages/codebraid/cmdline.py", line 85, in pandoc
    converter.code_braid()
  File "/Users/aguang/miniconda3/lib/python3.6/site-packages/codebraid/converters/base.py", line 1161, in code_braid
    self._extract_code_chunks()
  File "/Users/aguang/miniconda3/lib/python3.6/site-packages/codebraid/converters/pandoc.py", line 1146, in _extract_code_chunks
    self._load_and_process_initial_ast(source_string=source_string, single_source_name=source_name)
  File "/Users/aguang/miniconda3/lib/python3.6/site-packages/codebraid/converters/pandoc.py", line 1070, in _load_and_process_initial_ast
    source_name, line, line_number = next(source_name_line_and_number_iter)
StopIteration

Make StopIteration Errors more informative

Oftentimes when running codebraid, I get a StopIteration error and it is difficult to tell where this error comes from. Is there a way to make the StopIteration error more informative, like giving the snippet of text that causes the issue or the line number?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.