Просмотр исходного кода

feat: show line numbers from a specified number

this change allows to start numbering at any index 
`showLineNumbers=5` (here, numbering will start at index 5):

This is inspired from gatsby-remark-prismjs
Dhanraj Padmashali 4 лет назад
Родитель
Сommit
4260cab674
1 измененных файлов с 20 добавлено и 1 удалено
  1. 20 1
      index.js

+ 20 - 1
index.js

@@ -57,6 +57,24 @@ const calculateLinesToHighlight = (meta) => {
   }
 }
 
+/**
+ * Check if we want to start the line numbering from a given number or 0
+ * showLineNumbers=5, will start the numbering from 5
+ * @param {string} meta
+ * @returns {number}
+ */
+const calculateStartingLine = (meta) => {
+  const RE = /showLineNumbers=(?<lines>\d+)/i
+  // pick the line number after = using a named capturing group
+  if (RE.test(meta)) {
+    const {
+      groups: { lines },
+    } = RE.exec(meta)
+    return Number(lines)
+  }
+  return 0
+}
+
 /**
  * Split line to div node with className `code-line`
  *
@@ -193,13 +211,14 @@ const rehypePrism = (options = {}) => {
     refractorRoot.children = splitTextByLine(refractorRoot.children)
 
     const shouldHighlightLine = calculateLinesToHighlight(meta)
+    const startingLineNumber = calculateStartingLine(meta)
     // @ts-ignore
     const codeLineArray = splitLine(toString(node))
 
     for (const [i, line] of codeLineArray.entries()) {
       // Code lines
       if (meta.toLowerCase().includes('showLineNumbers'.toLowerCase()) || options.showLineNumbers) {
-        line.properties.line = [(i + 1).toString()]
+        line.properties.line = [(i + (startingLineNumber || 1)).toString()]
         line.properties.className.push('line-number')
       }