2020-10-04 22:23:57 -04:00
|
|
|
// Copyright 2020 The Gitea Authors. All rights reserved.
|
2023-09-07 21:40:02 -04:00
|
|
|
// SPDX-License-Identifier: MIT
|
2020-10-04 22:23:57 -04:00
|
|
|
|
|
|
|
package print
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-03-12 07:28:46 -05:00
|
|
|
"os"
|
2020-10-04 22:23:57 -04:00
|
|
|
|
|
|
|
"github.com/charmbracelet/glamour"
|
2023-04-29 23:43:26 -04:00
|
|
|
"golang.org/x/term"
|
2020-10-04 22:23:57 -04:00
|
|
|
)
|
|
|
|
|
2020-12-08 05:28:54 -05:00
|
|
|
// outputMarkdown prints markdown to stdout, formatted for terminals.
|
2020-10-04 22:23:57 -04:00
|
|
|
// If the input could not be parsed, it is printed unformatted, the error
|
|
|
|
// is returned anyway.
|
2021-03-12 07:28:46 -05:00
|
|
|
func outputMarkdown(markdown string, baseURL string) error {
|
2022-09-13 14:35:15 -04:00
|
|
|
var styleOption glamour.TermRendererOption
|
|
|
|
if IsInteractive() {
|
|
|
|
styleOption = glamour.WithAutoStyle()
|
|
|
|
} else {
|
|
|
|
styleOption = glamour.WithStandardStyle("notty")
|
|
|
|
}
|
|
|
|
|
2021-03-12 07:28:46 -05:00
|
|
|
renderer, err := glamour.NewTermRenderer(
|
2022-09-13 14:35:15 -04:00
|
|
|
styleOption,
|
2021-03-12 07:28:46 -05:00
|
|
|
glamour.WithBaseURL(baseURL),
|
2022-09-13 13:52:44 -04:00
|
|
|
glamour.WithPreservedNewLines(),
|
2021-03-12 07:28:46 -05:00
|
|
|
glamour.WithWordWrap(getWordWrap()),
|
|
|
|
)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf(markdown)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
out, err := renderer.Render(markdown)
|
2020-10-04 22:23:57 -04:00
|
|
|
if err != nil {
|
|
|
|
fmt.Printf(markdown)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
fmt.Print(out)
|
|
|
|
return nil
|
|
|
|
}
|
2021-03-12 07:28:46 -05: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-29 23:43:26 -04:00
|
|
|
if term.IsTerminal(fd) {
|
|
|
|
if w, _, err := term.GetSize(fd); err == nil {
|
2021-03-12 07:28:46 -05:00
|
|
|
width = w
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if width > 120 {
|
|
|
|
width = 120
|
|
|
|
}
|
|
|
|
return width
|
|
|
|
}
|