设置 Hugo 的代码高亮

前提条件

首先我们要保证 Hugo 的版本是高于 v0.65.0 的,查询方法如下:

1
2
$ hugo version
Hugo Static Site Generator v0.70.0-7F47B99E windows/amd64 BuildDate: 2020-05-06T11:17:50Z

上面查询,我的版本是 v0.70.0 如果你的版本低于 v0.65.0 则不支持我们今天要设置的代码高亮,请先升级版本。

Hugov0.65.0 版本之后使用了 Chroma 代码高亮插件,它是一个 Go 语言实现的非常漂亮并能快速生成的代码高亮工具。

如何配置

默认的代码高亮配置文件如下,你可以复制到你的配置文件内进行修改:

yaml 格式的配置文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
markup:
  highlight:
    codeFences: true
    guessSyntax: false
    hl_Lines: ""
    lineNoStart: 1
    lineNos: false
    lineNumbersInTable: true
    noClasses: true
    style: monokai
    tabWidth: 4

toml 格式的配置文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
[markup]
  [markup.highlight]
    codeFences = true
    guessSyntax = false
    hl_Lines = ""
    lineNoStart = 1
    lineNos = false
    lineNumbersInTable = true
    noClasses = true
    style = "monokai"
    tabWidth = 4

json 格式的配置文件:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
{
   "markup": {
      "highlight": {
         "codeFences": true,
         "guessSyntax": false,
         "hl_Lines": "",
         "lineNoStart": 1,
         "lineNos": false,
         "lineNumbersInTable": true,
         "noClasses": true,
         "style": "monokai",
         "tabWidth": 4
      }
   }
}

配置文件中各个设置项的含义如下:

  • codeFences:代码围栏功能,这个功能一般都要设为 true 的,不然很难看,就是干巴巴的代码文字,没有颜色。
  • guessSyntax:猜测语法,这个功能建议设置为 true, 如果你没有设置要显示的语言则会自动匹配。
  • hl_Lines:高亮的行号,一般这个不设置,因为每个代码块我们可能希望让高亮的地方不一样。
  • lineNoStart:行号从编号几开始,一般从 1 开始。
  • lineNos:是否显示行号,我比较喜欢显示,所以我设置的为 true.
  • lineNumbersInTable:使用表来格式化行号和代码,而不是 <span> 标签。这个属性一般设置为 true.
  • noClasses:使用 class 标签,而不是内嵌的内联样式 <style> 属性。我这里设置的是 true 因为我测试设置为 false 会有问题。
  • style:样式风格,下面会逐一介绍。
  • tabWidth:代码缩进字符数,或者说制表符的长度。

样式风格

缩小迷你版样式:https://xyproto.github.io/splash/docs/all.html

放大正常版样式:https://xyproto.github.io/splash/docs/longer/all.html

选择一个你喜欢的风格,设置到 style 属性中,例如我设置的是 dracula 风格。

自定义样式

如果某些代码块中你需要特殊设置,例如设置行号从某个位置开始,或者某几行代码高亮等。

例如这样写:

```go {hl_lines=[8,“15-17”],linenostart=199}

// … code

```

显示结果如下:

199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
// GetTitleFunc returns a func that can be used to transform a string to
// title case.
//
// The supported styles are
//
// - "Go" (strings.Title)
// - "AP" (see https://www.apstylebook.com/)
// - "Chicago" (see https://www.chicagomanualofstyle.org/home.html)
//
// If an unknown or empty style is provided, AP style is what you get.
func GetTitleFunc(style string) func(s string) string {
  switch strings.ToLower(style) {
  case "go":
    return strings.Title
  case "chicago":
    return transform.NewTitleConverter(transform.ChicagoStyle)
  default:
    return transform.NewTitleConverter(transform.APStyle)
  }
}

可以看到行号从 199 开始了,然后第 8 行和 第 15~17 行高亮了。

支持的语法

ABAP

ABAP, abap

ABNF

abnf

ANTLR

antlr

APL

apl

ActionScript

actionscript, as

ActionScript 3

actionscript3, as, as3

Ada

ada, ada2005, ada95, adb, ads

Angular2

ng2

ApacheConf

aconf, apache, apacheconf, conf, htaccess

AppleScript

applescript

Arduino

arduino, ino

Awk

awk, gawk, mawk, nawk

BNF

bnf

Ballerina

bal, ballerina

Base Makefile

*, bsdmake, mak, make, makefile, mf, mk

Bash

bash, bash_*, bashrc, ebuild, eclass, exheres-0, exlib, ksh, sh, shell, zsh, zshrc

Batchfile

bat, batch, cmd, dosbatch, winbatch

BibTeX

bib, bibtex

BlitzBasic

b3d, bb, blitzbasic, bplus, decls

Brainfuck

b, bf, brainfuck

C

c, h, idc

C#

c#, cs, csharp

C++

C, CPP, H, c++, cc, cp, cpp, cxx, h++, hh, hpp, hxx

CFEngine3

cf, cf3, cfengine3

CMake

cmake, txt

COBOL

COB, CPY, cob, cobol, cpy

CSS

css

Cap’n Proto

capnp

Cassandra CQL

cassandra, cql

Ceylon

ceylon

ChaiScript

chai, chaiscript

Cheetah

cheetah, spitfire, spt, tmpl

Clojure

clj, clojure

CoffeeScript

coffee, coffee-script, coffeescript

