2020-10-05 10:23:57 +08:00
|
|
|
// Copyright 2020 The Gitea Authors. All rights reserved.
|
2023-09-08 09:40:02 +08:00
|
|
|
// SPDX-License-Identifier: MIT
|
2020-10-05 10:23:57 +08:00
|
|
|
|
|
|
|
package print
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-03-12 20:28:46 +08:00
|
|
|
"os"
|
2020-10-05 10:23:57 +08:00
|
|
|
|
|
|
|
"github.com/charmbracelet/glamour"
|
2023-04-30 11:43:26 +08:00
|
|
|
"golang.org/x/term"
|
2020-10-05 10:23:57 +08:00
|
|
|
)
|
|
|
|
|
2020-12-08 18:28:54 +08:00
|
|
|
// outputMarkdown prints markdown to stdout, formatted for terminals.
|
2020-10-05 10:23:57 +08:00
|
|
|
// If the input could not be parsed, it is printed unformatted, the error
|
|
|
|
// is returned anyway.
|
2021-03-12 20:28:46 +08:00
|
|
|
func outputMarkdown(markdown string, baseURL string) error {
|
2022-09-14 02:35:15 +08:00
|
|
|
var styleOption glamour.TermRendererOption
|
|
|
|
if IsInteractive() {
|
|
|
|
styleOption = glamour.WithAutoStyle()
|
|
|
|
} else {
|
|
|
|
styleOption = glamour.WithStandardStyle("notty")
|
|
|
|
}
|
|
|
|
|
2021-03-12 20:28:46 +08:00
|
|
|
renderer, err := glamour.NewTermRenderer(
|
2022-09-14 02:35:15 +08:00
|
|
|
styleOption,
|
2021-03-12 20:28:46 +08:00
|
|
|
glamour.WithBaseURL(baseURL),
|
2022-09-14 01:52:44 +08:00
|
|
|
glamour.WithPreservedNewLines(),
|
2021-03-12 20:28:46 +08:00
|
|
|
glamour.WithWordWrap(getWordWrap()),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf(markdown)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
out, err := renderer.Render(markdown)
|
2020-10-05 10:23:57 +08:00
|
|
|
if err != nil {
|
|
|
|
fmt.Printf(markdown)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
fmt.Print(out)
|
|
|
|
return nil
|
|
|
|
}
|
2021-03-12 20:28:46 +08:00
|
|
|
|
|
|
|
// stolen from https://github.com/charmbracelet/glow/blob/e9d728c/main.go#L152-L165
|
|
|
|
func getWordWrap() int {
|
|
|
|
fd := int(os.Stdout.Fd())
|
|
|
|
width := 80
|
2023-04-30 11:43:26 +08:00
|
|
|
if term.IsTerminal(fd) {
|
|
|
|
if w, _, err := term.GetSize(fd); err == nil {
|
2021-03-12 20:28:46 +08:00
|
|
|
width = w
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if width > 120 {
|
|
|
|
width = 120
|
|
|
|
}
|
|
|
|
return width
|
|
|
|
}
|