前言

优化代码块:

  • 添加语言显示
  • Chroma主题切换
  • 代码块折叠展开

PaperMod 主题默认使用的是 highlight.js, 这是一种由 js 生成的高亮方案。相比 highlight.js, Hugo 官方更倾向使用 Chroma 来生成代码高亮。

Chroma 是由 Go 写的语法高亮工具,其编译速度更快,且 Hugo 内置了 Chroma 工具。 Hugo 关于 Chroma 的文档在 Syntax Highlighting

禁用 Highlight.js

highlight.js 与 Chroma 的样式是冲突的。

通过 params.assets.disableHLJS 禁用 Highlight.js 即可。

1
2
3
params:
  assets:
    disableHLJS: true

高亮配置

官方文档:syntax-highlighting

本文以下面的主题为例:

  • light-theme: monokailight
  • dark-theme: github-dark

config/_default/markup.yaml,增加以下配置:

1
2
3
4
5
6
7
highlight:
    codeFences: true # 代码围栏功能
    tabWidth: 4 # 制表符宽度
    guessSyntax: true # 猜测语法
    lineNos: true # 是否显示行号
    noClasses: false # 是否不生成 CSS 类,即直接嵌套 CSS 内联样式
    lineNumbersInTable: true # 是否在表格中显示行号

生成 CSS 类

1
2
hugo gen chromastyles --style=monokailight > assets/css/includes/chroma-syntax-light.scss
hugo gen chromastyles --style=github-dark > assets/css/includes/chroma-syntax-dark.scss

通过 hugo gen 命令可以生成 Chroma 的样式。

Hugo 支持的代码高亮样式:Chroma Style Gallery

明暗代码块格式切换

assets/css/extended 创建一个 _themes.scss 来控制明暗模式的切换:

1
2
3
4
5
6
7
8
9
// Syntax for themes light
.light {
    @import "syntax-light";
}

// Syntax for themes dark
.dark {
    @import "syntax-dark";
}

代码折叠

由于在找寻代码折叠功能部分,发现 Mac 风格的代码样式,于是采用下面的样式。

复制主题的 layouts/partials/footer.html 到根目录下,找到其中代码块复制功能部分,大概在 95 行左右,替换代码:

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
{{- if (and (eq .Kind "page") (ne .Layout "archives") (ne .Layout "search") (or (.Param "ShowCodeCopyButtons") (.Param "ShowMacDots") (.Param "ShowCodeLang") (.Param "ShowExpandButton"))) }}
<style>
    .code-toolbar {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 5px 10px;
        {{/*  background: var(--code-block-bg);  */}}
        background: #232323;
        border-top-left-radius: 5px;
        border-top-right-radius: 5px;
        font-size: 0.8em;
        position: relative;
    }
    .mac-dots {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        background-color: #ff5f56;
        box-shadow: 20px 0 0 #ffbd2e, 40px 0 0 #27c93f;
        margin-right: 5px;
    }
    .lang-label {
        flex-grow: 1;
        text-align: center;
        margin: 0 5px;
        color: rgba(255,255,255,.8);
    }
    .toolbar-group {
        display: flex;
        align-items: center;
    }
    .expand-button, .copy-code {
        background: none;
        border: none;
        cursor: pointer;
        padding: 0 5px;
    }
    .highlight {
        position: relative;
    }
    .highlight.collapsible {
        max-height: {{ .Site.Params.codeMaxHeight | default "300px" }};
        overflow: hidden;
    }
    .highlight.expanded {
        max-height: none;
    }
    .highlight pre {
        margin-bottom: 0;
    }
    .expand-button {
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        background-color: transparent;
        padding: 5px 10px;
        border-radius: 5px 5px 0 0;
        display: none;
        height: 30px;
        &:hover {
            background: rgba(255,255,255,.1);
            color: #fff;
        }
    }
    .highlight.collapsible .expand-button {
        display: block;
    }
    .highlight table {
        margin-bottom: 0;
    }
    .post-content pre code {
        overflow-x: auto;
        overflow-y: hidden;
    }
