浏览代码

Merge pull request #19 from PsyGik/patch-1

feat: custom starting index for line numbers
Timothy 4 年之前
父节点
当前提交
23af3dec40
共有 2 个文件被更改,包括 40 次插入1 次删除
  1. 20 1
      index.js
  2. 20 0
      test.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 1
+ * 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 1
+}
+
 /**
  * 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).toString()]
         line.properties.className.push('line-number')
       }
 

+ 20 - 0
test.js

@@ -230,6 +230,26 @@ test('showLineNumbers property works in meta field', async () => {
   assert.not(result.match(/line="3"/g))
 })
 
+test('showLineNumbers property with custom index works in meta field', async () => {
+  const meta = 'showLineNumbers=5'
+  const result = processHtml(
+    dedent`
+    <div>
+      <pre>
+      <code class="language-py code-highlight">x = 6
+      y = 7
+      </code>
+      </pre>
+    </div>
+    `,
+    {},
+    meta
+  ).trim()
+  assert.ok(result.match(/line="5"/g))
+  assert.ok(result.match(/line="6"/g))
+  assert.not(result.match(/line="7"/g))
+})
+
 test('should support both highlighting and add line number', async () => {
   const meta = '{1} showLineNumbers'
   const result = processHtml(