python-markdownify icon indicating copy to clipboard operation
python-markdownify copied to clipboard

Allow html tags that contain only spaces

Open tthkbw opened this issue 1 year ago • 2 comments

markdownify converts this:

one<i> </i>two

into:

oneone

because the function chomp returns the text inside the tags as an empty string.

One can argue that empty tags like this should not be allowed, but the epub The Last Dangerous Visions from Blackstone Publishing has this structure in dozens of locations and the space inside the tag is the space between two words of the text. This results in my epub reader showing a bunch of words without spaces between them when I use markdownify to convert the

text of the epub files into markdown.

I don't pretend to understand how the markdownify code works in detail, but modifying chomp to look like this fixes the issue for me:

def chomp(text):
    """
    If the text in an inline tag like b, a, or em contains a leading or trailing
    space, strip the string and return a space as suffix of prefix, if needed.
    This function is used to prevent conversions like
        <b> foo</b> => ** foo**
    """
    #change to allow empty tags: "<i> </i>" and maintain the space
    if text.isspace():
        prefix = ''
        suffix = ''
        text = ' '
    else:
        prefix = ' ' if text and text[0] == ' ' else ''
        suffix = ' ' if text and text[-1] == ' ' else ''
        text = text.strip()
    return (prefix, suffix, text)

An unfortunate side effect of my fix is that this turns into something similar to &nbsp.

tthkbw avatar Oct 27 '24 17:10 tthkbw

Hey Terry, thanks for your issue! Unfortunately, your code converts <b> </b> to ** ** which is not what should happen. Maybe you could preprocess your ebook by replacing all occurances of <i> </i> with a single space?

AlexVonB avatar Nov 24 '24 20:11 AlexVonB

Perhaps there could be a combined fix for #175 and this issue. Let's see where that discussion leads first.

chrispy-snps avatar Jan 02 '25 18:01 chrispy-snps