Small library for simple and convenient formatted stylized output to the console.

Build Status Codecov Go Report Card GitHub license Mentioned in Awesome Go

cfmt

cfmt is a small library for simple and convenient formatted stylized output to the console, providing an interface that is exactly the same as the standard fmt library.

Table of Contents

Install

go get -u -v github.com/i582/cfmt

Usage

To switch to cfmt anywhere in the code, it is enough to add one letter c to fmt and you get all the possibilities, the library is fully compatible with the standard library fmt.

Simple usage

Let's take an example:

Suppose you need to display text and highlight some word or phrase. Using cfmt, all that is needed is to wrap the desired part in {{}} and after :: write the desired styles:

cfmt.Println("This is a {{red color}}::red")

If we compare this with the gookit/color library, then this example looks more complicated and less readable there:

fmt.Printf("This is a %s", color.Red.Sprintf("red color"))

Complex style

It is even more convenient if you need complex styles, if you want to make the text also bold, then all you need to add is in the format after | write bold:

cfmt.Println("This is a {{red color}}::red|bold")

In gookit/color, this is done as follows:

redBold := color.New(color.FgRed, color.OpBold)
fmt.Printf("This is a %s", redBold.Sprintf("red color"))

Custom styles

In the gookit/color we can reuse the created style, in cfmt this is also possible. To do this, you need to register a new style using the cfmt.RegisterStyle function:

cfmt.RegisterStyle("code", func(s string) string {
	return cfmt.Sprintf("{{%s}}::red|underline", s)
})

And now it can be used anywhere just by writing its name:

cfmt.Println("This is a {{red color}}::code")

The new style can of course also be used in conjunction with others:

cfmt.Println("This is a {{red color}}::code|bold")

HEX colors

If the standard colors are not enough for you, then you can use the colors in the Hex format (note, not all consoles support all colors fully!).

cfmt.Println("This is a {{red color}}::#ff0000")

Background color

To set the background color, you need to add the prefix bg to the color, in the case of standard colors, the first letter of the color must be capitalized:

cfmt.Println("This is a {{red color}}::bgRed")

For HEX it will look like this:

cfmt.Println("This is a {{red color}}::bg#ff0000")

Other examples

cfmt.RegisterStyle("code", func(s string) string {
	return cfmt.Sprintf("{{%s}}::red|underline", s)
})

cfmt.Printf(`
    {{Example of reports}}::bold

    {{                                                                            }}::bgRed
    {{                            Critical errors found                           }}::bgRed|#ffffff
    {{                                                                            }}::bgRed

    {{100}}::#ffffff myStyle := color.{{New(color.FgWhite, color.BgBlack, color.OpBold)}}::code|bold
        {{[100, 17]}}::blue Undefined function New at {{~/projects/test}}::underline:100

    {{101}}::#ffffff {{myStyle}}::code.Print("t")
        {{[101, 0]}}::blue Undefined variable myStyle at {{~/projects/test}}::underline:101
`)

cfmt.Print(`
        {{                 -/+:.          }}::green
        {{                :++++.          }}::green
        {{               /+++/.           }}::green
        {{       .:-::- .+/:-''.::-       }}::green
        {{    .:/++++++/::::/++++++//:    }}::green
        {{  .:///////////////////////:    }}::yellow
        {{  ////////////////////////      }}::yellow
        {{ -+++++++++++++++++++++++       }}::red
        {{ /++++++++++++++++++++++/       }}::red
        {{ /sssssssssssssssssssssss.      }}::red
        {{ :ssssssssssssssssssssssss-     }}::red
        {{  osssssssssssssssssssssssso/   }}::magenta
        {{   syyyyyyyyyyyyyyyyyyyyyyyy+   }}::magenta
        {{    ossssssssssssssssssssss/    }}::blue
        {{      :ooooooooooooooooooo+.    }}::blue
        {{       :+oo+/:-..-:/+o+/-       }}::blue
`)

Supported colors and styles

Styles
italic
bold
crossout
underline
overline
faint
reverse
blink
Colors
black darkGray bgDarkGray bgBlack
red lightRed bgLightRed bgRed
green lightGreen bgLightGreen bgGreen
yellow lightYellow bgLightYellow bgYellow
blue lightBlue bgLightBlue bgBlue
magenta lightMagenta bgLightMagent bgMagenta
cyan lightCyan bgLightCyan bgCyan
white lightWhite bgLightWhite bgWhite
gray bgGray

