Commit 51fed0c

HPCesia <me@hpcesia.com>
2025-02-07 14:22:23
feat: heading shift plugin
Add an optional remark plugin to shift headings -- start from h2.
1 parent 84f56fe
Changed files (3)
src/content/posts/markdown.md
@@ -8,7 +8,18 @@ published: 2021-07-09 12:00:00
 
 Here is an example of a Markdown blog post.
 
-# Heading Level 1
+# Heading Level 1 (I Suggest That DO NOT Use This Level)
+
+Heading Level 1 is reserved for the post title, so you should start with Heading Level 2.
+
+<details>
+  <summary>Or</summary>
+  <p>
+    Add <code>import remarkHeadingShift from './src/plugins/remark-heading-shift.mjs';</code> to the top of <code>astro.config.mjs</code> and uncomment the first line of the <code>remarkPlugins</code> array, then you can use Heading Level 1 as a regular heading in your blog posts.
+  </p>
+</details>
+
+## Heading Level 2
 
 You can use GitHub Flavored Markdown to format your blog posts. For example, you can use **bold**, _italic_ and ~~strikethrough~~ text, create a [link](https://example.com) or just write a raw URL like https://example.com, and add images:
 
@@ -47,7 +58,7 @@ $$
  \int_{-\infty}^{+\infty} e^{-x^2} \mathrm{d}x = \sqrt{\pi}
 $$
 
-## Heading Level 2
+### Heading Level 3
 
 Other GitHub Flavored Markdown features include:
 
@@ -87,3 +98,9 @@ You can also add footnotes[^1] or [reference links][1].
 > This is a caution.
 
 And that's it!
+
+#### I Think You Want to Have a Look at Heading Level 4
+
+##### Too Many Nested Headings is Not a Good Idea, but Here is Heading Level 5
+
+###### Heading Level 6 is the Last One, Why You Want to Use This?
src/plugins/remark-heading-shift.mjs
@@ -0,0 +1,17 @@
+import { visit } from 'unist-util-visit';
+
+/**
+ * Remark plugin to shift all heading levels down by one (starting from h2)
+ *
+ * Remark 插件,将所有标题层级下移一级(从 h2 开始)
+ *
+ * @type {import('unified').Plugin}
+ */
+export default function remarkHeadingShift() {
+  return (tree) => {
+    visit(tree, 'heading', (node) => {
+      // 将所有标题层级加1(最大到6)
+      node.depth = Math.min(node.depth + 1, 6);
+    });
+  };
+}
astro.config.mjs
@@ -34,6 +34,7 @@ export default defineConfig({
       defaultColor: false,
     },
     remarkPlugins: [
+      // remarkHeadingShift,
       remarkMath,
       remarkReadingTime,
       remarkExcerpt,