markup: Reimplement pygmentsCodefencesGuessSyntax

Fixes #6565
This commit is contained in:
Bjørn Erik Pedersen
2019-12-02 08:31:23 +01:00
parent d534ce9424
commit 40a092b068
10 changed files with 74 additions and 9 deletions

View File

@@ -58,6 +58,8 @@ type Config struct {
// TabWidth sets the number of characters for a tab. Defaults to 4.
TabWidth int
GuessSyntax bool
}
func (cfg Config) ToHTMLOptions() []html.Option {
@@ -104,6 +106,10 @@ func ApplyLegacyConfig(cfg config.Provider, conf *Config) error {
conf.CodeFences = cfg.GetBool("pygmentsCodeFences")
}
if conf.GuessSyntax == DefaultConfig.GuessSyntax && cfg.IsSet("pygmentsCodefencesGuessSyntax") {
conf.GuessSyntax = cfg.GetBool("pygmentsCodefencesGuessSyntax")
}
if cfg.IsSet("pygmentsOptions") {
if err := applyOptionsFromString(cfg.GetString("pygmentsOptions"), conf); err != nil {
return err

View File

@@ -52,6 +52,14 @@ func highlight(code, lang string, cfg Config) (string, error) {
lexer = lexers.Get(lang)
}
if lexer == nil && cfg.GuessSyntax {
lexer = lexers.Analyse(code)
if lexer == nil {
lexer = lexers.Fallback
}
lang = strings.ToLower(lexer.Config().Name)
}
if lexer == nil {
wrapper := getPreWrapper(lang)
fmt.Fprint(w, wrapper.Start(true, ""))

View File

@@ -84,4 +84,26 @@ LINE5
result, _ = h.Highlight(lines, "bash", "linenos=table")
c.Assert(result, qt.Contains, "<span class=\"lnt\">1\n</span>")
})
c.Run("No language", func(c *qt.C) {
cfg := DefaultConfig
cfg.NoClasses = false
cfg.LineNos = true
h := New(cfg)
result, _ := h.Highlight(lines, "", "")
c.Assert(result, qt.Equals, "<pre><code>LINE1\nLINE2\nLINE3\nLINE4\nLINE5\n</code></pre>")
})
c.Run("No language, guess syntax", func(c *qt.C) {
cfg := DefaultConfig
cfg.NoClasses = false
cfg.GuessSyntax = true
cfg.LineNos = true
cfg.LineNumbersInTable = false
h := New(cfg)
result, _ := h.Highlight(lines, "", "")
c.Assert(result, qt.Contains, "<span class=\"ln\">2</span>LINE2\n<")
})
}