Crates.io | rins_markdown_parser |
lib.rs | rins_markdown_parser |
version | 0.1.2 |
source | src |
created_at | 2024-11-21 00:37:33.315499 |
updated_at | 2024-11-21 01:04:57.77457 |
description | Simple markdown parser written on Rust |
homepage | https://github.com/r-rin/rins-markdown-parser |
repository | https://github.com/r-rin/rins-markdown-parser |
max_upload_size | |
id | 1455484 |
size | 73,275 |
[!IMPORTANT] This parser uses not the most ideal grammar, so it is recommended to avoid using any complex or ambiguous combinations of styles, etc. For example, if you use bold and italic styles at the same time, then it is recommended to use underscores (
_italic_
) for italic styling.
Crates.io: click here Github: click here
This is a Rust library that parses Markdown text, covering essential Markdown syntax elements such as headers, lists, emphasis, links, code blocks, and more. It parses Markdown into an Abstract Syntax Tree (AST), making it easier to manipulate, transform, or render Markdown content in various formats.
#
, ##
, ###
, etc.) into structured nodes in the AST.[text](url)
) and reference links.code
) and fenced code blocks.> Quote
) as distinct elements.![alt text](url)
).---
in your file.1. Item
) and unordered (- Item or * Item
) lists.- [ ] Task or - [x] Done
).:smile:
) and converting them to the appropriate Unicode or image representation.==highlighted==
).H~2~O
).X^2^
).The parser processes Markdown into an Abstract Syntax Tree, which can be used for rendering Markdown as HTML, analyzing document structure, or exporting to other formats or editing a markdown file.
markdown = { SOI ~ (block ~ empty_line*)* ~ EOI }
block = _{
heading
| quote
| code_block
| horizontal_rule
| paragraph
}
SOI
) and ends with the End of Input (EOI
).heading = _{
heading1
| heading2
| heading3
}
heading1 = {
"#" ~ ws ~ single_line_text ~ NEWLINE?
}
heading2 = {
"##" ~ ws ~ single_line_text ~ NEWLINE?
}
heading3 = {
"###" ~ ws ~ single_line_text ~ NEWLINE?
}
single_line_text = {
(!NEWLINE ~ ANY)+
}
#
symbols at the start of the line.#
corresponds to Heading 1, two ##
to Heading 2, and three ###
to Heading 3.# Heading 1
## Heading 2
### Heading 3
horizontal_rule = {
("---"|"***"|"–––") ~ ws* ~ (NEWLINE | EOI)
}
---
)***
)–––
)---
***
–––
quote = {
">" ~ paragraph
}
>
character followed by a paragraph.> This is a quote. Hello!
code_block = {
"```" ~ (code_lang ~ ws* ~ NEWLINE)? ~ code_content ~ NEWLINE? ~ "```" ~ NEWLINE?
}
code_lang = {
ws* ~ ('a'..'z' | 'A'..'Z')+
}
code_content = {
(!(NEWLINE? ~ "```") ~ ANY)+
}
```
). ```py
print("Hello World!")
```
paragraph = {
paragraph_line+
}
paragraph_line = {
text+ ~ paragraph_break?
}
paragraph_break = _{
NEWLINE
}
text = _{
plain_text
| escaped
| styled_text
}
styled_text = _{
escaped* ~ (bold | underline | italic | strikethrough | inline_image | inline_link | content) ~ escaped*
}
strikethrough = {
"~~" ~ (styled_text)+ ~ "~~"
}
underline = {
"__" ~ (styled_text)+ ~ "__"
}
bold = {
"**" ~ (styled_text)+ ~ "**"
}
italic = {
("*" ~ (styled_text)+ ~ "*")
| ("_" ~ (styled_text)+ ~ "_")
}
content = @{
(!(exclude_styles | exclude_block_elems) ~ ANY)+
}
**
).*
) or underscores (_
).__
).~~
).inline_link = {
"[" ~ link_text ~ "](" ~ url ~ ")"
}
link_text = {
(!"]" ~ ANY)+
}
url = {
(!")" ~ ANY)+
}
[link text](url)
.inline_image = {
"![" ~ alt_text ~ "](" ~ url ~ ")"
}
alt_text = {
(!"]" ~ ANY)+
}
url = {
(!")" ~ ANY)+
}
![alt text](url)
.escaped = {
"\\" ~ (!ws ~ char)
}
char = {
ANY
}
\
).plain_text = @{
!exclude_block_elems ~ (!exclude_styles ~ ANY)+
}
empty_line = {
NEWLINE
}
\n
).[!NOTE] More additional rules and their description can be found in the
src/grammar.pest
!
You can add this project as a dependency to your Rust project by fetching it from crates.io.
cargo add
to add the crate to your project's dependencies:$ cargo add rins_markdown_parser
.rs
file inside your project:// any .rs file, e.g. main.rs
use rins_markdown_parser::{Grammar, parse_to_console}
Alternatively, you can use this project as a standalone command-line interface (CLI). To do so:
$ git clone https://github.com/r-rin/rins-markdown-parser.git
$ cd rins-markdown-parser
$ cargo build --release
The compiled binary will be located in the target/release directory.
$ ./target/release/rins-markdown-parser help
or use make
$ make run args="..."
Crate provides various utilities for parsing Markdown text and converting it into HTML. Below are examples and explanations of how to use the provided functions.
You can use the str_to_html
function to parse Markdown text from a string and convert it to HTML.
use rins_markdown_parser::{str_to_html, ErrorParse};
fn main() -> Result<(), ErrorParse> {
let markdown_text = "# Hello, World!\nThis is **bold** and *italic*.";
let html_lines = str_to_html(markdown_text)?;
for line in html_lines {
println!("{}", line);
}
Ok(())
}
Output:
<h1>Hello, World!</h1>
<p>This is <strong>bold</strong> and <em>italic</em>.</p>
Use the md_to_html_file function
to convert a Markdown file into an HTML file.
use rins_markdown_parser::{md_to_html_file, ErrorParse};
use std::path::Path;
fn main() -> Result<(), ErrorParse> {
let markdown_path = Path::new("example.md");
let html_path = Path::new("example.html");
md_to_html_file(markdown_path, html_path)?;
println!("Markdown converted to HTML successfully!");
Ok(())
}
The parse_to_console
function allows you to parse Markdown text and print the resulting HTML directly to the console.
use rins_markdown_parser::parse_to_console;
fn main() {
let markdown_text = r#"
# Welcome
This is **\*bold _bold and italic_** text!
"#;
if let Err(err) = parse_to_console(markdown_text) {
println!("Error: {}", err);
}
}
If you need to parse only specific parts of the Markdown using custom rules defined in grammar.pest
, use the parse_by_rule
function.
use rins_markdown_parser::{parse_by_rule, Grammar, Rule, ErrorParse};
fn main() -> Result<(), ErrorParse> {
let markdown_text = "## Subheading\nSome text here.";
let pairs = parse_by_rule(Rule::heading2, markdown_text)?;
for pair in pairs {
println!("Parsed pair: {:?}", pair);
}
Ok(())
}
The rins_markdown_parser
provides a Command Line Interface (CLI) to interact with the markdown parser. You can use it to parse markdown files or text into HTML or view project credits.
If you have cloned the project, build it using Cargo:
$ cargo build --release
This will create an executable in the target/release
directory. Alternatively, if you installed it as a binary crate, you can directly use rins_markdown_parser
.
To see the available commands, use the --help
option or help
subcommand:
$ rins_markdown_parser --help
Output:
rins_markdown_parser vX.X.X
Allows to interact with markdown parser via a Command Line Interface.
Usage: rins_markdown_parser [COMMAND]
Commands:
parse Parses provided markdown text and returns it in html format
credits Displays credits and project information
help Print this message or the help of the given subcommand(s)
Options:
-h, --help Print help
-V, --version Print version
parse
The parse
command is used to convert Markdown text to HTML. It accepts input either from a file or directly as text.
Options
-I, --in <input_file>
Specifies the location of the input markdown file.
-O, --out <output_file>
Specifies the location where the HTML output will be saved. If not provided, the result is printed to the console.
-t, --text <markdown_text>
Accepts Markdown text directly from the CLI.
[!NOTE] This option conflicts with --in and --out.
Examples
$ rins_markdown_parser parse --in example.md --out example.html
$ rins_markdown_parser parse --text "# Hello World\nThis is **Markdown**."
credits
Displays project information and credits.
$ rins_markdown_parser credits
help [COMMAND]
Displays helpful information about available subcommands and their arguments.
This project is intended solely for personal and educational use. It was never intented to be used at production. Use with caution.