docsify icon indicating copy to clipboard operation
docsify copied to clipboard

Prismjs supports line numbers and sepcific line highlight

Open toavinar opened this issue 6 years ago • 4 comments

Is it possible to integrate to docsify PrismJS line-highlight and line-numbers plugins ?

Thank's for this amazing project, great work !

toavinar avatar Feb 15 '19 13:02 toavinar

Sure, but it seems that you need to write the code and pre elements manually.

timaschew avatar Feb 18 '19 12:02 timaschew

Of course, here is my workaround for line-numbers :

index.html :

<script>
    window.$docsify = {
      markdown: {        
            code: function(code, lang) {
                return ('<pre data-lang="'+lang+'"><code class="line-numbers language-'+lang+'">'+code+'</code></pre>')
            }
        },
      plugins: [
          function (hook, vm) {
              hook.doneEach(function (html) {                
                Prism.highlightAll();
              })
          }
      ]
</script>

It works but copy clipboard plugin doesn't works anymore. I keep working on it.

Edit :

I try to add : data-lang="'+lang+'" like this :

code: function(code, lang) {
  return ('<pre data-lang="'+lang+'"><code class="line-numbers language-'+lang+'">'+code+'</code></pre>')
}

Copy to clipboard button works but line-numbers is breaking. If any suggests ?

toavinar avatar Feb 18 '19 12:02 toavinar

This workaround doesn't work now. I discovered that the problem is caused by overflow attribute. So here's my solution:

First change the default rendering behavior to add class line-numbers:

window.$docsify {
    markdown: {
        renderer: {
          /* Change code block rendering. Add line-numbers class.*/
          code: function (code, lang) {
            let cc = document.createElement('code');
            cc.textContent = code;
            cc.setAttribute('class', 'language-' + lang);
            return '<pre data-lang="' + lang + '" class="line-numbers">' + cc.outerHTML + '</pre>';
          }
        }
      }
}

Then I need to change that incorrect overflow by an another CSS:

/*  
 * Fix line number in code block. 
 * Change this overflow attr to <pre> not the <code>.
 */
.markdown-section pre[data-lang] {
    overflow: auto !important;
}
.markdown-section pre[data-lang] code {
    overflow: visible;
}

At last I need to change the padding of .line-numbers to align with codes:

.line-numbers .line-numbers-rows {
    border-right : 2px solid white;
    /* Fix paddings to align with code.*/
    padding: 2.2em 0; /* Same as code block */
}

And finally those code-numbers were showed correctly.

guyutongxue avatar Jul 09 '20 08:07 guyutongxue

This doesn't seem to work anymore with more recent versions...?

thediveo avatar May 07 '23 15:05 thediveo