Skip to content

Commit

Permalink
hotfix for "applyReferenceLinkFix"
Browse files Browse the repository at this point in the history
  • Loading branch information
dphuang2 committed Nov 6, 2023
1 parent bc44a4e commit 89f852d
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,46 @@ export function insertTableOfContents({
fs.writeFileSync(readmePath, withTocAndReferenceLinkFix)
}

const { slugify } = require('markdown-toc/lib/utils')

// https://github.com/pypa/readme_renderer/issues/169#issuecomment-808577486
/**
* Turns all headings into links by adding <a id="..."></a> after them with no space.
* Uses regex to avoid parsing the markdown AST.
*/
function applyReferenceLinkFix(markdown: string): string {
const { slugify } = require('markdown-toc/lib/utils')
/**
* Applies reference link fix to markdown text, excluding code blocks.
*
* @param markdown - The markdown text.
* @returns The fixed markdown text.
*/
export function applyReferenceLinkFix(markdown: string): string {
// This regex matches code blocks.
const codeBlockRegex = /```[\s\S]*?```/g
// This regex matches headings outside code blocks.
const headingRegex = /^#+\s+(.*)$/gm
return markdown.replace(headingRegex, (match, p1) => {

// Function to replace headings with slugified anchors.
function replaceHeadings(match: string, p1: string): string {
const slug = slugify(p1)
return `${match}<a id="${slug}"></a>`
}

// Split the content by code blocks and process non-code sections.
const parts = markdown.split(codeBlockRegex)
const codeBlocks = markdown.match(codeBlockRegex) || []

let fixedMarkdown = ''
let codeBlockIndex = 0

parts.forEach((part, index) => {
// Apply fix to non-code parts.
fixedMarkdown += part.replace(headingRegex, replaceHeadings)
// Re-insert code blocks where they were.
if (codeBlockIndex < codeBlocks.length) {
fixedMarkdown += codeBlocks[codeBlockIndex++]
}
})

return fixedMarkdown
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { applyReferenceLinkFix } from '../../src/util/insert-table-of-contents'

it('apply reference link fix', () => {
expect(applyReferenceLinkFix(`# Heading 1`)).toMatchInlineSnapshot(
`"# Heading 1<a id="heading-1"></a>"`
)
expect(applyReferenceLinkFix(`\`\`\`python\n#comment\n\`\`\``))
.toMatchInlineSnapshot(`
"\`\`\`python
#comment
\`\`\`"
`)
})

0 comments on commit 89f852d

Please sign in to comment.