fix: double underscored filenames now render correctly

This commit is contained in:
Hanzen Shou 2024-12-28 21:03:19 -08:00
parent 35b9e4c85c
commit c798df215e

View file

@ -50,6 +50,43 @@ const remarkUrlToLink = () => {
}
}
/**
* Custom remark plugin that prevents filenames with extensions from being parsed as bold text
* For example: __init__.py should not be rendered as bold "init" followed by ".py"
*/
const remarkPreventBoldFilenames = () => {
return (tree: any) => {
visit(tree, "strong", (node: any, index: number | undefined, parent: any) => {
// Only process if there's a next node (potential file extension)
if (!parent || typeof index === "undefined" || index === parent.children.length - 1) return
const nextNode = parent.children[index + 1]
// Check if next node is text and starts with . followed by extension
if (nextNode.type !== "text" || !nextNode.value.match(/^\.[a-zA-Z0-9]+/)) return
// If the strong node has multiple children, something weird is happening
if (node.children?.length !== 1) return
// Get the text content from inside the strong node
const strongContent = node.children?.[0]?.value
if (!strongContent || typeof strongContent !== "string") return
// Validate that the strong content is a valid filename
if (!strongContent.match(/^[a-zA-Z0-9_-]+$/)) return
// Combine into a single text node
const newNode = {
type: "text",
value: `__${strongContent}__${nextNode.value}`,
}
// Replace both nodes with the combined text node
parent.children.splice(index, 2, newNode)
})
}
}
const StyledMarkdown = styled.div`
pre {
background-color: ${CODE_BLOCK_BG_COLOR};
@ -160,6 +197,7 @@ const MarkdownBlock = memo(({ markdown }: MarkdownBlockProps) => {
const { theme } = useExtensionState()
const [reactContent, setMarkdown] = useRemark({
remarkPlugins: [
remarkPreventBoldFilenames,
remarkUrlToLink,
() => {
return (tree) => {