CodeToMarkdown.py - a module to translate source code to Markdown¶
The API lists two functions which convert source code into Markdown. It relies on Implementation to classify the source as code or comment, then _generate_markdown to convert this to Markdown. To convert this output to HTML using Markdown or CommonMark:
1from CodeChat.CodeToMarkdown import code_to_markdown_string
2import markdown
3import CommonMark
4
5# Translate code to Markdown.
6md_str = code_to_markdown_string("# Testing, 1, 2, 3.")
7# Render it, using two different Markdown implementations.
8print(markdown.markdown(s))
9print(CommonMark.commonmark(s))
Imports¶
These are listed in the order prescribed by PEP 8.
Standard library¶
Third-party imports¶
None.
Local application imports¶
API¶
The following routines provide easy access to the core functionality of this module.
code_to_markdown_string¶
This function converts a string containing source code to Markdown, preserving all indentations of both source code and comments. To do so, the comment characters are stripped from CodeChat-formatted comments and all code is placed inside fenced code blocks.
code_str: the code to translate to markdown.
See options.
Use a StringIO to capture writes into a string.
Include a header containing some CodeChat style.
code_to_markdown_file¶
Convert a source file to a Markdown file.
Path to a source code file to process.
Path to a destination Markdown file to create. It will be overwritten if it
already exists. If not specified, it is source_path.md
.
Encoding to use for the input file. The default of None detects the encoding of the input file.
Encoding to use for the output file.
See options.
Provide a default rst_path
.
If not already present, provide the filename of the source to help in identifying a lexer.
Converting classified code to markdown¶
The fence used for a fenced code block. We hope the code doesn’t contain this.
_generate_markdown¶
Generate markdown from the classified code. To do this, create a state machine,
where current_type defines the state. When the state changes, exit the
previous state (output a closing fence or closing </div>
, then enter the
new state (output a fenced code block or an opening <div style=...>
.
An iterable of (type, string) pairs, one per line.
A file-like output to which the markdown text is written.
Keep track of the current type. Begin with neither comment nor code.
Keep track of the current line number.
See if there’s a change in state.
Exit the current state.
Enter the new state.
Code state: emit the beginning of a fenced block.
Comment state: emit an opening indent for non-zero indents.
Add an indent if needed.
Update the state.
When done, exit the last state.
_exit_state¶
Output text produced when exiting a state. Supports _generate_markdown.
The type (classification) of the last line.
See out_file.
Code state: emit an ending fence.
Comment state: emit a closing indent.
Initial state or non-indented comment. Nothing needed.