r-lib / downlit

Syntax Highlighting and Automatic Linking
https://downlit.r-lib.org
Other
90 stars 22 forks source link

Fix: `downlit_html_*()` keeps all pre classes #155

Closed etiennebacher closed 2 years ago

etiennebacher commented 2 years ago

Close #149, close #156.

downlit_html() now keeps all pre classes, which allows for customization of code blocks in pkgdown using chunk options class.source and attr.source.

Old behavior (.my-class is not kept):

html <- xml2::read_xml("
  <div class='sourceCode'>
    <pre class='sourceCode r my-class'>
      <code class='sourceCode r'>
        <span>Hello</span>
      </code>
    </pre>
  </div>"
)
downlit::downlit_html_node(html)
html
#> {xml_document}
#> <div class="sourceCode">
#> [1] <pre class="downlit sourceCode r">\n<code class="sourceCode R"><span><spa ...

Created on 2022-08-05 by the reprex package (v2.0.1)

New behavior (.my-class is kept):

html <- xml2::read_xml("
  <div class='sourceCode'>
    <pre class='sourceCode r my-class'>
      <code class='sourceCode r'>
        <span>Hello</span>
      </code>
    </pre>
  </div>"
)
downlit::downlit_html_node(html)
html
#> {xml_document}
#> <div class="sourceCode">
#> [1] <pre class="downlit sourceCode r my-class">\n<code class="sourceCode R">< ...

Created on 2022-08-05 by the reprex package (v2.0.1)

@cderv You said that a fix for this should also fix https://github.com/r-lib/downlit/issues/133 but I didn't look at https://github.com/r-lib/downlit/issues/133 because of time and because it is related to several other issues.

Happy to modify the code and to bump version and NEWS if required.

etiennebacher commented 2 years ago

Actually, this PR doesn't work because it applies all pre classes to all codeblocks, which is not the expected behavior:

html <- xml2::read_xml("
<div>
  <div class='sourceCode'>
    <pre class='sourceCode r my-class'>
      <code class='sourceCode r'>
        <span>Hello</span>
      </code>
    </pre>
  </div>
  <div class='sourceCode'>
    <pre class='sourceCode r another-class'>
      <code class='sourceCode r'>
        <span>Hello</span>
      </code>
    </pre>
  </div>
</div>"
)
downlit::downlit_html_node(html)
html
#> {xml_document}
#> <div>
#> [1] <div class="sourceCode">\n  <pre class="downlit sourceCode r my-class dow ...
#> [2] <div class="sourceCode">\n  <pre class="downlit sourceCode r my-class dow ...

Created on 2022-08-08 by the reprex package (v2.0.1)

Therefore, I close it and will make a new one if I find a solution.