markdown - can I have underscores w/o escaping them and not have markdown italics?
Asked Answered
F

1

19

I want to have text that has underscores in it.

It's not code and so I don't want to use code format.

I want to stop markdown treating it as an instruction to italicize it.

I can escape _each_underscore (see!) with \ but I have a total of 20 and that looks ugly in the source, hard to maintain and not very DRY.

Any other options?

Foamy answered 24/4, 2012 at 16:59 Comment(0)
P
18

Some Markdown implementations – in particular Stack Overflow's server-side C# version MarkdownSharp (where it's optional behavior) and client-side JavaScript version PageDown, but also e.g. GitHub's flavor – have deviated from the Markdown spec for the very reason you describe.

For some history on this as far as Stack Overflow goes, see the two blog posts Three Markdown Gotchas and Markdown, One Year Later.

Since this is a commonly uttered criticism of Markdown, there are probably more implementations that either make this behavior user-settable, or just go with the stricter version altogether. So it depends on what implementation you're using.

If you're using a port that is based on John Gruber's original Perl implementation (i.e. the "tons of regex replacements" version), it should be fairly easy to make this change yourself. The relevant function is likely called _DoItalicsAndBold (original Perl version, Showdown/PageDown), DoItalicsAndBold (MarkdownSharp), _do_italics_and_bold (python-markdown2) or similar.

Look at our PageDown version of that function for the stricter regular expressions that are used here on Stack Overflow:

function _DoItalicsAndBold(text) {

    // <strong> must go first:
    text = text.replace(/([\W_]|^)(\*\*|__)(?=\S)([^\r]*?\S[\*_]*)\2([\W_]|$)/g,
    "$1<strong>$3</strong>$4");

    text = text.replace(/([\W_]|^)(\*|_)(?=\S)([^\r\*_]*?\S)\2([\W_]|$)/g,
    "$1<em>$3</em>$4");

    return text;
}
Pericline answered 25/4, 2012 at 6:0 Comment(1)
Thank you for this. I was looking for the regex to handle this and your answer is perfectly informative.Timikatiming

© 2022 - 2024 — McMap. All rights reserved.