rins_markdown_parser 0.1.2

Simple markdown parser written on Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
# Simple Markdown Parser

> [!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](https://crates.io/crates/rins_markdown_parser)
**Github**: [click here](https://github.com/r-rin/rins-markdown-parser)

---

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.

### Features
* Headers - Parses Markdown headers (`#`, `##`, `###`, etc.) into structured nodes in the AST.
* Emphasis - Recognizes *italic* and **bold** text, along with other emphasis markers.
* Links - Parses inline links (`[text](url)`) and reference links.
* Code Blocks - Detects inline code (`code`) and fenced code blocks.
* Blockquotes - Parses quoted text (`> Quote`) as distinct elements.
* Images - Recognizes inline images (`![alt text](url)`).
* Horizontal Rule - Detects horizontal rules `---` in your file.

### Plans
* Lists - Support for both ordered (`1. Item`) and unordered (`- Item or * Item`) lists.
* Tables - Recognition of tables with rows and columns.
* Footnotes - Support for footnotes, allowing references in the text and corresponding notes at the bottom.
* Task List - Parsing of task lists, with checkboxes (e.g., `- [ ] Task or - [x] Done`).
* Emoji - Recognition of shortcodes for emojis (e.g., `:smile:`) and converting them to the appropriate Unicode or image representation.
* Highlighted Text - Support for highlighted text (e.g., using `==highlighted==`).
* Subscript - Parsing of subscript text (e.g., `H~2~O`).
* Superscript - Parsing of superscript text (e.g., `X^2^`).
* Definition Lists - Parsing of definition lists.
* Markdown extensions - Support for extended Markdown features like GitHub-flavored Markdown (GFM), including task lists, strikethrough, and more.

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.

# Grammar

## 1. General Structure

```pest
markdown = { SOI ~ (block ~ empty_line*)* ~ EOI }

block = _{
  heading
  | quote
  | code_block
  | horizontal_rule
  | paragraph
}
```

- The file starts with the **Start of Input** (`SOI`) and ends with the **End of Input** (`EOI`).
- Markdown documents are composed of **blocks** separated by zero or more **empty lines**.

## 2. Block Elements
### 2.1 Headings

```pest
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)+
}
```

- Represented using one or more `#` symbols at the start of the line.
- One `#` corresponds to Heading 1, two `##` to Heading 2, and three `###` to Heading 3.
- Must be followed by a space and a single line of text.
- Example:
```md
# Heading 1
## Heading 2
### Heading 3
```

### 2.2 Horizontal Rules

```pest
horizontal_rule = {
    ("---"|"***"|"–––") ~ ws* ~ (NEWLINE | EOI)
}    
```

- Created with three or more of the following symbols:
  - Dashes (`---`)
  - Asterisks (`***`)
  - En-dashes (`–––`)
- Can optionally include trailing whitespace and must end with a newline.
- Example: 
```md
---
***
–––
```

### 2.3 Blockquotes

```pest
quote =  {
    ">" ~ paragraph
}
```

- Indicated by a `>` character followed by a paragraph.
- Example:
```md
> This is a quote. Hello!
```

### 2.4 Code Blocks

```pest
code_block = {
    "```" ~ (code_lang ~ ws* ~ NEWLINE)? ~ code_content ~ NEWLINE? ~ "```" ~ NEWLINE?
}

code_lang = {
    ws* ~ ('a'..'z' | 'A'..'Z')+
}

code_content = {
    (!(NEWLINE? ~ "```") ~ ANY)+
}
```

- Start and end with three backticks (` ``` `).
- May optionally include a programming language name after the opening backticks.
- Example:
```md
    ```py
        print("Hello World!")
    ```
```

### 2.5 Paragraphs

```pest
paragraph = {
	paragraph_line+ 
}

paragraph_line = {
	text+ ~ paragraph_break?
}

paragraph_break = _{
    NEWLINE
}

text = _{
    plain_text
  | escaped
  | styled_text
}
```

- Consist of one or more paragraph lines.
- Paragraphs are separated by an empty line or a paragraph break (newline).

## 3. Inline Elements

### 3.1 Text Styles

```pest
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)+
}
```

