Coder Social home page Coder Social logo

charmbracelet / glamour Goto Github PK

View Code? Open in Web Editor NEW
2.2K 16.0 162.0 2.6 MB

Stylesheet-based markdown rendering for your CLI apps πŸ’‡πŸ»β€β™€οΈ

License: MIT License

Go 98.74% Shell 1.26%
markdown go golang cli hacktoberfest tui

glamour's Introduction

Glamour

Glamour Title Treatment
Latest Release GoDoc Build Status Coverage Status Go ReportCard

Stylesheet-based markdown rendering for your CLI apps.

Glamour dark style example

glamour lets you render markdown documents & templates on ANSI compatible terminals. You can create your own stylesheet or simply use one of the stylish defaults.

Usage

import "github.com/charmbracelet/glamour"

in := `# Hello World

This is a simple example of Markdown rendering with Glamour!
Check out the [other examples](https://github.com/charmbracelet/glamour/tree/master/examples) too.

Bye!
`

out, err := glamour.Render(in, "dark")
fmt.Print(out)

Hello World example

Custom Renderer

import "github.com/charmbracelet/glamour"

r, _ := glamour.NewTermRenderer(
    // detect background color and pick either the default dark or light theme
    glamour.WithAutoStyle(),
    // wrap output at specific width (default is 80)
    glamour.WithWordWrap(40),
)

out, err := r.Render(in)
fmt.Print(out)

Styles

You can find all available default styles in our gallery. Want to create your own style? Learn how!

There are a few options for using a custom style:

  1. Call glamour.Render(inputText, "desiredStyle")
  2. Set the GLAMOUR_STYLE environment variable to your desired default style or a file location for a style and call glamour.RenderWithEnvironmentConfig(inputText)
  3. Set the GLAMOUR_STYLE environment variable and pass glamour.WithEnvironmentConfig() to your custom renderer

Glamourous Projects

Check out these projects, which use glamour:

  • Glow, a markdown renderer for the command-line.
  • GitHub CLI, GitHub’s official command line tool.
  • GitLab CLI, GitLab's official command line tool.
  • Gitea CLI, Gitea's official command line tool.
  • Meteor, an easy-to-use, plugin-driven metadata collection framework.

Feedback

We’d love to hear your thoughts on this project. Feel free to drop us a note!

License

MIT


Part of Charm.

The Charm logo

Charmηƒ­ηˆ±εΌ€ζΊ β€’ Charm loves open source

glamour's People

Contributors

anthonyfok avatar arl avatar aymanbagabas avatar bashbunni avatar bene64 avatar benicas avatar brianstrauch avatar caarlos0 avatar dependabot[bot] avatar garymh avatar jessemillar avatar jolheiser avatar lepasq avatar maaslalani avatar meowgorithm avatar mmrwoods avatar muesli avatar otherjl0 avatar profclems avatar raidancampbell avatar ravisuhag avatar samcoe avatar toby avatar twpayne avatar wilso199 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

glamour's Issues

Prefix on multi-lined blockquotes

As a warning, I understand what I'm about to outline is expected behavior; this a proposal for an exception for blockquotes.

A multiline block will only render the prefix at the beginning of the first line. For example, this input…

> Down dropt the breeze, the sails dropt down,                                                      
> ’Twas sad as sad could be;                                                                        
> And we did speak only to break                                                                    
> An artichoke in the sea!

Renders to…

> Down dropt the breeze, the sails dropt down,                                                      
’Twas sad as sad could be;                                                                        
And we did speak only to break                                                                    
An artichoke in the sea! 

When all the text is on one line we get similar output. This…

> The artichoke is mentioned as a garden plant in the 8th century BC by Homer and Hesiod. The naturally occurring variant of the artichoke, the cardoon…

…renders to…

> The artichoke is mentioned as a garden plant in the 8th century BC by Homer and
Hesiod. The naturally occurring variant of the artichoke, the cardoon…

If we changed the behavior so the prefix was applied to every line, we could get nice effects like:

