2020-10-05 10:23:57 +08:00
|
|
|
// Copyright 2020 The Gitea Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a MIT-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
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"
|
2021-03-12 20:28:46 +08:00
|
|
|
"golang.org/x/crypto/ssh/terminal"
|
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 {
|
|
|
|
renderer, err := glamour.NewTermRenderer(
|
|
|
|
glamour.WithAutoStyle(),
|
|
|
|
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
|
|
|
|
if terminal.IsTerminal(fd) {
|
|
|
|
if w, _, err := terminal.GetSize(fd); err == nil {
|
|
|
|
width = w
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if width > 120 {
|
|
|
|
width = 120
|
|
|
|
}
|
|
|
|
return width
|
|
|
|
}
|