A lightweight Docusaurus plugin that exposes your Markdown files as raw .md
URLs and adds a button (or drop-down widget) to each page so users can copy the
Markdown file to their clipboard.
Note
This project is not packaged and distributed on npm. This is a fork of markdown_docusaurus_plugin by FlyNumber with some added functionality to support docs.modular.com.
Here are some of the things we added/changed:
- Supports
.mdxfiles, turning them into.md - Extracts page title from frontmatter before stripping the frontmatter
- Renders a single "Copy page" button instead of drop-down widget, by default (the drop-down widget is still available via configuration)
- Miscellaneous improvements to processing Docusaurus tags like tabs, plus other MDX components (most are specific to docs.modular.com)
- Adds several user-configuration properties:
- Specify the path to your docs (previously hard-coded to
/docs) - Optional
blogarray so@docusaurus/plugin-content-blogposts get matching.mdURLs (same slug rules as the blog plugin) - Select the widget type, either original drop-down or new button
- Specify the DOM element where you want to inject the button/drop-down as a CSS selector (default is the page header)
- Specify the button text
- Specify the button/widget icons
- Specify the path to your docs (previously hard-coded to
- Adds
markdown_sourcefront matter, so a page whose body renders client-side can supply its own.mdcontent - Ports upstream's
aiProviders/aiPromptoptions ("Open in ChatGPT", "Open in Claude", and so on) into a reworked drop-down widget that sites can restyle and render themselves, with an optionaldescriptionper provider (see AI assistant links) - Adds support for docs pages with
slug: /frontmatter (other docs slug overrides are currently not supported)
Although this fork is not distributed as a package, you can still add it
as a dependency in your package.json pointing to the GitHub repo:
{
"dependencies": {
"docusaurus-markdown-source-plugin": "github:modular/markdown_docusaurus_plugin"
}
}Then run npm install to generate package-lock.json, which pins the resolved
commit. To update to a specific commit later, update the lock file entry or
append a commit hash:
"docusaurus-markdown-source-plugin": "github:modular/markdown_docusaurus_plugin#abc1234"The plugin accepts several configuration options to customize the "copy page" behavior on your Docusaurus pages.
You don't need to set any of these, but here's a snippet you can copy paste
into your docusaurus.config.js file in case you want to customize:
module.exports = {
plugins: [
['docusaurus-markdown-source-plugin', {
// URL path prefix where docs are served; set to '/' if docs
// are at the site root (default: '/docs/')
docsPath: '/docs/',
// Filesystem directory name containing markdown source files,
// relative to the site root (default: 'docs')
docsDir: 'docs',
// When true, generate .md for EVERY docs version (e.g. /docs/*.md and
// /nightly/docs/*.md), auto-discovered from @docusaurus/plugin-content-docs.
// When false, only the single `docsDir` tree is emitted. (default: false)
includeAllDocVersions: false,
// Which @docusaurus/plugin-content-docs instance to read when
// includeAllDocVersions is enabled, matching that plugin's `id`.
// (default: 'default')
docsPluginId: 'default',
// Blog content (@docusaurus/plugin-content-blog): emit `.md` URLs that match
// blog permalinks (routeBasePath + slug), not plain filesystem mirroring.
blog: [
{
path: 'releases',
exclude: ['archive.md', 'index.md'],
},
],
// 'button' for a simple copy button, 'dropdown' for a menu
// with multiple actions (default: 'button')
widgetType: 'button',
// CSS selector for the element the widget is injected into
// (default: 'article .markdown header')
containerSelector: 'article .markdown header',
// Label shown on the copy button (default: 'Copy page')
copyButtonText: 'Copy page',
// Label shown after a successful copy (default: 'Copied')
copiedButtonText: 'Copied',
// "Open in …" rows in the drop-down widget: built-in ids
// ('chatgpt', 'claude', 'gemini', 'perplexity', 'grok') and/or custom
// { label, url, description?, context? } entries, or false for none.
// (default: all five built-ins)
aiProviders: ['chatgpt', 'claude'],
// Prompt sent to the assistant; must contain {url}.
// (default: 'Read from {url} so I can ask questions about it.')
aiPrompt: 'Read from {url} so I can ask questions about it.',
// When true, trailing-slash URLs fetch intro.md
// (e.g., /foo/ -> /foo/intro.md). When false, the trailing slash
// is stripped (e.g., /foo/ -> /foo.md). (default: false)
supportDirectoryIndex: false,
// When true, rewrites internal markdown links to fully-qualified
// .md URLs using the site's configured URL. Makes the raw markdown
// self-contained for LLMs and external tools. (default: false)
fullyQualifiedLinks: false,
// Override the base URL used when fullyQualifiedLinks is enabled.
// By default the plugin uses context.siteConfig.url + baseUrl
// from your Docusaurus config. (default: undefined — auto-detected)
// siteUrl: 'https://example.com/docs',
// Markdown blockquote prepended to every generated .md file.
// Satisfies the llms-txt-directive check (afdocs). When set, the
// plugin also provides a <LlmsDirective /> theme component for
// placement on any page. (default: null — disabled)
// directive: '> For the full docs index, see [llms.txt](/llms.txt).\n> Markdown versions of all pages are available by appending .md to any URL.',
// HTML string injected as a <blockquote class="llms-directive">
// before the Docusaurus React root via preBodyTags. Ensures agents
// on the HTML path encounter the directive before navbar/sidebar
// content. (default: null — disabled)
// htmlDirective: 'To view this page as Markdown, append `.md` to the URL. For the full docs index, see <a href="/llms.txt">llms.txt</a>.',
}],
],
};By default the plugin only mirrors the single docsDir tree, so on a
versioned site the raw .md files are
generated for just one version. On a site where the latest stable docs are
served at the canonical path (e.g. /docs/) and the in-development docs at a
prefixed path (e.g. /nightly/docs/), this means:
/nightly/docs/*.mdis missing entirely, and- the canonical
/docs/*.mdis generated from the wrong source tree.
Set includeAllDocVersions: true to instead generate .md for all doc
versions. The plugin reads the loaded versions from
@docusaurus/plugin-content-docs at build time and, for each version, emits
.md at the same URL Docusaurus serves the HTML from (its permalink + .md).
Because output is driven by each version's loaded docs, excluded, draft, and
unlisted docs are automatically omitted — the .md set matches the HTML set.
['docusaurus-markdown-source-plugin', {
docsPath: '/',
includeAllDocVersions: true,
// docsPluginId: 'default', // only needed for a non-default docs instance
}]Use docsPluginId when the docs you want to mirror come from a named
@docusaurus/plugin-content-docs instance (the plugin ignores every other docs
instance, e.g. a separate design-system docs plugin).
If the docs plugin content can't be found at build time (misconfigured id, or
the docs plugin isn't present), the plugin logs a warning and falls back to the
legacy single-docsDir behavior.
Note: cross-version site-root-absolute links (e.g. a literal
/docs/foowritten in anightlypage) are not rewritten to point at their own version; this matches the plugin's existing absolute-link handling.
Optional array for Markdown trees served by
@docusaurus/plugin-content-blog. The cleaning pipeline is the same as for
docs; only output paths and fully-qualified link bases follow the
blog plugin’s URL scheme (routeBasePath + slug from filename rules or
front matter slug:), so appending .md matches the HTML route.
Root-level index.md / index.mdx (the blog list / hub page at
/{routeBasePath}/) is written as {routeBasePath}.md in the build output
(e.g. releases.md), matching the usual “strip trailing slash and add .md”
behavior.
Each entry:
path— folder relative to the site directory (same as the blog pluginpath). Used as the URLrouteBasePathwhen that option is omitted.routeBasePath— optional URL segment (same meaning as the blog plugin). Defaults topath; set only when the served route prefix differs from the source folder (unusual).exclude— optional basenames or relative paths to skip (for examplearchive.md).
Some pages have no useful markdown source because their body is rendered
client-side from data, such as an OpenAPI reference page that mounts an API
renderer. Their .md would hold only the title. To give such a page real
markdown, generate a markdown file for it before the build and name that file
in the page's front matter:
---
title: Create chat completion
markdown_source: generated/create-chat-completion.md
---The value is a path relative to the site directory (the one holding
docusaurus.config.js); absolute paths and paths containing .. are
rejected, as are symlinks that resolve to a file outside the site directory. Keep the file outside your docs and static directories, so that it
isn't also built as a doc page or served on its own.
The plugin emits that file as the page's .md instead of the cleaned page
source. Write it as plain markdown with its own H1: the plugin skips MDX
cleanup and image handling for it, but still prepends the directive and
applies fullyQualifiedLinks. Relative links resolve against the page's URL,
not the file's location, so prefer site-root links.
markdown_source applies to docs pages only, not blog posts. If the file is
missing, the build logs an error and writes no .md for that page.
When fullyQualifiedLinks is enabled, the plugin rewrites all internal
hyperlinks in the generated .md files to absolute URLs with .md extensions.
This makes the raw markdown useful outside the browser — for example, when an
LLM fetches a .md file, every link it encounters will be a fetchable URL
rather than a relative path that only works on the website.
Generated URLs have the form <siteUrl>/<docPath>.md, where <siteUrl> is
your Docusaurus url + baseUrl (e.g. https://example.com/docs) and
<docPath> is the resolved path relative to the docs root. For example, a
relative link ./algorithm/ in std/index.md becomes
https://example.com/docs/std/algorithm.md.
The plugin handles two kinds of internal links:
- Relative (
./algorithm/,../types) — resolved against the current file's directory (usingdirnameof the source path), then converted to a fully-qualified.mdURL. - Site-root-absolute (
/docs/roadmap,/docs/manual/types#string-literals) — converted directly to a fully-qualified.mdURL with the fragment preserved.
External links (https://...), anchor-only links (#section), and image
references (both inline  and reference-style ![alt][ref]) are
left unchanged.
The base URL defaults to url + baseUrl from your Docusaurus config. You can
override it with the siteUrl option if your production URL differs from the
config.
When directive is set to a markdown blockquote string, the plugin:
- Prepends it to every generated
.mdfile — before fully-qualified link processing, so links in the directive (like/llms.txt) are also rewritten whenfullyQualifiedLinksis enabled. - Provides a
LlmsDirectivetheme component — a server-rendered<blockquote>you can place on any page, satisfying the llms-txt-directive check. For doc pages, swizzleDocItem/Content(wrapping mode) and render<LlmsDirective />before the original content.
Example configuration:
directive: '> For the full docs index, see [llms.txt](/llms.txt).\n'
+ '> Markdown versions of all pages are available by appending .md to any URL.',The rendered HTML blockquote has the class llms-directive so you can style or
visually hide it with CSS (the spec permits hiding it while keeping it in the
server-rendered HTML for agents).
Doc pages — swizzle DocItem/Content:
// src/theme/DocItem/Content/index.js
import React from 'react';
import Content from '@theme-original/DocItem/Content';
import LlmsDirective from '@theme/LlmsDirective';
export default function ContentWrapper(props) {
return (
<>
<LlmsDirective />
<Content {...props} />
</>
);
}Non-doc pages — import the component directly:
import LlmsDirective from '@theme/LlmsDirective';
export default function HomePage() {
return (
<Layout>
<LlmsDirective />
{/* ... */}
</Layout>
);
}When directive is not configured, the component renders nothing.
The directive option places the blockquote inside each page's <main>
content area, which works well for the .md path. However, on the HTML path,
Docusaurus renders a navbar and sidebar before <main>, so agents using
Turndown (HTML-to-markdown conversion) may not reach the directive until deep
into the output.
The htmlDirective option solves this by injecting the directive as the very
first element in <body>, before the Docusaurus React root. It uses the
Docusaurus injectHtmlTags lifecycle with preBodyTags, so no component
swizzling or DOM reordering is needed.
['docusaurus-markdown-source-plugin', {
// Markdown directive for .md files (existing)
directive: '> For the full docs index, see [llms.txt](/llms.txt).\n'
+ '> Markdown versions available by appending .md to any URL.',
// HTML directive injected before <body> content (new)
htmlDirective:
'To view this page as Markdown, append `.md` to the URL. '
+ 'For the complete documentation index, see '
+ '<a href="/llms.txt">llms.txt</a>.',
}]The injected element is a <blockquote class="llms-directive">, so the same
CSS that hides the in-page directive (e.g. clip-path: inset(50%)) applies
here too.
When htmlDirective is not configured, nothing is injected.
The drop-down widget can list "Open in …" rows that open an AI assistant with
a prompt pointing at the current page. These options and the provider table
are ported from
upstream, and
both options are validated at build time, so a typo fails docusaurus build.
Built-in providers:
| id | Opens | {url} in the prompt |
|---|---|---|
chatgpt |
https://chatgpt.com/?hints=search&q=… |
the page's .md URL |
claude |
https://claude.ai/new?q=… |
the page's .md URL |
gemini |
https://www.google.com/search?udm=50&q=… (Google AI Mode) |
the HTML page URL |
perplexity |
https://www.perplexity.ai/search/new?q=… |
the HTML page URL |
grok |
https://grok.com/?q=… |
the HTML page URL |
ChatGPT and Claude fetch the URL they're given, so they get the clean .md
file. The others answer from a search index, which doesn't hold the .md
files, so they get the HTML page. Each built-in row shows the description
"Ask questions about this page".
aiProviders takes built-in ids in the order you want them, custom entries,
or false for none:
aiProviders: [
'claude',
'chatgpt',
{
label: 'Open in Mistral',
description: 'Chat about this page', // optional (fork addition)
url: 'https://chat.mistral.ai/chat?q={prompt}', // must contain {prompt}
context: 'page', // optional: 'page' (default) or 'markdown'
},
],The rows appear in the drop-down widget only. MarkdownCopyButton ignores
these options.
Instead of letting the plugin inject the widget with containerSelector, you
can import a component and render it in a swizzled theme component. Set
containerSelector to a selector that matches nothing (such as
'#no-inject') so the plugin doesn't also inject one.
import { usePluginData } from '@docusaurus/useGlobalData';
import MarkdownCopyButton from 'docusaurus-markdown-source-plugin/components/MarkdownCopyButton';
import MarkdownActionsDropdown from 'docusaurus-markdown-source-plugin/components/MarkdownActionsDropdown';
// A single copy button:
<MarkdownCopyButton docsPath="/" copyButtonText="Copy as Markdown" copiedButtonText="Copied!" />
// The drop-down, with the AI rows from your plugin config:
const { aiProviders, aiPrompt } = usePluginData('markdown-source-plugin');
<MarkdownActionsDropdown
docsPath="/"
buttonText="Copy page" // trigger label (default: 'Copy page')
copiedButtonText="Copied!" // copy row title after copying (default: 'Copied')
actions={['copy', 'view']} // markdown rows, in order (default: ['view', 'copy'])
labels={{ view: { description: 'Open the raw .md file' } }} // per-row title/description overrides
aiProviders={aiProviders} // default: none when rendered directly
aiPrompt={aiPrompt}
triggerClassName="" // default: Infima 'button button--secondary button--sm'
unstyled // skip the plugin's default styles (default: false)
/>The plugin loads default styles for the drop-down
(css/markdown-actions-dropdown.css): row layout with the title above the
description, icon spacing, the separator, and the chevron rotation. They're
scoped to .markdown-actions-dropdown--styled, which the component adds
unless you pass unstyled. Override individual rules with more specific
selectors, or pass unstyled to style the drop-down from scratch.
The drop-down's elements have these classes for styling:
| Class | Element |
|---|---|
.markdown-actions-dropdown |
Root (also Infima's .dropdown; --open while open; --styled unless unstyled) |
.markdown-actions-dropdown__trigger |
The button that opens the menu |
.markdown-actions-dropdown__label, __chevron |
Trigger label and chevron |
.markdown-actions-dropdown__menu |
The menu list (also Infima's .dropdown__menu) |
.markdown-actions-dropdown__item |
Each row; --copy, --view, --ai and --<provider id> modifiers; --copied / --error on the copy row |
.markdown-actions-dropdown__icon |
Icon slot in the trigger and each row |
.markdown-actions-dropdown__title, __description |
Row text lines |
.markdown-actions-dropdown__external |
External-link indicator on AI rows |
.markdown-actions-dropdown__separator |
Divider between markdown rows and AI rows |
The plugin uses theme components for icons, which can be overridden in your
site's src/theme/ directory:
Override the copy icon:
Create src/theme/MarkdownCopyIcon/index.js:
import React from 'react';
import IconCopy from '@theme/Icon/Copy';
export default function MarkdownCopyIcon({ size = 16, style }) {
return <IconCopy style={{ width: size, height: size, ...style }} />;
}Override the success/check icon:
Create src/theme/MarkdownCheckIcon/index.js:
import React from 'react';
import IconSuccess from '@theme/Icon/Success';
export default function MarkdownCheckIcon({ size = 16, style }) {
return <IconSuccess style={{ width: size, height: size, ...style }} />;
}The drop-down widget also uses these overridable icon components, which receive
the same size and style props:
MarkdownChevronIcon: the drop-down indicatorMarkdownViewIcon: the "View as Markdown" rowMarkdownExternalLinkIcon: the indicator on "Open in …" rowsMarkdownProviderIcon: AI provider marks (also receives the providerid)
This allows you to use your site's existing icon components or any custom SVG icons.
You'll want to customize this yourself, but here's some CSS to get the button or drop-down in the page header looking good.
Whether you're using the button or drop-down, add these styles to your
src/css/custom.css to set the layout position:
/* Style the article header as flexbox */
article .markdown header {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
overflow: visible;
}
/* Allow h1 to grow and take available space */
article .markdown header h1 {
flex: 1 1 auto;
margin: 0;
}
/* Container for the markdown actions dropdown */
.markdown-actions-container {
flex-shrink: 0;
margin-left: auto;
position: relative;
}
/* Ensure dropdown wrapper has proper positioning */
.markdown-actions-container .dropdown {
position: relative;
}Then, if you're using the default button, add this:
.markdown-actions-container {
display: inline-flex;
align-items: center;
}
.markdown-actions-container .markdown-copy-button {
display: inline-flex;
align-items: center;
gap: 8px;
background-color: transparent;
border: none;
padding: 0;
font-size: 0.875rem;
cursor: pointer;
color: var(--ifm-color-emphasis-600);
}
.markdown-actions-container .markdown-copy-button:hover {
color: var(--ifm-color-emphasis-900);
}
.markdown-actions-container .markdown-copy-button svg {
fill: currentColor;
}Or if you set widgetType: 'dropdown', add these styles:
/* Base dropdown menu styles */
.markdown-actions-container .dropdown__menu {
z-index: 1000;
min-width: 220px;
right: auto;
left: 0;
}
/* Add hover effect for dropdown items */
.dropdown__link:hover {
background-color: var(--ifm-hover-overlay);
}
/* Responsive adjustments for mobile */
@media (max-width: 768px) {
.markdown-actions-container {
margin-right: clamp(0px, 0.5rem, 1rem);
margin-bottom: 1rem;
}
.markdown-actions-container .button {
font-size: 0.875rem;
padding: 0.375rem 0.75rem;
}
/* Right-align menu on mobile to prevent cutoff */
.markdown-actions-container .dropdown__menu {
right: 0;
left: auto;
min-width: min(220px, calc(100vw - 2rem));
max-width: calc(100vw - 2rem);
padding-bottom: 0.75rem;
}
}
/* RTL language support */
[dir="rtl"] .markdown-actions-container {
margin-left: 0;
margin-right: auto;
}
[dir="rtl"] .markdown-actions-container .dropdown__menu {
right: auto;
left: 0;
}
@media (max-width: 768px) {
[dir="rtl"] .markdown-actions-container .dropdown__menu {
left: 0;
right: auto;
}
}For more information, see the original repo at FlyNumber/markdown_docusaurus_plugin