Repository: executablebooks/mdit-py-plugins

Issue:
Admonition title syntax is not consistent with other implementation
### Describe the bug

**context**

The [admonition syntax](https://mdit-py-plugins.readthedocs.io/en/latest/#containers) is based on [Python Markdown](https://python-markdown.github.io/extensions/admonition/):

~~~markdown
!!! danger "Don't try this at home"
    ...
~~~

**expectation**

I would expect the quotes to be absent from the output.

**bug**

With mdit-py-plugins, the quotes are present in the output:

![image](https://github.com/executablebooks/mdit-py-plugins/assets/946727/7a1543cd-d4a3-4df4-b96a-e225965720ee)

Unexpected output generated by mdit-py-plugins (spurious quotes):

~~~html
<div class="admonition danger"> <p class="admonition-title">"Don't try this at home"</p> <p>...</p> </div>
~~~

Moreover, the [additional CSS classes](https://squidfunk.github.io/mkdocs-material/reference/admonitions/) are not supported either.

Changing the behavior might cause compatiblity issues with [markdown-it-admon](https://github.com/commenthol/markdown-it-admon) however.

**problem**

This is a problem for people migrating from Python Markdown.


### Reproduce the bug

Create markdown file with:

~~~markdown
!!! danger "Don't try this at home"
    ...
~~~

Create script

~~~python3
from markdown_it import MarkdownIt
from mdit_py_plugins.admon import admon_plugin

md_opts = {
    "html": True,
}

markdown_it_render = MarkdownIt("commonmark", md_opts).use(admon_plugin)

source = open("/dev/stdin", "rt").read()
res = markdown_it_render.render(source)
print(res)
~~~

Run:

~~~sh
python3 test.py < test.md
~~~

Output:

~~~html
<div class="admonition danger">
<p class="admonition-title">&quot;Don't try this at home&quot;</p>
<p>...</p>
</div>
~~~

### List your environment

* Python 3.11.4
* Debian Linux
* markdown-it-py==3.0.0
* mdit-py-plugins==0.4.0

Hints from issue comments:
@welcome: Thanks for opening your first issue here! Engagement like this is essential for open source projects! :hugs:
<br>If you haven't done so already, check out [EBP's Code of Conduct](https://github.com/executablebooks/.github/blob/master/CODE_OF_CONDUCT.md). Also, please try to follow the issue template as it helps other community members to contribute more effectively.
<br>If your issue is a feature request, others may react to it, to raise its prominence (see [Feature Voting](https://executablebooks.org/en/latest/feature-vote/)).
<br>Welcome to the EBP community! :tada:
@chrisjsewell: Pinging @KyleKing (who worked on this plugin 😄 )@KyleKing: Thanks for reporting the bug. It may be straightforward to remove the outer quotes from the matched admonition title, and I'll separately take a look at the CSS classes since those seem pretty generic@KyleKing: I have a PR that should resolve the problem in: https://github.com/executablebooks/mdit-py-plugins/pull/94

I'll take a look at the HTML roles next@randomstuff: For reference, here is a quick patch I made, probably redundant with yours.@KyleKing: Got the HTML roles too 👍🏻

@chrisjsewell #94 is ready for review. I'm happy to split off the `roles` change in a separate PR. Let me know if there is anything I can add or remove otherwise!@randomstuff: > Moreover, the additional CSS classes are not supported either.

Some clarifications about this point.

This is the syntax documented in [mkdocs-material](https://squidfunk.github.io/mkdocs-material/reference/admonitions/). This implementation supports multiple token after `!!!` which are translated into CSS classes.

~~~markdown
!!! info inline end "Lorem ipsum"

    Lorem ipsum dolor sit amet, consectetur
    adipiscing elit. Nulla et euismod nulla.
    Curabitur feugiat, tortor non consequat
    finibus, justo purus auctor massa, nec
    semper lorem quam in massa.
~~~

Which gives:

~~~html
<div class="admonition info inline end"> <p class="admonition-title">Lorem ipsum</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla et euismod nulla. Curabitur feugiat, tortor non consequat finibus, justo purus auctor massa, nec semper lorem quam in massa.</p> </div>
~~~@randomstuff: My PR attempts to provides this but introduces a breaking change for this reason.@randomstuff: This syntax is what is implemented in [Python Markdown](https://github.com/Python-Markdown/markdown/blob/master/markdown/extensions/admonition.py:) in practice (though not documented?):

~~~
>>> import re
>>> RE = re.compile(r'(?:^|\n)!!! ?([\w\-]+(?: +[\w\-]+)*)(?: +"(.*?)")? *(?:\n|$)')
>>> RE.match("!!! a b c d").groups()
('a b c d', None)
>>> RE.match('!!! a b c d   "zzzz"  ').groups()
('a b c d', 'zzzz')
~~~@randomstuff: Notice in particuliar how the Python-Markdown implementation handles trailing `""`:

~~~
>>> RE.match('!!! a b c d   "Note: note about "foo""  ').groups()
('a b c d', 'Note: note about "foo"')
~~~@KyleKing: I just saw your replies here. I think we should be able to avoid a breaking change if double quotes aren't present, but I'll need to check locally@randomstuff: Kindly ping. Need help on this?@KyleKing: The PR is done and awaiting review.

@chrisjsewell, when you have a chance, could you please review and release this change: https://github.com/executablebooks/mdit-py-plugins/pull/94?@KyleKing: FYI: this change will be released in the next version of `mdformat-admon` regardless of the status of the PR (https://github.com/KyleKing/mdformat-admon/commit/aa27baa06b3747f507003ea36b3392acc2a632c0)

Solution patch:
diff --git a/mdit_py_plugins/admon/index.py b/mdit_py_plugins/admon/index.py
index a46e8cf..c39a4f7 100644
--- a/mdit_py_plugins/admon/index.py
+++ b/mdit_py_plugins/admon/index.py
@@ -1,7 +1,10 @@
 # Process admonitions and pass to cb.
+
 from __future__ import annotations
 
-from typing import TYPE_CHECKING, Callable, Sequence
+from contextlib import suppress
+import re
+from typing import TYPE_CHECKING, Callable, List, Sequence, Tuple
 
 from markdown_it import MarkdownIt
 from markdown_it.rules_block import StateBlock
@@ -14,20 +17,34 @@ if TYPE_CHECKING:
     from markdown_it.utils import EnvType, OptionsDict
 
 
-def _get_tag(params: str) -> tuple[str, str]:
+def _get_multiple_tags(params: str) -> Tuple[List[str], str]:
+    """Check for multiple tags when the title is double quoted."""
+    re_tags = re.compile(r'^\s*(?P<tokens>[^"]+)\s+"(?P<title>.*)"\S*$')
+    match = re_tags.match(params)
+    if match:
+        tags = match["tokens"].strip().split(" ")
+        return [tag.lower() for tag in tags], match["title"]
+    raise ValueError("No match found for parameters")
+
+
+def _get_tag(_params: str) -> Tuple[List[str], str]:
     """Separate the tag name from the admonition title."""
-    if not params.strip():
-        return "", ""
+    params = _params.strip()
+    if not params:
+        return [""], ""
+
+    with suppress(ValueError):
+        return _get_multiple_tags(params)
 
-    tag, *_title = params.strip().split(" ")
+    tag, *_title = params.split(" ")
     joined = " ".join(_title)
 
     title = ""
     if not joined:
         title = tag.title()
-    elif joined != '""':
+    elif joined != '""':  # Specifically check for no title
         title = joined
-    return tag.lower(), title
+    return [tag.lower()], title
 
 
 def _validate(params: str) -> bool:
@@ -125,12 +142,13 @@ def admonition(state: StateBlock, startLine: int, endLine: int, silent: bool) ->
     # this will prevent lazy continuations from ever going past our end marker
     state.lineMax = next_line
 
-    tag, title = _get_tag(params)
+    tags, title = _get_tag(params)
+    tag = tags[0]
 
     token = state.push("admonition_open", "div", 1)
     token.markup = markup
     token.block = True
-    token.attrs = {"class": " ".join(["admonition", tag, *_extra_classes(markup)])}
+    token.attrs = {"class": " ".join(["admonition", *tags, *_extra_classes(markup)])}
     token.meta = {"tag": tag}
     token.content = title
     token.info = params


Test patch:
diff --git a/tests/fixtures/admon.md b/tests/fixtures/admon.md
index 083d0b9..ffd7d2f 100644
--- a/tests/fixtures/admon.md
+++ b/tests/fixtures/admon.md
@@ -53,6 +53,32 @@ Shows no title
 .
 
 
+Removes extra quotes from the title
+.
+!!! danger "Don't try this at home"
+    ...
+
+.
+<div class="admonition danger">
+<p class="admonition-title">Don't try this at home</p>
+<p>...</p>
+</div>
+.
+
+
+Parse additional classes to support Python markdown (https://github.com/executablebooks/mdit-py-plugins/issues/93#issuecomment-1601822723)
+.
+!!! a b c d inline-classes   "Note: note about "foo"" 
+    ...
+
+.
+<div class="admonition a b c d inline-classes">
+<p class="admonition-title">Note: note about &quot;foo&quot;</p>
+<p>...</p>
+</div>
+.
+
+
 Closes block after 2 empty lines
 .
 !!! note