Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

Update anchor link handling to retain query params (#6930)

SamarJyoti496fd3853714882
diff --git a/examples/markdown/anchor_links.py b/examples/markdown/anchor_links.py
new file mode 100644
index 0000000000..58173eb737
--- /dev/null
+++ b/examples/markdown/anchor_links.py
@@ -0,0 +1,87 @@
+"""Test anchor links preserving query parameters.
+
+This example demonstrates that anchor links in markdown properly preserve
+query parameters (like ?file=test.py) when navigating within the document.
+
+To test:
+ Run this file with: marimo edit anchor_links.py
+"""
+
+import marimo
+
+__generated_with = "0.16.5"
+app = marimo.App(width="medium")
+
+
+def _():
+ import marimo as mo
+ return (mo,)
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ """
+ # Anchor Link Test
+
+ This document tests that anchor links preserve query parameters when
+ navigating between sections.
+
+ ## Table of Contents
+
+ - [Go to Section 1](#section-1)
+ - [Go to Section 2](#section-2)
+ - [Go to Section 3](#section-3)
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ """
+ # Section 1
+
+ This is the first section. You can navigate to:
+ - [Section 2](#section-2)
+ - [Section 3](#section-3)
+ - [Back to top](#anchor-link-test)
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ """
+ # Section 2
+
+ This is the second section. You can navigate to:
+ - [Section 1](#section-1)
+ - [Section 3](#section-3)
+ - [Back to top](#anchor-link-test)
+ """
+ )
+ return
+
+
[email protected](hide_code=True)
+def _(mo):
+ mo.md(
+ """
+ # Section 3
+
+ This is the third section. You can navigate to:
+ - [Section 1](#section-1)
+ - [Section 2](#section-2)
+ - [Back to top](#anchor-link-test)
+ """
+ )
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/frontend/src/components/ui/query-param-preserving-link.tsx b/frontend/src/components/ui/query-param-preserving-link.tsx
new file mode 100644
index 0000000000..201e87f68d
--- /dev/null
+++ b/frontend/src/components/ui/query-param-preserving-link.tsx
@@ -0,0 +1,48 @@
+/* Copyright 2025 Marimo. All rights reserved. */
+
+import React, { useRef } from "react";
+import { usePress } from "react-aria";
+
+interface QueryParamPreservingLinkProps
+ extends Omit<React.HTMLAttributes<HTMLAnchorElement>, "href"> {
+ href: string;
+ children: React.ReactNode;
+}
+
+export const QueryParamPreservingLink: React.FC<
+ QueryParamPreservingLinkProps
+> = ({ href, children, ...props }) => {
+ const ref = useRef<HTMLAnchorElement>(null);
+
+ const navigateWithQueryParams = () => {
+ const currentUrl = new URL(globalThis.location.href);
+ // Preserve existing query parameters and update the hash
+ currentUrl.hash = href;
+ globalThis.history.pushState({}, "", currentUrl.toString());
+
+ // Scroll to the anchor
+ const targetId = href.slice(1);
+ const targetElement = document.getElementById(targetId);
+ if (targetElement) {
+ targetElement.scrollIntoView({ behavior: "smooth", block: "start" });
+ }
+ };
+
+ const { pressProps } = usePress({
+ onPress: () => {
+ navigateWithQueryParams();
+ },
+ });
+
+ // For anchor links, we need to prevent default navigation
+ const handleClick = (e: React.MouseEvent<HTMLAnchorElement>) => {
+ e.preventDefault();
+ navigateWithQueryParams();
+ };
+
+ return (
+ <a ref={ref} href={href} {...pressProps} onClick={handleClick} {...props}>
+ {children}
+ </a>
+ );
+};
diff --git a/frontend/src/plugins/core/RenderHTML.tsx b/frontend/src/plugins/core/RenderHTML.tsx
index 6865e7e5c3..2957ebbc20 100644
--- a/frontend/src/plugins/core/RenderHTML.tsx
+++ b/frontend/src/plugins/core/RenderHTML.tsx
@@ -13,6 +13,7 @@ import React, {
useRef,
} from "react";
import { CopyClipboardIcon } from "@/components/icons/copy-icon";
+import { QueryParamPreservingLink } from "@/components/ui/query-param-preserving-link";
import { sanitizeHtml, useSanitizeHtml } from "./sanitize";
type ReplacementFn = NonNullable<HTMLReactParserOptions["replace"]>;
@@ -106,6 +107,30 @@ const replaceSrcScripts = (domNode: DOMNode): JSX.Element | undefined => {
}
};
+const preserveQueryParamsInAnchorLinks: TransformFn = (
+ reactNode: ReactNode,
+ domNode: DOMNode,
+): JSX.Element | undefined => {
+ if (domNode instanceof Element && domNode.name === "a") {
+ const href = domNode.attribs.href;
+ // Only handle anchor links (starting with #)
+ if (href?.startsWith("#") && !href.startsWith("#code/")) {
+ // Get the children from the parsed React node
+ let children: ReactNode = null;
+ if (isValidElement(reactNode) && "props" in reactNode) {
+ const props = reactNode.props as { children?: ReactNode };
+ children = props.children;
+ }
+
+ return (
+ <QueryParamPreservingLink href={href} {...domNode.attribs}>
+ {children}
+ </QueryParamPreservingLink>
+ );
+ }
+ }
+};
+
// Add copy button to codehilite blocks
const addCopyButtonToCodehilite: TransformFn = (
reactNode: ReactNode,
@@ -198,6 +223,7 @@ function parseHtml({
const transformFunctions: TransformFn[] = [
addCopyButtonToCodehilite,
+ preserveQueryParamsInAnchorLinks,
removeWrappingBodyTags,
removeWrappingHtmlTags,
];