GitHub
· Extracted in 2148 ms
✨ Add `--enable-tables` to the CLI, and fix interactive-mode line joi... · executablebooks/markdown-it-py@c02f6b1
Source: https://github.com/executablebooks/markdown-it-py/commit/c02f6b1fcd6af070f0fa82b5758f5b36e3e814ee
Repository navigation
Commit c02f6b1
Browse files
chrisjsewell
and
jf nz
authored
✨ Add --enable-tables to the CLI, and fix interactive-mode line joining ( #425 )
## Summary
Supersedes #422 by @user01010111 , whose fork does not allow maintainer
pushes; their commit is carried here verbatim with authorship preserved
(thank you!). Closes #352 and closes #172 .
- Adds `--enable-tables` to the `markdown-it` CLI for file, stdin and
interactive input, by threading one `MarkdownIt` instance through every
route (each function keeps an `md=None` default, so existing callers are
unaffected).
- Also fixes the interactive mode's line joining, the root cause of #172
(five years old): each input line already ends in `"\n"`, so the old
`"\n".join(contents)` doubled every newline, split every line into its
own paragraph and broke hard line breaks. Now `"".join`. This change was
in #422 but not called out there; this PR adds a changelog line and a
regression test for it.
## Commits
1. `✨ NEW: Add --enable-tables to the CLI` -- the contributor's commit,
unchanged.
2. `🐛 FIX: Note and test interactive-mode line joining fix ( #172 )` --
changelog entries and `test_interactive_hard_line_break`, which drives
`interactive()` with patched `input` and asserts `foo\` + `bar` renders
as one paragraph with `<br />`.
## Verification
- 1000 tests pass (+7 over master), all pre-commit hooks pass under the
new ruff 0.16 / mypy 2.3 pins.
- Local docs build adds no warnings over master.
- Smoke-checked: `--help` matches the README block, `--enable-tables
--stdin` renders a `<table>`, and without the flag the same input stays
a paragraph.
---------
Co-authored-by: jf nz <talon_usable_9k@icloud.com>
1 parent d9b0526 commit c02f6b1
4 files changed
Lines changed: 84 additions & 17 deletions
File tree
Lines changed: 2 additions & 0 deletions
| Original file line number | Diff line number | Diff line change |
@@ -2,6 +2,8 @@
|
2 | 2 |
|
3 | 3 | ## Unreleased
|
4 | 4 |
|
| 5 | +* ✨ Add `--enable-tables` to the CLI for file, standard input and interactive parsing in [#422](https://github.com/executablebooks/markdown-it-py/pull/422)
|
| 6 | +* 🐛 Fix CLI interactive mode joining input lines with an extra newline, which split every line into its own paragraph and broke hard line breaks, in [#172](https://github.com/executablebooks/markdown-it-py/issues/172)
|
5 | 7 | * 📚 Document the Python renderer constructor contract.
|
6 | 8 |
|
7 | 9 | ## 4.2.0 - 2026-05-07
|
|
Lines changed: 16 additions & 6 deletions
| Original file line number | Diff line number | Diff line change |
@@ -101,17 +101,18 @@ Render markdown to HTML with markdown-it-py from the
|
101 | 101 | command-line:
|
102 | 102 |
|
103 | 103 | ```console
|
104 | | -usage: markdown-it [-h] [-v] [--stdin|filenames [filenames ...]]
|
| 104 | +usage: markdown-it [-h] [-v] [--stdin] [--enable-tables] [filenames ...]
|
105 | 105 |
|
106 | 106 | Parse one or more markdown files, convert each to HTML, and print to stdout
|
107 | 107 |
|
108 | 108 | positional arguments:
|
109 | | - --stdin read source Markdown file from standard input
|
110 | | - filenames specify an optional list of files to convert
|
| 109 | + filenames specify an optional list of files to convert
|
111 | 110 |
|
112 | | -optional arguments:
|
113 | | - -h, --help show this help message and exit
|
114 | | - -v, --version show program's version number and exit
|
| 111 | +options:
|
| 112 | + -h, --help show this help message and exit
|
| 113 | + -v, --version show program's version number and exit
|
| 114 | + --stdin read Markdown from standard input
|
| 115 | + --enable-tables enable table parsing
|
115 | 116 |
|
116 | 117 | Interactive:
|
117 | 118 |
|
@@ -132,6 +133,15 @@ Batch:
|
132 | 133 |
|
133 | 134 | ```
|
134 | 135 |
|
| 136 | +Tables are disabled by default, as in CommonMark.
|
| 137 | +Use `--enable-tables` with any input mode to enable them:
|
| 138 | +
|
| 139 | +```bash
|
| 140 | +markdown-it --enable-tables README.md > index.html
|
| 141 | +markdown-it --enable-tables --stdin < README.md > index.html
|
| 142 | +markdown-it --enable-tables
|
| 143 | +```
|
| 144 | +
|
135 | 145 | ## References / Thanks
|
136 | 146 |
|
137 | 147 | Big thanks to the authors of [markdown-it]:
|
|
Lines changed: 18 additions & 11 deletions
| Original file line number | Diff line number | Diff line change |
@@ -18,50 +18,54 @@
|
18 | 18 |
|
19 | 19 | def main(args: Sequence[str] | None = None) -> int:
|
20 | 20 | namespace = parse_args(args)
|
| 21 | + md = MarkdownIt()
|
| 22 | + if namespace.enable_tables:
|
| 23 | + md.enable("table")
|
21 | 24 | if namespace.filenames:
|
22 | | - convert(namespace.filenames)
|
| 25 | + convert(namespace.filenames, md)
|
23 | 26 | elif namespace.stdin:
|
24 | | - convert_stdin()
|
| 27 | + convert_stdin(md)
|
25 | 28 | else:
|
26 | | - interactive()
|
| 29 | + interactive(md)
|
27 | 30 | return 0
|
28 | 31 |
|
29 | 32 |
|
30 | | -def convert(filenames: Iterable[str]) -> None:
|
| 33 | +def convert(filenames: Iterable[str], md: MarkdownIt | None = None) -> None:
|
31 | 34 | for filename in filenames:
|
32 | | - convert_file(filename)
|
| 35 | + convert_file(filename, md)
|
33 | 36 |
|
34 | 37 |
|
35 | | -def convert_stdin() -> None:
|
| 38 | +def convert_stdin(md: MarkdownIt | None = None) -> None:
|
36 | 39 | """
|
37 | 40 | Parse a Markdown file and dump the output to stdout.
|
38 | 41 | """
|
39 | 42 | try:
|
40 | | - rendered = MarkdownIt().render(sys.stdin.read())
|
| 43 | + rendered = (md or MarkdownIt()).render(sys.stdin.read())
|
41 | 44 | print(rendered, end="")
|
42 | 45 | except OSError:
|
43 | 46 | sys.stderr.write("Cannot parse Markdown from the standard input.\n")
|
44 | 47 | sys.exit(1)
|
45 | 48 |
|
46 | 49 |
|
47 | | -def convert_file(filename: str) -> None:
|
| 50 | +def convert_file(filename: str, md: MarkdownIt | None = None) -> None:
|
48 | 51 | """
|
49 | 52 | Parse a Markdown file and dump the output to stdout.
|
50 | 53 | """
|
51 | 54 | try:
|
52 | 55 | with open(filename, encoding="utf8", errors="ignore") as fin:
|
53 | | - rendered = MarkdownIt().render(fin.read())
|
| 56 | + rendered = (md or MarkdownIt()).render(fin.read())
|
54 | 57 | print(rendered, end="")
|
55 | 58 | except OSError:
|
56 | 59 | sys.stderr.write(f'Cannot open file "{filename}".\n')
|
57 | 60 | sys.exit(1)
|
58 | 61 |
|
59 | 62 |
|
60 | | -def interactive() -> None:
|
| 63 | +def interactive(md: MarkdownIt | None = None) -> None:
|
61 | 64 | """
|
62 | 65 | Parse user input, dump to stdout, rinse and repeat.
|
63 | 66 | Python REPL style.
|
64 | 67 | """
|
| 68 | + md = md or MarkdownIt()
|
65 | 69 | print_heading()
|
66 | 70 | contents = []
|
67 | 71 | more = False
|
@@ -70,7 +74,7 @@ def interactive() -> None:
|
70 | 74 | prompt, more = ("... ", True) if more else (">>> ", True)
|
71 | 75 | contents.append(input(prompt) + "\n")
|
72 | 76 | except EOFError:
|
73 | | - print("\n" + MarkdownIt().render("\n".join(contents)), end="")
|
| 77 | + print("\n" + md.render("".join(contents)), end="")
|
74 | 78 | more = False
|
75 | 79 | contents = []
|
76 | 80 | except KeyboardInterrupt:
|
@@ -110,6 +114,9 @@ def parse_args(args: Sequence[str] | None) -> argparse.Namespace:
|
110 | 114 | parser.add_argument(
|
111 | 115 | "--stdin", action="store_true", help="read Markdown from standard input"
|
112 | 116 | )
|
| 117 | + parser.add_argument(
|
| 118 | + "--enable-tables", action="store_true", help="enable table parsing"
|
| 119 | + )
|
113 | 120 | parser.add_argument(
|
114 | 121 | "filenames", nargs="*", help="specify an optional list of files to convert"
|
115 | 122 | )
|
|
Lines changed: 48 additions & 0 deletions
| Original file line number | Diff line number | Diff line change |
@@ -95,3 +95,51 @@ def test_interactive_render():
|
95 | 95 | # The rendered output is prefixed by a newline
|
96 | 96 | assert "\n<h1>hello</h1>\n" in output
|
97 | 97 | assert "Exiting" in output
|
| 98 | +
|
| 99 | +
|
| 100 | +def test_interactive_hard_line_break():
|
| 101 | + """Interactive input lines are joined as typed, see issue #172."""
|
| 102 | + # Simulate user typing 'foo\\' then 'bar', Ctrl-D (renders), then Ctrl-C (exits)
|
| 103 | + mock_input = patch(
|
| 104 | + "builtins.input", side_effect=["foo\\", "bar", EOFError, KeyboardInterrupt]
|
| 105 | + )
|
| 106 | + string_io = io.StringIO()
|
| 107 | + with redirect_stdout(string_io), mock_input:
|
| 108 | + parse.interactive()
|
| 109 | +
|
| 110 | + # a single paragraph with a hard break, not two paragraphs
|
| 111 | + assert "\n<p>foo<br />\nbar</p>\n" in string_io.getvalue()
|
| 112 | +
|
| 113 | +
|
| 114 | +@pytest.mark.parametrize("route", ["files", "stdin", "interactive"])
|
| 115 | +@pytest.mark.parametrize("enable_tables", [False, True])
|
| 116 | +def test_tables(route, enable_tables, tmp_path, capsys):
|
| 117 | + """Table parsing is opt-in on every CLI route, preserving HTML settings."""
|
| 118 | + source = "a | b\n--- | ---\n1 | 2\n\n<em>raw</em> ~~plain~~\n"
|
| 119 | + expected = (
|
| 120 | + "<table>\n<thead>\n<tr>\n<th>a</th>\n<th>b</th>\n</tr>\n</thead>\n"
|
| 121 | + "<tbody>\n<tr>\n<td>1</td>\n<td>2</td>\n</tr>\n</tbody>\n</table>\n"
|
| 122 | + if enable_tables
|
| 123 | + else "<p>a | b\n--- | ---\n1 | 2</p>\n"
|
| 124 | + ) + "<p><em>raw</em> ~~plain~~</p>\n"
|
| 125 | + args = ["--enable-tables"] if enable_tables else []
|
| 126 | + if route == "files":
|
| 127 | + paths = [tmp_path / "first.md", tmp_path / "second.md"]
|
| 128 | + for path in paths:
|
| 129 | + path.write_text(source, encoding="utf8")
|
| 130 | + assert parse.main([*args, *map(str, paths)]) == 0
|
| 131 | + expected *= 2
|
| 132 | + elif route == "stdin":
|
| 133 | + with patch("sys.stdin", io.StringIO(source)):
|
| 134 | + assert parse.main([*args, "--stdin"]) == 0
|
| 135 | + else:
|
| 136 | + inputs = [*source.splitlines(), EOFError] * 2 + [KeyboardInterrupt]
|
| 137 | + with patch("builtins.input", side_effect=inputs):
|
| 138 | + assert parse.main(args) == 0
|
| 139 | + expected = (
|
| 140 | + f"{parse.version_str} (interactive)\n"
|
| 141 | + "Type Ctrl-D to complete input, or Ctrl-C to exit.\n"
|
| 142 | + + ("\n" + expected) * 2
|
| 143 | + + "\nExiting.\n"
|
| 144 | + )
|
| 145 | + assert capsys.readouterr().out == expected
|
|
|