arronhunt / highlightjs-copy

📋❇️ A simple, accessible highlightjs plugin to add a copy button to your code blocks.

Home Page:https://highlightjs-copy.netlify.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Just copy one line

dufu1991 opened this issue · comments

Is it possible to copy only one line, because there are many times when we only need a line in a large block of code?

@dufu1991 Yes, you should be able to do that with hooks. Something like this could work for simple use cases, and even be extended to support multiple lines.

<pre>
  <code class="language-js" data-line-to-copy="3">
    // sample code
    function doAThing(string) {
      alert(string);
    }
  </code>
</pre>

<script>
  hljs.addPlugin(
    new CopyButtonPlugin({
      hook: (text, el) => {
        const lines = text.split("\n");
        let { lineToCopy } = el.dataset;
        if (lineToCopy) {
          return lines[parseInt(lineToCopy)].trim();
        }
        return text;
      },
    })
  );
</script>