Merge pull request #2700 from jackyzha0/dev-mode/strip-diacritics-slugs

feat(slugs): opt-in configuration.slugs.stripDiacritics (#2410)
This commit is contained in:
Emile Bangma authored and GitHub committed 2026-11-26 18:58:06 +01:00
commit 11334aa029
11 files changed
+229 -5

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@jackyzha0/quartz": minor
---
New opt-in `configuration.slugs.stripDiacritics`: strips accents and other diacritics from generated slugs (`české/čeština.md` → `/ceske/cestina`). Links, embeds, aliases, permalinks and folder pages resolve to the stripped addresses; heading anchors and non-Latin scripts are unchanged. With `@quartz-community/utils` 1.3+ the option also reaches plugins that slug through utils (tag pages, canvas, bases, alias-redirects).
+5
View File
@@ -54,6 +54,11 @@ This part of the configuration concerns anything that can affect the whole site.
- `"all"` (default): every file that isn't ignored.
- `"referenced"`: only files a published page links to or embeds. Use this with [[ExplicitPublish]] or [[private pages|drafts]], so that files only unpublished notes use stay private.
- Files that Quartz renders as pages themselves (e.g. `.base` and `.canvas` files) are never copied as raw assets.
- `slugs`: how file paths become URLs.
- `stripDiacritics`: `true` strips accents and other diacritics from page, folder and file URLs, e.g. `české/čeština.md` is published at `/ceske/cestina` instead of `/české/čeština` (which browsers show as `%C4%8Desk%C3%A9/...` when copied). Off by default.
- Links keep working as written in your notes: `[[čeština]]`, `[[české/čeština#Nadpis]]` and embeds like `![[obrázek.png]]` resolve to the stripped addresses. Aliases and `permalink`s are stripped the same way. Heading anchors (`#Nadpis`) keep their diacritics. Tag pages and the pages plugins generate from files (canvas, bases, …) are stripped too with `@quartz-community/utils` 1.3 or newer; with older versions they keep their diacritics.
- Only combining accents (`á č é ů …`) are removed. Letters without a decomposition (`ø`, `ł`, `ß`, `æ`) and non-Latin scripts (Chinese, Japanese, Korean, Arabic, Devanagari, …) are kept as they are.
- Turning it on changes the URLs of existing pages; links shared elsewhere to the old addresses will 404 unless you add the old addresses as `aliases`.
- `ignorePatterns`: a list of [glob](<https://en.wikipedia.org/wiki/Glob_(programming)>) patterns that Quartz should ignore and not search through when looking for files inside the `content` folder. See [[private pages]] for more details.
- `theme`: configure how the site looks.
- `fontOrigin`: where to load fonts from.
+10
View File
@@ -109,6 +109,16 @@ export interface GlobalConfiguration {
* - "referenced": Only copy assets referenced by published pages
*/
publishAssets?: "all" | "referenced"
/** How file paths become URLs. */
slugs?: SlugsConfig
}
export interface SlugsConfig {
/**
* Strip accents and other diacritics from generated slugs (`české/čeština.md` →
* `ceske/cestina`), aliases and permalinks; links are resolved the same way. Off by default.
*/
stripDiacritics?: boolean
}
/** Shared by every built-in: `enabled: false` turns it off (e.g. to replace it with a plugin). */
+39 -1
View File
@@ -34,7 +34,8 @@ import {
import type { PluginJsonEntry } from "../loader/types"
import type { BuildCtx } from "../../util/ctx"
import type { ContentDetails } from "../types"
import type { FullSlug } from "../../util/path"
import type { FullSlug, SimpleSlug } from "../../util/path"
import { setSlugOptions } from "../../util/path"
import type { ProcessedContent } from "../vfile"
const entry = (source: string, extra: Partial<PluginJsonEntry> = {}): PluginJsonEntry => ({
@@ -365,6 +366,43 @@ describe("links built-in", () => {
assert.deepStrictEqual(file.data.links?.sort(), ["folder/sibling", "t"])
})
test("slugs.stripDiacritics: link targets are stripped like the slugs they point at (#2410)", () => {
setSlugOptions({ stripDiacritics: true })
try {
const img: Element = {
type: "element",
tagName: "img",
properties: { src: "obr%C3%A1zek.png" },
children: [],
}
const { els, file } = run(
[a("./%C4%8Ce%C5%A1tina#%C4%8Cesk%C3%BD-nadpis", "Čeština"), a("Příliš"), img],
"ceske/page",
{ markdownLinkResolution: "shortest" },
["ceske/page", "ceske/cestina", "jine/prilis", "ceske/obrazek.png"],
)
const [cestina, prilis] = els.filter((e) => e.tagName === "a")
assert.strictEqual(cestina.properties.href, "../ceske/cestina#český-nadpis")
assert.ok(!(cestina.properties.className as string[]).includes("broken"))
assert.strictEqual(prilis.properties.href, "../jine/prilis")
assert.strictEqual(
els.find((e) => e.tagName === "img")!.properties.src,
"../ceske/obrazek.png",
)
assert.ok(file.data.links?.includes("ceske/cestina" as SimpleSlug))
} finally {
setSlugOptions(undefined)
}
})
test("without slugs.stripDiacritics link targets keep their diacritics", () => {
const { els } = run([a("Příliš")], "page", { markdownLinkResolution: "shortest" }, [
"page",
"jine/příliš",
])
assert.strictEqual(els[0].properties.href, "./jine/příliš")
})
test("footnote anchors stay internal without Obsidian's note-link class", () => {
const fn = (props: Record<string, unknown>): Element => ({
type: "element",
+25 -1
View File
@@ -14,6 +14,8 @@ import {
resolveRelative,
simplifySlug,
slugifyFilePath,
applySlugOptions,
getSlugOptions,
splitAnchor,
stripSlashes,
transformLink,
@@ -86,6 +88,28 @@ export function pageExists(allSlugs: readonly string[], full: string): boolean {
return false
}
/**
* Link targets are written as in the vault (`[[Čeština]]`, `../české/x.png`). With
* `configuration.slugs.stripDiacritics` the pages and files they point at have stripped slugs,
* so the path part of the target is stripped the same way before it is resolved (wikilinks
* from obsidian-flavored-markdown are slugged with the plain rules first). The `#anchor` is
* left alone: heading ids keep their diacritics.
*/
function slugOptionsOnLinkPath(raw: string): string {
if (!getSlugOptions().stripDiacritics) return raw
const hash = raw.indexOf("#")
const linkPath = hash === -1 ? raw : raw.slice(0, hash)
const anchor = hash === -1 ? "" : raw.slice(hash)
let decoded = linkPath
try {
decoded = decodeURI(linkPath)
} catch {
// not percent-encoded (or malformed): strip as written
}
const stripped = applySlugOptions(decoded)
return stripped === decoded ? raw : stripped + anchor
}
export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
const opts = { ...linksDefaults, ...userOpts }
return {
@@ -111,7 +135,7 @@ export const Links: QuartzTransformerPlugin<LinksConfig> = (userOpts) => {
: fileSlug
const rebase = targets.size > 0 || pathSlug !== fileSlug
const resolveLink = (raw: string): RelativeURL => {
const rel = transformLink(pathSlug, raw, transformOptions)
const rel = transformLink(pathSlug, slugOptionsOnLinkPath(raw), transformOptions)
if (!rebase) return rel
const hash = rel.indexOf("#")
const anchor = hash === -1 ? "" : rel.slice(hash)
+4
View File
@@ -61,6 +61,7 @@ import {
import { collectPluginConfigWarnings, printPluginConfigWarnings } from "./option-validation"
import { componentRegistry, RegisteredComponent } from "../../components/registry"
import { frameRegistry } from "../../components/frames/registry"
import { setSlugOptions } from "../../util/path"
import { getCondition, getAllConditionNames } from "./conditions"
import {
LAYOUT_SLOTS,
@@ -365,6 +366,7 @@ export async function loadQuartzConfig(
if (!json) {
// Fallback: import old-style config directly
const oldConfig = await import("../../../quartz")
setSlugOptions(oldConfig.default?.configuration?.slugs)
return oldConfig.default
}
@@ -372,6 +374,8 @@ export async function loadQuartzConfig(
...(json.configuration as unknown as GlobalConfiguration),
...configOverrides,
}
// before anything computes a slug (this runs in the main thread and in every worker)
setSlugOptions(configuration.slugs)
// Entries of official plugins that are now built into core (crawl-links, remove-draft,
// content-index) are handled by the built-ins below and never installed or loaded.
+22 -1
View File
@@ -16,7 +16,7 @@ import {
} from "./dispatcher"
import { QuartzPageTypePluginInstance } from "../types"
import { QuartzComponent } from "../../components/types"
import { FilePath, FullSlug, SimpleSlug } from "../../util/path"
import { FilePath, FullSlug, SimpleSlug, setSlugOptions } from "../../util/path"
import { Root as HtmlRoot } from "hast"
import { BuildCtx } from "../../util/ctx"
import { defaultProcessedContent } from "../vfile"
@@ -278,6 +278,27 @@ describe("generateVirtualPages", () => {
assert.strictEqual(ctx.virtualPages.length, 2)
})
test("slugs.stripDiacritics moves folder pages to the stripped folder slug (#2410)", async () => {
setSlugOptions({ stripDiacritics: true })
try {
const entries = await generateVirtualPages(
[makePageType({ generate: () => [page("české/index"), page("tags/čeština")] })],
[],
makeCtx(),
{ head: StubHead },
{},
)
// tag pages keep their slugs: tag links are slugged by the plugins that render them
assert.deepStrictEqual(
entries.map((e) => e.vpSlug),
["ceske/index", "tags/čeština"],
)
assert.strictEqual(entries[0].vfile.data.slug, "ceske/index")
} finally {
setSlugOptions(undefined)
}
})
test("keeps the 404 page out of ctx.virtualPages", async () => {
const ctx = makeCtx()
const entries = await generateVirtualPages(
+4 -1
View File
@@ -15,6 +15,7 @@ import {
pathToRoot,
simplifySlug,
slugifyFilePath,
applySlugOptions,
} from "../../util/path"
import { ProcessedContent, defaultProcessedContent } from "../vfile"
import { write } from "../emitters/helpers"
@@ -215,7 +216,9 @@ export async function generateVirtualPages(
const layout = resolveLayout(pt, defaults, byPageType)
const fileBacked = (pt.fileExtensions?.length ?? 0) > 0
for (const vp of virtualPages) {
const vpSlug = vp.slug as FullSlug
// A folder's page lives at the folder's slug; with `slugs.stripDiacritics` that is the
// stripped one, whatever the page type computed from the file path (folder-page).
const vpSlug = (vp.slug.endsWith("/index") ? applySlugOptions(vp.slug) : vp.slug) as FullSlug
const vpRelativePath = (vpSlug + ".md") as FilePath
const [tree, vfile] = defaultProcessedContent({
slug: vpSlug,
+12
View File
@@ -195,6 +195,18 @@
"default": "all",
"description": "Controls which assets are copied to public. \"all\" copies all non-markdown files; \"referenced\" only copies assets referenced by published pages"
},
"slugs": {
"type": "object",
"additionalProperties": false,
"description": "How file paths become URLs (slugs).",
"properties": {
"stripDiacritics": {
"type": "boolean",
"default": false,
"description": "Strip accents and other diacritics from generated slugs (české/čeština.md → ceske/cestina). Applies to file and folder names, aliases and permalinks; links are resolved the same way."
}
}
},
"frontmatter": {
"description": "Built-in frontmatter parsing: titles, tags, aliases, dates, drafts. Default order 0.",
"oneOf": [
+47
View File
@@ -392,3 +392,50 @@ describe("resolveRelative", () => {
assert.strictEqual(path.resolveRelative("abc/def" as FullSlug, "ghi/" as SimpleSlug), "../ghi/")
})
})
describe("slugs.stripDiacritics (#2410)", () => {
const withStrip = <T>(fn: () => T): T => {
path.setSlugOptions({ stripDiacritics: true })
try {
return fn()
} finally {
path.setSlugOptions(undefined)
}
}
test("off by default: slugs keep their diacritics", () => {
assert.strictEqual(path.slugifyFilePath("české/čeština.md" as path.FilePath), "české/čeština")
})
test("strips diacritics from folder and file names", () => {
withStrip(() => {
const slug = (fp: string) => path.slugifyFilePath(fp as path.FilePath)
assert.strictEqual(slug("české/Čeština.md"), "ceske/cestina")
assert.strictEqual(slug("Příliš žluťoučký kůň.md"), "prilis-zlutoucky-kun")
assert.strictEqual(slug("Café/Crème brûlée.md"), "cafe/creme-brulee")
assert.strictEqual(slug("Tiếng Việt.md"), "tieng-viet")
assert.strictEqual(slug("obrázek.PNG"), "obrazek.PNG")
// decomposed input (macOS file names) gives the same slug
assert.strictEqual(slug("čeština.md"), "cestina")
})
})
test("keeps scripts whose marks are not Latin diacritics", () => {
withStrip(() => {
const slug = (fp: string) => path.slugifyFilePath(fp as path.FilePath)
assert.strictEqual(slug("한국어.md"), "한국어")
assert.strictEqual(slug("がぎぐ.md"), "がぎぐ")
assert.strictEqual(slug("हिन्दी.md"), "हिन्दी")
assert.strictEqual(slug("日本語/中文.md"), "日本語/中文")
// letters without a decomposition are kept
assert.strictEqual(slug("Łódź ø ß.md"), "łodz-ø-ß")
})
})
test("is idempotent", () => {
withStrip(() => {
const once = path.slugifyFilePath("Čeština/Ž.md" as path.FilePath)
assert.strictEqual(path.slugifyFilePath(`${once}.md` as path.FilePath), once)
})
})
})
+56 -1
View File
@@ -6,7 +6,6 @@ export {
isRelativeURL,
isAbsoluteURL,
getFullSlug,
slugifyFilePath,
simplifySlug,
joinSegments,
endsWith,
@@ -35,6 +34,62 @@ export type {
// --- v5-specific exports below ---
import { slugifyFilePath as slugifyFilePathBase } from "@quartz-community/utils"
import * as quartzUtils from "@quartz-community/utils"
import type { FilePath as _FilePath, FullSlug as _FullSlug } from "@quartz-community/utils"
export interface SlugOptions {
/** Strip accents and other diacritics (`č` → `c`, `é` → `e`) from generated slugs. */
stripDiacritics?: boolean
}
let slugOptions: SlugOptions = {}
/**
* Set how core turns file paths into slugs (`configuration.slugs`). Called when the config is
* loaded, in the main thread and in every worker, so all slugs of a build agree.
*/
export function setSlugOptions(options: SlugOptions | undefined): void {
slugOptions = { ...(options ?? {}) }
// @quartz-community/utils 1.3+ applies the same options to every slug it computes, for core
// and for plugins (tag pages, canvas, bases, alias-redirects …). Older utils lack it; core's
// own wrapper below and the links/dispatcher handling then cover core's slugs. Stripping is
// idempotent, so both applying is harmless. (Drop the wrapper once core requires utils 1.3.)
const utilsSetter = (quartzUtils as { setSlugOptions?: (o: SlugOptions | undefined) => void })
.setSlugOptions
utilsSetter?.(slugOptions)
}
export function getSlugOptions(): Readonly<SlugOptions> {
return slugOptions
}
/**
* Remove combining diacritical marks (U+0300–U+036F) after canonical decomposition:
* `Čeština` → `Cestina`, `Ελληνικά` → `Ελληνικα`. The string is recomposed afterwards, so
* scripts whose marks are outside that block (Hangul, kana with dakuten, Devanagari, Arabic)
* keep their usual form. Letters without a decomposition (`ø`, `ł`, `ß`, `æ`) are kept.
*/
export function stripDiacritics(s: string): string {
return s
.normalize("NFD")
.replace(/[\u0300-\u036f]/g, "")
.normalize("NFC")
}
/** `stripDiacritics` when `configuration.slugs.stripDiacritics` is on, else unchanged. */
export function applySlugOptions(s: string): string {
return slugOptions.stripDiacritics ? stripDiacritics(s) : s
}
/**
* Slug of a content file path (see `@quartz-community/utils`), honouring
* `configuration.slugs` (see setSlugOptions).
*/
export function slugifyFilePath(fp: _FilePath, excludeExt?: boolean): _FullSlug {
return slugifyFilePathBase(applySlugOptions(fp) as _FilePath, excludeExt)
}
export const QUARTZ = "quartz"
// from micromorph/src/utils.ts