metonym / svelte-highlight

Syntax Highlighting for Svelte using highlight.js
https://svhe.onrender.com
MIT License
253 stars 13 forks source link

Add line numbers #240

Closed pjebs closed 1 year ago

pjebs commented 1 year ago

https://github.com/wcoder/highlightjs-line-numbers.js#usage

Is there a way to make this work with the above package:

https://github.com/wcoder/highlightjs-line-numbers.js/issues/78

pjebs commented 1 year ago

Here is my workaround:

        code = `package main`;
        let i = 1;
        code = code.replace(/^/gm, () => `${i++}.\t`);      

At least for the go language detection, it works perfectly.

pjebs commented 1 year ago

Assuming above code for prepending line numbers, for "basic" line highlighting, the best I was able to get was:

<HighlightSvelte language={go} {code}  on:highlight={(e) => {
    let n = line_number;
    let numbers = document.getElementsByClassName('hljs')[0].getElementsByClassName('hljs-number');
        for (let i = 0; i < numbers.length; i++) {
            if ((numbers[i].textContent === '' + n + '.') || 
                ((numbers[i].textContent === '' + n) && numbers[i].nextSibling.nodeValue.charAt(0) === '.')) {
                numbers[i].style.backgroundColor = 'blue';
                numbers[i].scrollIntoView({ block: 'center', behavior: 'auto' })
                return;
        }
}}/>
CaptainT33mo commented 1 year ago

Can you please create a repel demo for the workaround to add line numbers to the code?

metonym commented 1 year ago

@CaptainT33mo Line numbers are now supported by this library in version 7.

<script>
  import Highlight, { LineNumbers } from "svelte-highlight";
  import typescript from "svelte-highlight/languages/typescript";
  import atomOneDark from "svelte-highlight/styles/atom-one-dark";

  const code = "const add = (a: number, b: number) => a + b";
</script>

<svelte:head>
  {@html atomOneDark}
</svelte:head>

<Highlight language={typescript} {code} let:highlighted>
  <LineNumbers {highlighted} />
</Highlight>