</style>
<script>
    document.addEventListener('DOMContentLoaded', () => {
        const codeBlocks = document.querySelectorAll('.highlight');
        const maxHeight = parseInt('{{ .Site.Params.codeMaxHeight | default "300" }}');
        
        codeBlocks.forEach((block) => {
            const pre = block.querySelector('pre');
            const code = pre.querySelector('code');
            // Determine if a toolbar is needed
            let toolbarNeeded = false;
            if ({{ .Param "ShowMacDots" }} || {{ .Param "ShowCodeLang" }}) {
                toolbarNeeded = true;
            }
            if (toolbarNeeded) {
                const toolbar = document.createElement('div');
                toolbar.classList.add('code-toolbar');
                block.insertBefore(toolbar, block.firstChild);
                const leftGroup = document.createElement('div');
                leftGroup.classList.add('toolbar-group');
                toolbar.appendChild(leftGroup);
                const rightGroup = document.createElement('div');
                rightGroup.classList.add('toolbar-group');
                toolbar.appendChild(rightGroup);
                if ({{ .Param "ShowMacDots" }}) {
                    const macDots = document.createElement('div');
                    macDots.classList.add('mac-dots');
                    leftGroup.appendChild(macDots);
                }
                if ({{ .Param "ShowCodeLang" }}) {
                    let language = '';
                    const possibleElements = [
                        block,
                        block.querySelector('code'),
                        block.querySelector('pre > code'),
                        block.querySelector('pre'),
                        block.querySelector('td:nth-child(2) code')
                    ];
                    for (const element of possibleElements) {
                        if (element && element.className) {
                            const elementLanguageClass = element.className.split(' ').find(cls => cls.startsWith('language-'));
                            if (elementLanguageClass) {
                                language = elementLanguageClass.replace('language-', '');
                                break;
                            }
                        }
                    }
                    if (language) {
                        const langLabel = document.createElement('div');
                        langLabel.classList.add('lang-label');
                        langLabel.textContent = language;
                        toolbar.insertBefore(langLabel, rightGroup);
                    }
                }
                if ({{ .Param "ShowCodeCopyButtons" }}) {
                    const copyButton = document.createElement('button');
                    copyButton.classList.add('copy-code');
                    copyButton.innerHTML = '{{- i18n "code_copy" | default "copy" }}';
                    rightGroup.appendChild(copyButton);
                    copyButton.addEventListener('click', () => {
                        let textToCopy = code.textContent;
                        if (code.parentNode.parentNode.parentNode.parentNode.parentNode.nodeName == "TABLE") {
                            textToCopy = Array.from(code.parentNode.parentNode.parentNode.querySelectorAll('td:nth-child(2)'))
                                .map(td => td.textContent)
                                .join('\n');
                        }
                        
                        if ('clipboard' in navigator) {
                            navigator.clipboard.writeText(textToCopy);
                            copyingDone();
                            return;
                        }
                        const textArea = document.createElement('textarea');
                        textArea.value = textToCopy;
                        document.body.appendChild(textArea);
                        textArea.select();
                        try {
                            document.execCommand('copy');
                            copyingDone();
                        } catch (e) { };
                        document.body.removeChild(textArea);
                    });
                    function copyingDone() {
                        copyButton.innerHTML = '{{- i18n "code_copied" | default "copied!" }}';
                        setTimeout(() => {
                            copyButton.innerHTML = '{{- i18n "code_copy" | default "copy" }}';
                        }, 2000);
                    }
                }
            } else if ({{ .Param "ShowCodeCopyButtons" }}) {
                const copyButton = document.createElement('button');
                copyButton.classList.add('copy-code');
                copyButton.innerHTML = '{{- i18n "code_copy" | default "copy" }}';
                if (block.classList.contains("highlight")) {
                    block.appendChild(copyButton);
                } else if (block.parentNode.firstChild == block) {
                    // td containing LineNos
                } else if (code.parentNode.parentNode.parentNode.parentNode.parentNode.nodeName == "TABLE") {
                    // table containing LineNos and code
                    code.parentNode.parentNode.parentNode.parentNode.parentNode.appendChild(copyButton);
                } else {
                    // code blocks not having highlight as parent class
                    code.parentNode.appendChild(copyButton);
                }
                copyButton.addEventListener('click', () => {
                    let textToCopy = code.textContent;
                    if (code.parentNode.parentNode.parentNode.parentNode.parentNode.nodeName == "TABLE") {
                        textToCopy = Array.from(code.parentNode.parentNode.parentNode.querySelectorAll('td:nth-child(2)'))
                            .map(td => td.textContent)
                            .join('\n');
                    }
                    
                    if ('clipboard' in navigator) {
                        navigator.clipboard.writeText(textToCopy);
                        copyingDone();
                        return;
                    }
                    const textArea = document.createElement('textarea');
                    textArea.value = textToCopy;
                    document.body.appendChild(textArea);
                    textArea.select();
                    try {
                        document.execCommand('copy');
                        copyingDone();
                    } catch (e) { };
                    document.body.removeChild(textArea);
                });
                function copyingDone() {
                    copyButton.innerHTML = '{{- i18n "code_copied" | default "copied!" }}';
                    setTimeout(() => {
                        copyButton.innerHTML = '{{- i18n "code_copy" | default "copy" }}';
                    }, 2000);
                }
            }
            if ({{ .Param "ShowExpandButton" }}) {
                const expandButton = document.createElement('button');
                expandButton.classList.add('expand-button');
                expandButton.innerHTML = '&#9660;'; // Down arrow
                block.appendChild(expandButton);
                if (pre.offsetHeight > maxHeight) {
                    block.classList.add('collapsible');
                    expandButton.style.display = 'block';
                    expandButton.addEventListener('click', () => {
                        block.classList.toggle('expanded');
                        expandButton.innerHTML = block.classList.contains('expanded') ? '&#9650;' : '&#9660;';
                    });
                }
            }
        });
    });
</script>
{{- end }}

修改config/_default/markup.yaml,增加以下配置:

1
2
3
4
5
6
highlight:
    ShowMacDots: true # Mac色块
    ShowCodeLang: true # 语言显示
    ShowExpandButton: true # 代码块折叠
    ShowCodeCopyButtons: true # 代码块复制按钮
    codeMaxHeight: "300px" # 代码块最大折叠高度
参考教程