β”‚  Down dropt the breeze, the sails dropt down,                                                      
β”‚  ’Twas sad as sad could be;                                                                        
β”‚  And we did speak only to break                                                                    
β”‚  An artichoke in the sea!

Alternatively, we could use prefix/suffix to do things surround quotes with β€œ and ”, but at the moment suffix is rendered on a new line. I suspect the more popular and useful behavior would be a prefix before every line.

Tables don’t inherit document color

It appears to be choosing either white or dark depending on the terminal background. Here's an example of it rendering in a light terminal with gold -s light:

Screen Shot 2019-12-16 at 8 15 26 PM

Background color on non-Chroma'd code block

When there’s a background color on a code block, should the background color also color the empty cells on the line? Given the following styling:

"code_block": {
  "prefix": "\n",
  "suffix": "\n",
  "margin": 4,
  "background_color": "21"
}

A code block currently renders as follows:

Screen Shot 2019-12-08 at 6 18 51 PM

Enumerated lists with nested items mis-renders

It seems as though nested lists with enumerations aren't quite rendering properly. Given this markdown:

1. Carrots
1. Celery
1. Tacos
  1. Soft
  1. Hard
1. Cucumber

---

1. Carrots
1. Celery
1. Tacos
  * Soft
  * Hard
1. Cucumber

I get the following output:

  1. Carrots                                                                                        
  2. Celery                                                                                         
  3. Tacos                                                                                          
  4. Soft                                                                                           
  5. Hard                                                                                           
  6. Cucumber                                                                                       
                                                                                                    
  --------                                                                                          
                                                                                                    
  1. Carrots                                                                                        
  2. Celery                                                                                         
  3. Tacos                                                                                          
                                                                                                    
  β€’ Soft                                                                                            
  β€’ Hard                                                                                            
                                                                                                    
  1. Cucumber

This is as rendered from the dark style in master.

First item in a list gets two bullets

Here’s the style I'm using:

"list": {
  "prefix": "β€’Β "
}

Here's the markup:

* Unordered list item
* Another unordered list item
* One more item

And here's the output:

β€’Β β€’Β Unordered list item                                                                           
β€’Β Another unordered list item                                                                   
β€’Β One more item

Background colors

It might be cool to support background colors, both for inline elements (maybe links have a special background color) as well as block-level elements (maybe a code block has a background color to differentiate it). Block-level code coloring could get weird because we don't know the user's default background color, but it could be a nice style offering.

New default style limited to basic ANSI colors

So there is -s [dark|light], I think that should be changed to -s [dark|light|term] where the term option uses color 0-15, which is easier to change than making a json file that only applies to this program.

(Sorry for making 2 issues so fast)

Inline elements in headers

If there's a link in a header, the link isn't rendered and the header doesn't render correctly.

### Do we allow [links](https://example.com) in headers?

Renders as

 ### Do we allow

List indentation

It would be nice to have lists with items spanning multiple rows indented to the same level for text. This is just my opinion, so feel free to close this if you disagree.

For instance:

* A list
* With a multiline item, since the item text is too long to stay on a single line because it is long.
* Another item

Renders to:

  β€’ A list
  β€’ With a multiline item, since the item text is too long to stay on a single line because it is
  long.
  β€’ Another item

Whereas this is slightly easier to read (IMHO):

  β€’ A list
  β€’ With a multiline item, since the item text is too long to stay on a single line because it is
    long.
  β€’ Another item

Suggestion: define default styles in Go, not JSON

