29
29
aTagRegexp = regexp .MustCompile (`(?m)(<a[^<]+?>.*?</a>)` )
30
30
hrefRegexp = regexp .MustCompile (`href="[^"]+?"` ) // 图片地址被 auto link
31
31
LocalImgRegexp = regexp .MustCompile (`(?:\s|^)(/static/upload/([a-z0-9]+)\.(jpg|jpe|jpeg|gif|png))\s?` ) // 本地上传的图片
32
- codeBlockRegexp = regexp .MustCompile ("(?s:(`{3} *([^ \n ]+)? \n (.+?) \n `{3}))" )
32
+ codeBlockRegexp = regexp .MustCompile ("(?s)```([ \\ s \\ S]*?)```" ) //"(?s)```(.*?)```"
33
33
langCaptionRegexp = regexp .MustCompile ("([^\\ s`]+)\\ s*(.+)?" )
34
- t4Re = regexp .MustCompile (`\A( {4}|\t)` )
35
- t4Re2 = regexp .MustCompile (`^( {4}|\t)` )
36
34
htmlRe = regexp .MustCompile ("<.*?>|&.*?;" )
37
35
MdImgRe = regexp .MustCompile (`(!\[.*]\(.{10,}\))|([\w./:]*/static/upload/([a-z\d-.]+)\.(jpg|jpe|jpeg|gif|png))` )
38
36
)
@@ -103,7 +101,7 @@ func ContentFmt(input string) string {
103
101
codeRawMap := map [string ]string {} // 代码块
104
102
if HasCodeBlock (input ) {
105
103
input = codeBlockRegexp .ReplaceAllStringFunc (input , func (s string ) string {
106
- s = strings . TrimSpace (s ) // important
104
+ s = s [ 3 : len (s )- 3 ] // 去掉两头 ```
107
105
// 获取并代码头部信息及处理代码高亮 html 代码
108
106
lines := StringSplit (s , "\n " )
109
107
// 至少 3 行
@@ -116,20 +114,22 @@ func ContentFmt(input string) string {
116
114
caption = v [2 ] // fmt.Sprintf(`<figcaption><span>%s</span></figcaption>`, v[2])
117
115
}
118
116
// 最后一行 ``` 舍弃
117
+ // 若每行都有相同的空格则去掉
118
+ prefixSpace , n := GetLeadingSpaces (lines [1 ])
119
+ if n > 0 {
120
+ for i := 1 ; i < len (lines )- 1 ; i ++ {
121
+ if len (lines [i ]) >= n && lines [i ][:n ] == prefixSpace {
122
+ lines [i ] = lines [i ][n :]
123
+ }
124
+ }
125
+ }
119
126
// 纯代码
120
127
codeRaw := strings .Join (lines [1 :len (lines )- 1 ], "\n " )
121
- // 替换掉每行多余的空格
122
- if t4Re .MatchString (codeRaw ) {
123
- codeRaw = t4Re2 .ReplaceAllString (codeRaw , "" )
124
- }
125
128
126
129
source := []string {`<figure class="code">` }
127
130
128
131
langName , hlText := ColorCode (codeRaw , lang )
129
132
130
- //if len(caption) > 0 {
131
- // source = append(source, caption)
132
- //}
133
133
if len (langName ) > 0 || len (caption ) > 0 {
134
134
source = append (source , `<figcaption><span>` + langName + ": " + caption + `</span></figcaption>` )
135
135
}
@@ -140,7 +140,7 @@ func ContentFmt(input string) string {
140
140
codeTag := codeBlockTag + strconv .Itoa (len (codeRawMap )) + "]"
141
141
codeRawMap [codeTag ] = strings .Join (source , "\n " )
142
142
143
- return codeTag
143
+ return " \n \n " + codeTag + " \n \n "
144
144
}
145
145
146
146
return s
0 commit comments