ckan icon indicating copy to clipboard operation
ckan copied to clipboard

markdown_extract truncates on the escaped text, so descriptions containing & or < lose a third of the extract

Open opensource-joe opened this issue 3 months ago • 2 comments

CKAN version

2.11.5 (verified against the installed package, not a checkout). markdown 3.10.2, bleach 6.4.0, matching requirements.txt.

Describe the bug

h.markdown_extract() measures its truncation width against the HTML-escaped text, so any description containing &, < or > is cut far shorter than the requested length.

ckan/lib/helpers.py:1402:

plain = bleach_clean(markdown(text), tags=(), strip=True)
if not extract_length or len(plain) < extract_length:
    return literal(plain)
return literal(str(shorten(plain, width=extract_length, placeholder='...')))

bleach leaves entities in the result, so R&D is five characters longer than it looks: R&amp;D costs 7 against the budget and displays as 3. shorten then measures the escaped string.

The visible effect is on dataset search listings, where templates/snippets/package_item.html:14 calls it with extract_length=180.

Steps to reproduce

from ckan.lib.helpers import markdown_extract

prefix = "Ozone and NO2 columns measured at Uccle. "
with_amp    = prefix + "R&D " * 40
without_amp = prefix + "RxD " * 40

print(len(str(markdown_extract(with_amp, 180)).replace("&amp;", "&")))  # 111
print(len(str(markdown_extract(without_amp, 180))))                     # 179

Two descriptions of the same length, differing only in whether a character needs escaping.

Expected behavior

Both should keep roughly the same number of visible characters, near the 180 requested. The one containing ampersands keeps 111, losing about a third of its extract.

The more entity-dense the text, the worse it gets. This affects any description using & in an organisation name, < or > in a value range, or quoted attributes.

Additional details

The fix presumably involves measuring the unescaped text, or unescaping before shorten and re-escaping after. I have not opened a PR because the choice affects what "length" means in the API and that seems worth a maintainer's view first. Happy to implement whichever direction you prefer.

Found while investigating #9366, which is a different problem. This one is separate and reproducible on its own.

opensource-joe avatar Aug 17 '26 04:08 opensource-joe

This looks fixed on master. 64e999c8 brought in html.unescape(nh3_clean(...)), and checking against master today, a description of Ben & Jerry repeated returns 190 visible characters with a raw & rather than &amp;, so the escaping no longer costs against the extract length.

Happy for this to be closed. #9489 is still open and #9491 now covers only that.

opensource-joe avatar Sep 09 '26 01:09 opensource-joe

Thanks for this @opensource-joe , yes we already had a conflicting change cued up for the release when you submitted. Closing as requested.

wardi avatar Sep 09 '26 01:09 wardi