Common Lisp

cl, common-lisp, lisp

Coq

coq, v

Crystal

cr, crystal

Cython

cython, pxd, pxi, pyrex, pyx

D

d, di

DTD

dtd

Dart

dart

Diff

diff, patch, udiff

Django/Jinja

django, jinja

Docker

docker, dockerfile

EBNF

ebnf

Elixir

elixir, ex, exs

Elm

elm

EmacsLisp

el, elisp, emacs, emacs-lisp

Erlang

erl, erlang, es, escript, hrl

FSharp

fs, fsharp, fsi

Factor

factor

Fish

fish, fishshell, load

Forth

forth, frt, fs, fth

Fortran

F03, F90, f03, f90, fortran

GAS

S, asm, gas, s

GDScript

gd, gdscript

GLSL

frag, geo, glsl, vert

Genshi

genshi, kid, xml+genshi, xml+kid

Genshi HTML

html+genshi, html+kid

Genshi Text

genshitext

Gnuplot

gnuplot, plot, plt

Go

go, golang

Go HTML Template

go-html-template

Go Text Template

go-text-template

GraphQL

gql, graphql, graphqls

Groovy

gradle, groovy

HCL

hcl

HTML

htm, html, xhtml, xslt

HTTP

http

Handlebars

handlebars

Haskell

haskell, hs

Haxe

haxe, hx, hxsl

Hexdump

hexdump

Hy

hy, hylang

INI

cfg, dosini, gitconfig, inf, ini

Idris

idr, idris

Igor

igor, igorpro, ipf

Io

io

J

ijs, j

JSON

json

Java

java

JavaScript

javascript, js, jsm

Julia

jl, julia

Jungle

jungle

Kotlin

kotlin, kt

LLVM

ll, llvm

Lighttpd configuration file

lighttpd, lighty

Lua

lua, wlua

MLIR

mlir

Mako

mako, mao

Mason

m, mason, mc, mhtml, mi

Mathematica

cdf, ma, mathematica, mma, nb, nbp

Matlab

m, matlab

MiniZinc

MZN, dzn, fzn, minizinc, mzn

Modula-2

def, m2, mod, modula2

MonkeyC

mc, monkeyc

MorrowindScript

morrowind, mwscript

MySQL

mysql, sql

Myghty

myghty, myt

NASM

ASM, asm, nasm

Newspeak

newspeak, ns2

Nginx configuration file

conf, nginx

Nim

nim, nimrod

Nix

nix, nixos

OCaml

ml, mli, mll, mly, ocaml

Objective-C

h, m, obj-c, objc, objective-c, objectivec

Octave

m, octave

OpenSCAD

openscad, scad

Org Mode

org, orgmode

PHP

inc, php, php3, php4, php5, php[345]

PL/pgSQL

plpgsql

POVRay

inc, pov

PacmanConf

conf, pacmanconf

Perl

perl, pl, pm, t

Pig

pig

PkgConfig

pc, pkgconfig

PostScript

eps, postscr, postscript, ps

PostgreSQL SQL dialect

postgres, postgresql

PowerShell

posh, powershell, ps1, psm1

Prolog

ecl, pl, pro, prolog

Protocol Buffer

proto, protobuf

Puppet

pp, puppet

Python

py, python, pyw, sage, sc, tac

Python 3

py3, python3

QBasic

BAS, bas, basic, qbasic

R

R, Renviron, Rhistory, Rprofile, S, r, s, splus

Racket

racket, rkt, rktd, rktl

Ragel

ragel

Rexx

arexx, rex, rexx, rx

Ruby

duby, gemspec, rake, rb, rbw, rbx, ruby

Rust

in, rs, rust

SCSS

scss

SPARQL

rq, sparql

SQL

sql

SYSTEMD

service, systemd

Sass

sass

Scala

scala

Scheme

scheme, scm, ss

Scilab

sce, sci, scilab, tst

Smalltalk

smalltalk, squeak, st

Smarty

smarty, tpl

Snobol

snobol

Solidity

sol, solidity

SquidConf

conf, squid, squid.conf, squidconf

Standard ML

fun, sig, sml

Swift

swift

TASM

ASM, asm, tasm

TOML

toml

TableGen

tablegen, td

Tcl

rvt, tcl

Tcsh

csh, tcsh

TeX

aux, latex, tex, toc

Termcap

src, termcap

Terminfo

src, terminfo

Terraform

terraform, tf

Thrift

thrift

TradingView

tradingview, tv

Transact-SQL

t-sql, tsql

Turing

tu, turing

Turtle

ttl, turtle

Twig

twig

TypeScript

ts, tsx, typescript

TypoScript

ts, txt, typoscript

TypoScriptCssData

typoscriptcssdata

TypoScriptHtmlData

typoscripthtmldata

VB.net

bas, vb, vb.net, vbnet

VHDL

vhd, vhdl

VimL

exrc, gvimrc, vim, vimrc

WDTE

wdte

XML

rss, svg, wsdl, wsf, xml, xsd, xsl, xslt

Xorg

conf, xorg.conf

YAML

yaml, yml

cfstatement

cfs

markdown

markdown, md, mkd

plaintext

no-highlight, plain, text, txt

reStructuredText

rest, restructuredtext, rst

react

jsx, react

reg

reg, registry

systemverilog

sv, svh, systemverilog

verilog

v, verilog

vue

vue, vuejs