Currently, glamour has a number of standard styles defined in JSON files. This has a number of side-effects:

  • glamour needs a module and an extra build step (currently statik to make these JSON files available in the glamour library. The build step needs to be re-run manually whenever any of the style JSON files are modified for the changes to take effect.
  • The JSON files are not parsed until they are loaded, i.e. at runtime. There is very little sanity checking: for example, a mis-spelled property will be silently ignored and will instead get the default zero value. Any error in the JSON file will only be raised when it is first used.
  • The standard styles are not exported from the glamour package in any way, so any application wanting to use a slightly-modified standard style needs to duplicate the style completely.

In short, the current process is:

JSON style file -> statik build step -> read JSON from statik at runtime -> parse JSON at runtime -> Go style struct

Would you consider a PR that replaces this with:

Go style struct

?

Specifically, I propose to:

  1. Maintain the current API.
  2. Replace the JSON style files with equivalent Go struct literals as exported variables.
  3. Remove the use of statik.

This would have the following advantages:

  1. Standard styles would be directly available to users.
  2. Styles would be checked by the compiler at build time.
  3. The build process would be simplified, without manual steps.

The only disadvantage that I see is that Go struct literals are more verbose than the equivalent JSON style files. Compare simple.json with the near-equivalent Go struct literal. However, the verbosity would only be noticed by the glamour authors.

Would you accept such a PR?

Inter-word spaces are incorrectly stripped from link text

The input markdown:

If you want to make a more significant change, please first [open an
issue](https://github.com/twpayne/chezmoi/issues/new) to discuss the change that
you want to make. Dave Cheney gives a [good
rationale](https://dave.cheney.net/2019/02/18/talk-then-code) as to why this is
important.

with the default dark style is rendered as:

glamour-spaces

Note that open an issue is rendered as open anissue and good rationale is rendered as goodrationale. In both cases, inter-word spaces are stripped but should not be.

The full input markdown document that demonstrates this error can be found here.

Relative path incorrectly prepended to footnotes

Glow does not seem to understand that footnotes (Pandoc syntax) are not URLs, notably when the footnote contains just a single word:

Foo[^1] bar.

[^1]: Not a URL here.

Foo1 bar.

Foo[^1] bar.

[^1]: baz

Foo^1 /home/caleb/scratch/baz bar.

Note the semantics of the input are the same in both cases, but it's handled wildly differently in each case. The latter case prepended the $PWD I executed the test from. I suspect it is just using some URL syntax that is not standard plain Markdown, but it would be nice to either disable this syntax extension completely or enable one for footnotes in this (common) format.

Footnotes

  1. Not a URL here. ↩

Implicit theme set

Currently, "theme": "charm" must be set in "code_block" in order for Chroma syntax highlighting to be picked up in the same style (JSON) file. It would be nice if these styles would be picked up without "theme": "charm" needing to be set.

Extra line-breaks are inserted at certain boundaries

Repro:

  1. put this in a file and send it through gold

testing: this is a test
too many lines: i think there will be too many lines between these items

Expect: no spaces between the lines

Result: spaces between the lines

Reflow paragraphs

It would be really nice if paragraphs were reflowed at 80 columns as part of the cleanup process. Or perhaps 76 is better?

Regardless, if we're really doing it right, we'd reflow at either 80/76 or the width of the terminal, whichever is smaller.

Trouble rendering bold, italics and underline in headers

When set on a header bold, italics and underline only seem to only affect the prefix. Given the following…

# Hello

## Hello

### Hello

#### Hello

##### Hello

###### Hello
{
    "heading": {
        "underline": true,
        "bold": true,
        "italic": true
    },
    "h1": { "prefix": "#" },
    "h2": { "prefix": "##" },
    "h3": { "prefix": "###" },
    "h4": { "prefix": "####" },
    "h5": { "prefix": "#####" },
    "h6": { "prefix": "######" }
}

…I'm getting the following output:

Screen Shot 2019-12-18 at 11 04 50 PM

This is consistent across MacOS Terminal, Kitty and iTerm2 on MacOS.

Feature request: consider using functional options

Thank you for this really nice project! I'd like to use it in chezmoi to replace chezmoi's existing very crude Markdown-to-text renderer.

Currently glamour provides a number of constructors, including NewTermRenderer and NewTermRendererFromBytes. Would you consider using functional options instead? This has a number of advantages, notably around simplified APIs (fewer constructors) and much greater future extensibility.

I would be happy to submit a PR to implement this if you agree.

Prefix/suffix coloring

If we could specify the the color of prefix and suffix elements (perhaps with something like prefix_color and suffix_color) it would open a world of styling possibilities.

Custom Chroma styles

We need to make a custom light/dark stock theme for Chroma to match our default coloring. The code blocks are a bit too jarring otherwise.

Code syntax highlighting and background color rendering

Code coloring doesn't inherit the background color of the document, instead it shifts the background color right. Additionally, code doesn’t highlight in MacOS's stock Terminal.

Kitty (with a dark gray background):

Screen Shot 2019-12-07 at 8 13 57 AM

MacOS default terminal (with a white background):

Screen Shot 2019-12-07 at 8 21 29 AM

Support multiple header levels

It would be nice if we could have different styling for different header levels (I believe blackfriday supports up to 6 levels). The style could cascade from the generic "header" element to something like "header 3" with "header 3" taking precedence.

Suggestion: disable coveralls.io coverage tests (not reporting)

At the time of writing, CI for master is failing because coveralls.io considers a coverage change of -6.7% to be a failure. In this case, the coverage drop seems to be related to the way that coverage is reported, not because of any actual change in coverage.

Code coverage is a fun and useful metric, but is overly simplistic for many cases and particularly problematic for Go, where high code coverage requires extra effort to cover all the err != nil cases.

Suggestion: configure coveralls.io so that it only reports build failures for very significant drops in coverage, say -20%.

Space before, space after

An option to add a few blank lines above or below block-level elements in styles would be helpful in both providing a sense of hierarchy and aiding readability.

Doesn't display "\<foo foo\>/bar/bar" correctly

I tried glow on README from p410n3/knifechoose.nut repo and it doesn't display "\<your csgo directory\>/csgo/scripts/vscripts" correctly.

P.S. I don't really know markdown, so I don't know if it's undefined behavior in how github renders it or a bug in glow

glow version 0.1.3

Screenshots

glow
20191224_034707

github
20191224_034714

Background color setting ignored

It looks like the background_color setting in the style JSON isn't being applied. I'm testing with the following JSON:

{
  "heading": {
    "color": "230",
    "background_color": "63"
  }
}

Via:

echo -e '# Hello!\n\nHow are you today?' | gold -s test.json -

Document style options

We should write a quick howto for style creators:

  • Which options work for each style element
  • What do the options affect

Indent ignored on headers

Not sure if this is intentional but I’m finding that the indent value is being ignored on headers:

"heading": {
  "indent": 8
}

Some rendering issues

I was viewing a README with glow. Noticed the following issues:

From the Features section (https://github.com/jarun/nnn/blob/master/README.md#features):

  β€’ Familiar shortcuts (arrows,                                                                   
    ~                                                                                               
    ,                                                                                               
    -                                                                                               
    ,                                                                                               
    @                                                                                               
    ), quick reference                                                                              
    β€’ CD on quit (easy shell integration)

Also the table of deps (https://github.com/jarun/nnn/blob/master/README.md#utility-dependencies) looks broken:

  $VISUAL$EDITOR$PAGER$SHELL            DEPENDENCY           β”‚ INSTALLATION β”‚           OPERATION   
  ─────────────────────────────────┼──────────────┼─────────────────────────────────                
    xdg-open (Linux), open(1)      β”‚ base         β”‚ desktop opener                                  
    (macOS), cygstart (Cygwin)     β”‚              β”‚                                                 
    file, coreutils (cp, mv, rm),  β”‚ base         β”‚ file type, copy, move and                       
    xargs                          β”‚              β”‚ remove                                          
    tar, (un)zip [atool/bsdtar for β”‚ base         β”‚ create, list, extract tar,                      
    more formats]                  β”‚              β”‚ gzip, bzip2, zip                                
    archivemount, fusermount(3)    β”‚ optional     β”‚ mount, unmount archives                         
    sshfs, rclone, fusermount(3)   β”‚ optional     β”‚ mount, unmount remotes                          
    trash-cli                      β”‚ optional     β”‚ trash files (default action:                    
                                   β”‚              β”‚ rm)                                             
    vlock (Linux), bashlock        β”‚ optional     β”‚ terminal locker (fallback:                      
    (macOS), lock(1) (BSD)         β”‚              β”‚ cmatrix)                                        
    advcpmv (Linux) (integration)  β”‚ optional     β”‚ copy, move progress                             
    $VISUAL (else $EDITOR),        β”‚ optional     β”‚ fallback vi, less, sh                           
    $PAGER, $SHELL                 β”‚              β”‚                                                 

Ordered Lists

Ordered lists are rendering as nested lists:

1. A
2. B
3. C

Renders as:

β€’ A
β€’ B
β€’ C

Chroma-colored code ignores prefix and suffix

When a code block is highlighted with Chroma prefix and suffix values are ignored.

(In my case I wanted to add an extra line above and below the code to further visually separate it from the surrounding content.)

Should we strip anchor links?

Because the terminal doesn't support links to anchors within the page we should strip them. In other words, code like this:

* [About](#about)

Which, in HTML, would render to:

<a href="#about">About</a>

Consider this example from the wild:

Screen Shot 2019-12-11 at 5 02 24 PM

Prefix/suffix styling

Would be helpful to have this option for some advanced rendering uses, even if the syntax is more complex.

Block level indenting

An option to indent sections could be a nice touch in aiding readability and hierarchy, for example, the way code blocks are indented in traditional markdown. That may complicate the word-wrapping a bit though.

Table styling

I imagine it's planned, but noting this one down so we can keep track of it. Would be cool, at least, to set foreground and background colors.

Handling "plain" links

So in cases like this:

Hello! https://example.com

It’s rendered as:

Hello! https://example.com (https://example.com)

Which is technically correct, but in those cases we should probably not repeat the link. The question, though, is so they get their own styling in that case?

Add notty style

Add a style for non-terminal output (e.g. less) that uses no ANSI sequences, but still makes use of prefixes and suffixes to style certain elements like lists, tables or headings.

Long headers don't wrap

Not totally sure about this one…but I think long headers should wrap?

Here's what I'm testing with:

# Long Header. It just goes on and on. What kind of header would be this long? A header in an academic paper!

Spurious table data is rendered before table

The input Markdown:

## Pre-built Linux packages

Download a package for your operating system and architecture and install it
with your package manager.

| Distribution | Architectures                                             | Package                                                                   |
| ------------ | --------------------------------------------------------- | ------------------------------------------------------------------------- |
| Debian       | `amd64`, `arm64`, `armel`, `i386`, `ppc64`, `ppc64le`     | [`deb`](https://github.com/twpayne/chezmoi/releases/latest)               |
| RedHat       | `aarch64`, `armhfp`, `i686`, `ppc64`, `ppc64le`, `x86_64` | [`rpm`](https://github.com/twpayne/chezmoi/releases/latest)               |
| OpenSUSE     | `aarch64`, `armhfp`, `i686`, `ppc64`, `ppc64le`, `x86_64` | [`rpm`](https://github.com/twpayne/chezmoi/releases/latest)               |
| Ubuntu       | `amd64`, `arm64`, `armel`, `i386`, `ppc64`, `ppc64le`     | [`deb`](https://github.com/twpayne/chezmoi/releases/latest)               |

with the default dark theme and with ansi.Options.WordWrap = 80 is rendered as:

glamour-wide-table

Data from the table is rendered twice, and this seems to throw off the column alignment.

The original Markdown file that demonstrates this can be found here

URLs containing only fragments should not be rendered

The input Markdown:

<!--- toc --->
* [Getting started](#getting-started)
* [Developing locally](#developing-locally)
* [Documentation changes](#documentation-changes)
* [Contributing changes](#contributing-changes)
* [Managing releases](#managing-releases)
* [Packaging](#packaging)
* [Updating the website](#updating-the-website)

with the default dark style is rendered as:

glamour-fragments

Since the URLs contain only document-relative fragments, they are not useful to click on or be copied to be opened elsewhere, and so should not be rendered.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.