And colors in HEX format. See HEX colors part.

Motivation

The existing libraries for styling output are very powerful, and this library is built on two of them (gookit/color and muesli/termenv). However, they are not very convenient to use for styling specific words or sentences, since you need to use Sprintf and put the stylized into a format string, which greatly reduces readability if you need to style many elements.

I believe that the library will be useful primarily for formatting ready-made text, for reference or examples. However, in other cases it should be just as convenient.

The library aims to make formatted text look readable in code, even with complex formatting.

Contact

For any questions — tg: @petr_makhnev.

License

This project is under the MIT License. See the LICENSE file for the full license text.

Owner
Makhnev Petr
Junior Developer in vk.com
Makhnev Petr
Similar Resources

Yet Another CLi Spinner; providing over 70 easy to use and customizable terminal spinners for multiple OSes

Yet Another CLi Spinner; providing over 70 easy to use and customizable terminal spinners for multiple OSes

Yet Another CLi Spinner (for Go) Package yacspin provides yet another CLi spinner for Go, taking inspiration (and some utility code) from the https://

Dec 25, 2022

Terminal string styling for go done right, with full and painless Windows 10 support.

Terminal string styling for go done right, with full and painless Windows 10 support.

GChalk GChalk is a library heavily inspired by chalk, the popular Node.js terminal color library, and using go ports of supports-color and ansi-styles

Dec 28, 2022

Code that will query the meta data of an instance within AWS and provide a json formatted output on Go

EC2 meta-data, output JSON Code that will query the meta data of an instance wit

Dec 16, 2021

Reads MAWS formatted data and converts it into JSON output stream.

maws2json Usage examples Over serial line (stdin pipe) Lets assume that Vaisala weather station is connected via RS232 to USB serial dongle in /dev/tt

Feb 6, 2022

Easy column formatted output for golang

Columnize Easy column-formatted output for golang Columnize is a really small Go package that makes building CLI's a little bit easier. In some CLI de

Mar 1, 2019

✨ #PTerm is a modern go module to beautify console output. Featuring charts, progressbars, tables, trees, and many more 🚀 It's completely configurable and 100% cross-platform compatible.

✨ #PTerm is a modern go module to beautify console output. Featuring charts, progressbars, tables, trees, and many more 🚀 It's completely configurable and 100% cross-platform compatible.

💻 PTerm | Pretty Terminal Printer A golang module to print pretty text Show Demo Code PTerm.sh | Installation | Documentation | Quick Start | Example

Dec 27, 2022

Encoding and decoding for fixed-width formatted data

fixedwidth Package fixedwidth provides encoding and decoding for fixed-width formatted Data. go get github.com/ianlopshire/go-fixedwidth Usage Struct

Dec 16, 2022

A simple tool to extract Fronius solar data logger output and output Influx line protocol

telegraf-exec-fronius This is a simple tool to extract Fronius solar data logger output and output Influx line protocol; it is designed to be used wit

Jan 8, 2022

Generate markdown formatted sprint updates based on the Jira tickets were involved in the given sprint.

Generate markdown formatted sprint updates based on the Jira tickets were involved in the given sprint.

Nov 15, 2021

A piece of software that shouldn't need to exist. Processes badly formatted outputs from Morgan Stanley Shareworks into usable CSV files.

A piece of software that shouldn't need to exist.  Processes badly formatted outputs from Morgan Stanley Shareworks into usable CSV files.

Shareworks-munger: A program to process Shareworks reports into Something Usable "Shareworks" is a product of Morgan Stanley which tracks certain kind

Jun 6, 2022

Intuitive package for prettifying terminal/console output. http://godoc.org/github.com/ttacon/chalk

Intuitive package for prettifying terminal/console output. http://godoc.org/github.com/ttacon/chalk

chalk Chalk is a go package for styling console/terminal output. Check out godoc for some example usage: http://godoc.org/github.com/ttacon/chalk The

Dec 23, 2022

Utilities to prettify console output of tables, lists, progress-bars, text, etc.

Utilities to prettify console output of tables, lists, progress-bars, text, etc.

go-pretty Utilities to prettify console output of tables, lists, progress-bars, text, etc. Table Pretty-print tables into ASCII/Unicode strings.

Dec 29, 2022

Censors or hides shell / Bash / console output based on defined patterns - great for hiding secrets in demos!

Censors or hides shell / Bash / console output based on defined patterns - great for hiding secrets in demos!

censor-shell Installation go install Usage Make the file ~/.censor-shell as an INI file with the following content: [nameofmyreplacement] pattern = b

Nov 11, 2022

FizzBuzz: A ready-to-use console application that provides tools to format output with conditions

FizzBuzz FizzBuzz is a ready-to-use console application that provides tools to f

Feb 16, 2022

A tiny markup language for terminal output. Makes formatting output in CLI apps easier!

A tiny markup language for terminal output. Makes formatting output in CLI apps easier!

tml - Terminal Markup Language A Go module (and standalone binary) to make the output of coloured/formatted text in the terminal easier and more reada

Dec 14, 2022

A convenient library to do a must pattern

must A convenient library to do a must pattern Problems Before Go 1.18, if you want to panic when the regular expression cannot compile, you need to d

Nov 15, 2022

Mcopa - A library allows for parsing an email message into a more convenient form than the net/mail provides

Mail content parsing This library allows for parsing an email message into a mor

Jan 1, 2022

Supports the safe and convenient execution of asynchronous computations with goroutines and provides facilities for the safe retrieval of the computation results.

Rendezvous The Rendezvous library supports the safe and convenient execution of asynchronous computations with goroutines and provides facilities for

Dec 29, 2021

Procmon is a Linux reimagining of the classic Procmon tool from the Sysinternals suite of tools for Windows. Procmon provides a convenient and efficient way for Linux developers to trace the syscall activity on the system.

Procmon is a Linux reimagining of the classic Procmon tool from the Sysinternals suite of tools for Windows. Procmon provides a convenient and efficient way for Linux developers to trace the syscall activity on the system.

Process Monitor for Linux (Preview) Process Monitor (Procmon) is a Linux reimagining of the classic Procmon tool from the Sysinternals suite of tools

Dec 29, 2022
Comments
  • Background color (hex) display failure

    Background color (hex) display failure

    rawHex replace style

             if isBackgroundHex(style) {
    		rawHex := strings.TrimPrefix(style, "bg")
    		err := checkHex(rawHex)
    		if err != nil {
    			return "", err
    		}
    		text = hexBackgroundColorFunc(style, text)   //  text = hexBackgroundColorFunc(rawHex, text)
    		return text, nil
    	}
    
Intuitive package for prettifying terminal/console output. http://godoc.org/github.com/ttacon/chalk
Intuitive package for prettifying terminal/console output. http://godoc.org/github.com/ttacon/chalk

chalk Chalk is a go package for styling console/terminal output. Check out godoc for some example usage: http://godoc.org/github.com/ttacon/chalk The

Dec 23, 2022
Console Text Colors - The non-invasive cross-platform terminal color library does not need to modify the Print method

ctc - Console Text Colors The non-invasive cross-platform terminal color library does not need to modify the Print method Virtual unix-like environmen

Nov 9, 2022
uilive is a go library for updating terminal output in realtime
uilive is a go library for updating terminal output in realtime

uilive uilive is a go library for updating terminal output in realtime. It provides a buffered io.Writer that is flushed at a timed interval. uilive p

Dec 28, 2022
Change the color of console text.

go-colortext package This is a package to change the color of the text and background in the console, working both under Windows and other systems. Un

Oct 26, 2022
Minimalist Go package aimed at creating Console User Interfaces.
Minimalist Go package aimed at creating Console User Interfaces.

GOCUI - Go Console User Interface Minimalist Go package aimed at creating Console User Interfaces. Features Minimalist API. Views (the "windows" in th

Dec 25, 2022
A tiny library for super simple Golang tables

Tabby A tiny library for super simple Golang tables Get Tabby go get github.com/cheynewallace/tabby Import Tabby import "github.com/cheynewallace/tabb

Nov 23, 2022
A go library to render progress bars in terminal applications
A go library to render progress bars in terminal applications

uiprogress A Go library to render progress bars in terminal applications. It provides a set of flexible features with a customizable API. Progress bar

Dec 29, 2022
A go library to improve readability in terminal apps using tabular data

uitable uitable is a go library for representing data as tables for terminal applications. It provides primitives for sizing and wrapping columns to i

Dec 30, 2022
Simple tables in terminal with Go

Simple tables in terminal with Go This package allows to generate and display ascii tables in the terminal, f.e.: +----+------------------+-----------

Dec 29, 2022