...

Source file src/github.com/cli/go-gh/v2/pkg/markdown/markdown.go

Documentation: github.com/cli/go-gh/v2/pkg/markdown

     1  // Package markdown facilitates rendering markdown in the terminal.
     2  package markdown
     3  
     4  import (
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/charmbracelet/glamour"
     9  )
    10  
    11  // WithoutIndentation is a rendering option that removes indentation from the markdown rendering.
    12  func WithoutIndentation() glamour.TermRendererOption {
    13  	overrides := []byte(`
    14  	  {
    15  			"document": {
    16  				"margin": 0
    17  			},
    18  			"code_block": {
    19  				"margin": 0
    20  			}
    21  	  }`)
    22  
    23  	return glamour.WithStylesFromJSONBytes(overrides)
    24  }
    25  
    26  // WithoutWrap is a rendering option that set the character limit for soft wraping the markdown rendering.
    27  func WithWrap(w int) glamour.TermRendererOption {
    28  	return glamour.WithWordWrap(w)
    29  }
    30  
    31  // WithTheme is a rendering option that sets the theme to use while rendering the markdown.
    32  // It can be used in conjunction with [term.Theme].
    33  // If the environment variable GLAMOUR_STYLE is set, it will take precedence over the provided theme.
    34  func WithTheme(theme string) glamour.TermRendererOption {
    35  	style := os.Getenv("GLAMOUR_STYLE")
    36  	if style == "" || style == "auto" {
    37  		switch theme {
    38  		case "light", "dark":
    39  			style = theme
    40  		default:
    41  			style = "notty"
    42  		}
    43  	}
    44  	return glamour.WithStylePath(style)
    45  }
    46  
    47  // WithBaseURL is a rendering option that sets the base URL to use when rendering relative URLs.
    48  func WithBaseURL(u string) glamour.TermRendererOption {
    49  	return glamour.WithBaseURL(u)
    50  }
    51  
    52  // Render the markdown string according to the specified rendering options.
    53  // By default emoji are rendered and new lines are preserved.
    54  func Render(text string, opts ...glamour.TermRendererOption) (string, error) {
    55  	// Glamour rendering preserves carriage return characters in code blocks, but
    56  	// we need to ensure that no such characters are present in the output.
    57  	text = strings.ReplaceAll(text, "\r\n", "\n")
    58  	opts = append(opts, glamour.WithEmoji(), glamour.WithPreservedNewLines())
    59  	tr, err := glamour.NewTermRenderer(opts...)
    60  	if err != nil {
    61  		return "", err
    62  	}
    63  	return tr.Render(text)
    64  }
    65  

View as plain text