Skip to content

Allow users to more easily customise code highlighting #467

Closed

Description

@d0ugal

Following this discussion we should allow users to take control here. People are very specific about how they like this to be handled.

Currently all the default themes force the user to use highlight.js. Let's find a way to let them change that easily. Ideally this would be done without requiring another setting - one possible approch would be with template overriding.

Activity

  1. brontosaurusrex commented on May 26, 2015

    @brontosaurusrex

    My opinions;
    a. If basic markdown (code is defined by 4 spaces) is found, the highlight.js is OFF
    b. if extended markdown (3 ticks and code type undefined) is found, the highlight.js could be ON, but only when it gets smart enough and the behaviour is specified in config file.
    c. if extended markdown (3 ticks and code type defined) is found, the highlight.js should be ON, but only when the behaviour is specified in the config file.

    (Short version: OFF)

    Buggy example;
    baddefault

  2. cdomigan commented on Jun 5, 2015

    @cdomigan

    +1

    It would be incredibly helpful to disable highlighting where needed, as it produces non-sensical output.
    Surely damning that this affects the mkdocs.org homepage itself! :)

    Edit: Looks like you can use the "no-highlight" tag after your backticks to solve this!!

  3. d0ugal commented on Jun 5, 2015

    @d0ugal
    ContributorAuthor

    Yup, that's correct. no-highlight will partially solve this. This issue is more about letting users customise the behaviour more generally - either to use a different highlighter or none at all. It seems people have particular choices when it comes to highlighting so whatever default we make wont work for everyone.

  4. brontosaurusrex commented on Jun 5, 2015

    @brontosaurusrex

    There is no "code blocks and backticks" in basic markdown as far is I can see.

  5. d0ugal commented on Jun 5, 2015

    @d0ugal
    ContributorAuthor

    @brontosaurusrex I don't follow. What are you replying to?

  6. brontosaurusrex commented on Jun 5, 2015

    @brontosaurusrex

    sorry, it was a reply to cdomigan
    "Edit: Looks like you can use the "no-highlight" tag after your backticks to solve this!!""

  7. d0ugal commented on Jun 5, 2015

    @d0ugal
    ContributorAuthor

    We support fenced code blocks in MkDocs (by enabling the python-markdown extension). http://www.mkdocs.org/user-guide/writing-your-docs/#fenced-code-blocks

    We should consider adding a no-highlight example.

  8. brontosaurusrex commented on Jun 5, 2015

    @brontosaurusrex

    I understand that, but someone (me) would want to keep it simple and nice to look in raw format (which basic markdown is) as well, so if we don't understand each other now, I quit :)

  9. facelessuser commented on Jun 5, 2015

    @facelessuser
    Contributor

    I think making highlighting more easily configurable is definitely the real solution as stated earlier. Currently, I override the base template and theme.js and use something else.

    I've never liked that highlight.js by default wants to guess languages as it often turns out bad with plain text. Guessing languages is hard, and highight.js breaks down when a block is just plain text. It seems to assume that fenced blocks are only code. I know when I was using highlight.js, I overrode the default load to search for pre code blocks that only had language attributes and loaded those individually. That way if I defined no language, highlight.js would leave it alone, and if it did have a language, it would use the specified language; it was more explicit.

    My JavaScript fu sucks, but this what I used at the time; I don't even know if this works with the latest highlight.js. But I guess my point isn't to use the code, but if you override the base template and the theme.js in your theme, you can currently control your highlighting or even use something else. But I think it should be even easier, and you should just be able to provide a highlight.html template.

    // No Guessing
    function hljs_initNoGuessOnLoad() {
        addEventListener('DOMContentLoaded', hljs_initNoGuessHighlighting, false);
        addEventListener('load', hljs_initNoGuessHighlighting, false);
    }
    
    function hljs_initNoGuessHighlighting() {
        var elements = document.querySelectorAll('pre code'),
            elength = elements.length,
            clenght, i, j, classes, m, language, obj, code, index;
    
        if (hljs_initNoGuessHighlighting.called) {
            return;
        }
        hljs_initNoGuessHighlighting.called = true;
    
        for (i = 0; i < elength; i++) {
            code = elements[i]
            classes = code.className.split(' ');
            language = null;
            clength = classes.length
            for (j=0; j < clength; j++) {
                hasLang = new RegExp(/^language-([^\s]+)$/)
                m = hasLang.exec(classes[j]);
                if (m) {
                    index = j;
                    language = m[1];
                    break;
                }
            }
            if (language) {
                obj = hljs.highlight(language, code.textContent, true)
                code.innerHTML = obj.value;
                classes[index] = "hljs " + obj.language;
                code.className = classes.join(" ");
                code.parentNode.className += " hljs";
            } else {
                code.className += " hljs";
                code.parentNode.className += " hljs";
            }
        }
    }
    
    hljs_initNoGuessOnLoad();
  10. added this to the 1.0.0 milestone on Jun 27, 2015
  11. obestwalter commented on Apr 18, 2016

    @obestwalter

    In my view there are two clear cases:

    1. language guessing in fenced code blocks without explicit language is perfectly o.k. (because you can add the language if the guess is wrong)
    2. language guessing in "old school" code blocks is not (because most of the time you don't want it and you can't correct it if it is wrong either)

    I was surprised by this behaviour and see it as a bug, because in my experience these blocks are almost always shell examples or program output, both of which should never be highlighted, but simply formatted in pre tags.

    I did not have a look at the code yet, but I would hope that the two cases mentioned above are handled separately.

    If there could be agreement on this I would try to find some time soon and fix that. My naive approach to fix it would be to just switch it off for 2. and leave it like it is for 1. (without any configuration settings to reactivate guessing in 2. because if you really want sane highlighting you can just use 1.).

  12. waylan commented on Apr 18, 2016

    @waylan
    Contributor

    @obestwalter MkDocs uses the highlight.js JavaScript library for highlighting, which runs in the browser. All it sees is the HTML output by Markdown after the build has completed. As the HTML for each type of code bock is the same, there is no way for it to differentiate between indented code blocks and fenced code blocks. Currently, the only way to address this as a user is to create a custom theme as the highlighting is all contained in the themes.

    A possible workaround may be to use a Markdown extension which does the highlighting at build time (fully configurable in MkDocs). As long as the output is not identified by highlight.js as a code block, then it won't run a second time. Of course, the highlight.js lib will still be served to all your users unnecessarily in that case, so that is less than ideal.

    For another possibility, the CodeHilite Extension (which ships with Python-Markdown) allows you to define a language for indented code blocks. Actually, if you use that extension with the use_pygments setting set to False (so that the language will be set as a class on the block only), then you can set the language and allow highlight.js to do the actual highlighting. By setting the language to no-highlight, highlight.js should not highlight that block. YMMV.

    I suspect the resolution to this issue will be addressed for the most part by better theme customization (see #607) and/or a Plugin API (see #206). That is unless MkDocs abandons using a JS library and uses a Markdown extension instead.

    Finally, I disagree with your premise that highlighting should be on by default for fenced code blocks but off by default for indented code blocks. Personally, any difference in behavior would be a bug in my view.

  13. obestwalter commented on Apr 18, 2016

    @obestwalter

    Thanks for the detailed explanation @waylan.

    As the HTML for each type of code bock is the same, there is no way for it to differentiate between indented code blocks and fenced code blocks.

    ah o.k. - then my naive approach would mean first changing the code in a way that the two different syntaxes result in two different renderings.

    Finally, I disagree with your premise that highlighting should be on by default for fenced code blocks but off by default for indented code blocks. Personally, any difference in behavior would be a bug in my view.

    Interesting. I think that in a perfect world where language guessing just works, this would be the obvious conclusion. In the messy real world though I think that different handling of the two different markdown syntaxes makes a lot of sense. Only one of the syntaxes is "real" Markdown anyway. The proposed rendering for code blocks using the original syntax in the "spec" is simply pre without any fancy stuff, so this would be consistent and unsurprising for most users, I guess. The fancy fenced codeblock addition could then offer highlighting. But - as I mentioned already - this would only work if the two syntaxes resulted in different HTML.

    Is this approach completely out of the question? Would that complicate the code too much?

    Anyway - I find the topic quite interesting and hope to have a closer look at the code and the issues you mentioned and then might start to agree with you, or have better arguments to make my case (or a better idea how to handle the problem in a saner way).

  14. waylan commented on Apr 18, 2016

    @waylan
    Contributor

    What is very clear is that different people have very different preconceived ideas about how syntax highlighting should work. What is not clear is which set of defaults would be the least surprising to the most people. And what is even less clear is how this issue should be resolved (how should users override those defaults--via a Markdown extension, additional settings, theme customization, a (future) Plugin...). If we work out that last issue, the rest will be easy enough to address.

  15. obestwalter commented on Apr 18, 2016

    @obestwalter

    I realize that my original bug report is to be treated independently from this discussion or the other ones that you mentioned. I clarified it in the original report.

  16. lukeschlather commented on Aug 17, 2016

    @lukeschlather

    Would you reconsider #902 ?

    I think highlight.js is great, but the autodetection is not useful and should probably be disabled by default.

  17. added
    Theme-general
    on Nov 1, 2017
  18. drmad commented on Dec 16, 2017

    @drmad

    I use extensively EnlighterJS, I think it's more complete and flexible that highlight.js. And it works ferpectly with PHP Markdown Extra because with it you can specify CSS classes and HTML attributes using CSS selectors to some MD elements, like headers, imgs and, obviously, fenced code blocks.

    Using CSS selectors to add CSS/HTML data to a MD element will not only allow to use a different enlightener, but will help to fine-tune some possible style issues.

    Also, with EnlighterJS it's easy to fix the original google group discussion issue: you can specify the default language for all the blocks using a meta tag.

  19. modified the milestones: 1.0.0, Post 1.0 on Feb 5, 2018
  20. waylan commented on Jul 5, 2018

    @waylan
    Contributor

    Since this discussion was started, a few major changes have happened to MkDocs. Most notably, we now have theme specific settings. In #1533 we add some new settings to the built-in themes related to code highlighting. The setting highlightjs can enable/disable use of the highlight.js lib. Therefore, if a user wishes to use a different tool for highlighting, they can "disable" highlight.js and then use extra_css and/or extra_javascript to add support for their tool of choice. Of note is that the built-in themes now use highlight.js via a CDN so no files are included in the built site for highlight.js. When a user sets highlightjs: false in their config, no references to highlight.js appear anywhere in the built site.

    To use the CodeHilite Markdown Extension in MkDocs version 1.0+, a user could use the following config:

    theme:
        name: mkdocs
        highlightjs: false
    
    extra_css:
        - css/code_styles.css
    
    markdown_extensions:
        - codehilite

    Then copy their CSS file of choice from richleland/pygments-css (or some custom styles if they desire) to css/code_styles.css within their docs_dir.

    Obviously, if a user wanted to use a competing JavaScript library, they would need to provide both the CSS and JavaScript files, which could easily be done with extra_css and extra_javascript settings.

    Of course, other third-party themes may provide any alternative they want. The entire feature is completely theme dependent and requires no changes to the MkDocs core. This issue was only ever really about the two built-in themes, which has been addressed. Therefore, I consider this issue to be resolved by #1533.

  21. modified the milestones: Post 1.0, 1.0.0 on Jul 5, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementTheme-general

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions