mixmark-io / turndown

🛏 An HTML to Markdown converter written in JavaScript
https://mixmark-io.github.io/turndown
MIT License
8.84k stars 879 forks source link

How to avoid escape for pre? #340

Open jet10000 opened 4 years ago

jet10000 commented 4 years ago

TurndownService.prototype.escape

        turndownService.addRule('strikethrough', {
            filter: ['pre'],
            replacement: function (content) {
                return '```\n' + content + '\n```'
            }
        });

I add a rule for pre, how to avoid escape for pre?

martincizek commented 4 years ago

If your intention is just to use just plain text content, which seems likely, then it is better to avoid the rendered content completely in your rule. So your example would look like

        turndownService.addRule('pre', {
            filter: 'pre',
            replacement: function (content, node) {
                // Note this is not bulletproof, see below.
                return '```\n' + node.textContent + '\n```'
            }
        });

To make it bulletproof, you need to deal with eventual fence string (```), which may occur within <pre>, and there are also a few considerations regarding leading and trailing newlines. All these things should now be covered in the standard fencedCodeBlock rule: https://github.com/domchristie/turndown/blob/master/src/commonmark-rules.js#L111