- **Bold:** Enclosed in double asterisks (`**`).
- **Italic:** Enclosed in single asterisks (`*`) or underscores (`_`).
- **Underline:** Enclosed in double underscores (`__`).
- **Strikethrough:** Enclosed in double tildes (`~~`).
- **Content** contains text which those elements are styling, used as plain text within styled elements.

### 3.2 Links

```pest
inline_link = {
	"[" ~ link_text ~ "](" ~ url ~ ")"
}

link_text = {
	(!"]" ~ ANY)+
}

url = {
	(!")" ~ ANY)+
}
```

- Formatted as `[link text](url)`.

### 3.3 Images

```pest
inline_image = {
	"![" ~ alt_text ~ "](" ~ url ~ ")"
}

alt_text = {
	(!"]" ~ ANY)+
}

url = {
	(!")" ~ ANY)+
}
```

- Formatted as `![alt text](url)`.

### 3.4 Escaped Characters

```pest
escaped = {
    "\\" ~ (!ws ~ char)
}

char = {
	ANY
}
```

- Special characters can be escaped using a backslash (`\`).

## 4. Miscellaneous Rules

### 4.1 Plain Text

```pest
plain_text = @{
    !exclude_block_elems ~ (!exclude_styles ~ ANY)+
}
```

- Any text not enclosed by styled elements or part of block elements.

### 4.2 Empty Lines

```pest
empty_line = {
	NEWLINE
}
```

- Represented by a single newline (`\n`).

> [!NOTE]
> More additional rules and their description can be found in the `src/grammar.pest`!

# Installation

### Using as a Crate

You can add this project as a dependency to your Rust project by fetching it from [crates.io](https://crates.io).

1. Open the folder of your desired project in a terminal.
2. Use `cargo add` to add the crate to your project's dependencies:
```bash
$ cargo add rins_markdown_parser
```
3. Import crate in any `.rs` file inside your project:
```rust
// any .rs file, e.g. main.rs
use rins_markdown_parser::{Grammar, parse_to_console} 
```

### Using as a Command-Line Tool

Alternatively, you can use this project as a standalone command-line interface (CLI). To do so:

1. Clone the repository:
```bash
$ git clone https://github.com/r-rin/rins-markdown-parser.git
$ cd rins-markdown-parser
```

2. Build the project:
```bash
$ cargo build --release
```
The compiled binary will be located in the target/release directory.

3. Run the CLI to parse a Markdown file:
```bash
$ ./target/release/rins-markdown-parser help
```

or use **make**

```bash
$ make run args="..."
```

# Usage
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.

### 1. Parse Markdown to HTML (String Input)

You can use the `str_to_html` function to parse Markdown text from a string and convert it to HTML.

```rust
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:**
```html
<h1>Hello, World!</h1>
<p>This is <strong>bold</strong> and <em>italic</em>.</p>
```

### 2. Parse Markdown File to HTML File

Use the `md_to_html_file function` to convert a Markdown file into an HTML file.

```rust
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(())
}
```

### 3. Parse Markdown and Print HTML to Console

The `parse_to_console` function allows you to parse Markdown text and print the resulting HTML directly to the console.

```rust
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);
    }
}
```

### 4. Customize Parsing Behavior with Specific Rules

If you need to parse only specific parts of the Markdown using custom rules defined in `grammar.pest`, use the `parse_by_rule` function.

```rust
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(())
}
```

# Command Line Interface (CLI)

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.

## Installation

If you have cloned the project, build it using Cargo:

```bash
$ 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`.

## Commands Overview

To see the available commands, use the `--help` option or `help` subcommand:

```bash
$ rins_markdown_parser --help
```
**Output:**
```text
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
```

### Commands

1. `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**
1. Parse a Markdown file and save the output to an HTML file:
```bash
$ rins_markdown_parser parse --in example.md --out example.html
```

2. Parse Markdown text directly from the CLI:
```bash
$ rins_markdown_parser parse --text "# Hello World\nThis is **Markdown**."
```

2. `credits`

Displays project information and credits.

```bash
$ rins_markdown_parser credits
```

3. `help [COMMAND]`

Displays helpful information about available subcommands and their arguments.

---

### License and Usage

This project is intended solely for personal and educational use. It was never intented to be used at production. Use with caution.

### Credits

- Author: [r-rin]https://github.com/r-rin
- This parser was developed as part of the Rust Programming Language course at NaUKMA with the support of the Ukrainian Rust community.