{"id":22572746,"url":"https://github.com/dmfed/termtools","last_synced_at":"2025-04-10T14:32:16.685Z","repository":{"id":57541842,"uuid":"292121283","full_name":"dmfed/termtools","owner":"dmfed","description":"Output to terminal in style.","archived":false,"fork":false,"pushed_at":"2022-01-18T19:52:48.000Z","size":138,"stargazers_count":7,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-03-24T13:05:13.629Z","etag":null,"topics":["ansi-codes","cli","color","color-reset","cursor","golang","linux","terminal","vt100"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dmfed.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-09-01T22:30:32.000Z","updated_at":"2024-10-08T17:11:51.000Z","dependencies_parsed_at":"2022-09-09T02:50:32.889Z","dependency_job_id":null,"html_url":"https://github.com/dmfed/termtools","commit_stats":null,"previous_names":[],"tags_count":3,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dmfed%2Ftermtools","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dmfed%2Ftermtools/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dmfed%2Ftermtools/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dmfed%2Ftermtools/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dmfed","download_url":"https://codeload.github.com/dmfed/termtools/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248233946,"owners_count":21069493,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ansi-codes","cli","color","color-reset","cursor","golang","linux","terminal","vt100"],"created_at":"2024-12-08T02:11:33.813Z","updated_at":"2025-04-10T14:32:16.669Z","avatar_url":"https://github.com/dmfed.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# module termtools\n\nversion 1.0.0\n\n**termtools** is basically a collection of utilities to style console output on Linux systems.\nThe module allows to colorize terminal output in a very simple and straighforward way.\nMost of the code is a wrapper around fmt module from Go's standard library. \n\n**termtools** module also includes utility functions to control cursor position in the terminal.\n\n**Note: This README is NOT intended to document all of what termtools has to offer and only provides some usage examples.** \n**Please see full module documentation at** **[https://pkg.go.dev/github.com/dmfed/termtools](https://pkg.go.dev/github.com/dmfed/termtools)** **for a complete list of what is available.**\n\n## Getting termtools\n\n**go get -u github.com/dmfed/termtools** and you are good to Go :) \n\n**import \"github.com/dmfed/termtools\"** to import module in you code\n\n## Basic usage\n\nFirst of all you can directly use any ANSI escapes declared in the module. (For a complete list of exported constants see **[https://pkg.go.dev/github.com/dmfed/termtools](https://pkg.go.dev/github.com/dmfed/termtools)**.)\n\n```go\ns := termtools.Red + \"We're gophers\" + termtools.Reset \t// adding escape for red and escape for color reset\nfmt.Println(s) \t\t\t\t\t\t// the string \"We're gophers\" will output in red.\n```\nYou can also get your string colorized using function similar to fmt.Sprint (same signature as Sprint, but first parameter is color name). \n\n```go\nmystring := termtools.Csprint(\"red\", \"This will print in red\") // Colorizes input string\nfmt.Println(mystring)\n```\nSee below for a full list of supported color names. \n\n## Using Printer\n\nMore clever way would be to use Printer. \n\n```go\nvar printer termtools.Printer \t\t\t\t// Initializes new Printer\nprinter.SetColor(9) \t\t\t\t\t// Sets color (9 is orange)\nprinter.Println(\"This will output in orange\") \t\t// This prints in orange\nprinter.SetColor(\"red\")\t\t\t\t\t// Sets color\nprinter.Println(\"This will output in red\")\t\t// This prints in red\nprinter.ToggleUnderline()\t\t\t\t// switches undeline mode on\nprinter.Println(\"This will output in undelined red\")\t// prints in underlined red\n```\n\nFont and backgrount colors can be set either by color name (supplied as string) or by color numeric id ranging from 0 to 255 inclusive. To set font or background color by name use **printer.SetColor(colorname interface{})** and **printer.SetBackground(colorname string)** methods of Printer accordingly. See **[https://pkg.go.dev/github.com/dmfed/termtools](https://pkg.go.dev/github.com/dmfed/termtools)** for a complete list of Printer methods.\n\nSupported color names are:\n\n**\"black\", \"blue\", \"cyan\", \"green\", \"magenta\", \"red\", \"white\", \"yellow\", \"brightblack\", \"brightblue\", \"brightcyan\", \"brightgreen\", \"brightmagenta\", \"brightred\", \"brightwhite\", \"brightyellow\"**\n\nColor numeric IDs are as follows:\n\n![image of palette with colors numbered 0-255](https://raw.githubusercontent.com/dmfed/termtools/main/palette.png)\n\nTo see the above palette in your terminal **git clone https://github.com/dmfed/termtools/** then **cd** into the repo and issue **go test**. The test will output known colors and the pallette with codes. See also see **samples/palette.go**\n\n*NOTE: colors may not display correctly in some shells and terminals depending on your settings.*\n\n## Printer modes: bold, underline, reversed, blinking\nPrinter has four modes: **bold**, **reversed**, **underline**, and **blinking**. Bold, underline and blinking are self explanatory. Reversed mode if switched on swaps font and background colors). These modes can be toggled on and off with **ToggleBold()**, **ToggleBlinking()**, **ToggleReversed()**, and **ToggleUnderline()** methods of Printer. For a complete list of Printer methods see **[https://pkg.go.dev/github.com/dmfed/termtools](https://pkg.go.dev/github.com/dmfed/termtools)**.\n\n## NewPrinter\nPrinter instance can be initialized with all options set to needed values at once. Use **termtools.NewPrinter()** to set up instance of Printer as required.\n\nThe functions sugnature is as follows: \n\n**func NewPrinter(conf PrinterConfig) (p \\*Printer, err error)**\n\nIt accepts PrinterConfig as single argument.\n\n```go\ntype PrinterConfig struct {\n\tName       string\n\tColor      interface{}\n\tBackground interface{}\n\tBold       bool\n\tUnderline  bool\n\tReversed   bool\n\tBlinking   bool\n\tPrefix     string\n\tSuffix     string\n}\n```\n\nHere is an example.\n\n```go\nprinter, err := termtools.NewPrinter(termtools.PrinterConfig{Color: \"blue\", Blinking: true})\nif err != nil {\n\tprinter.Println(err)\n}\nprinter.Println(\"Printing in blue blinking here.\")\n```\n## Printing methods\nPrinter type implements most print methods as in fmt module from standard library copying their signatures, names and behaviour. You can call **Println, Print, Sprint, Sprintf, Errorf** etc. In fact printing methods just wrap around fmt module by adding required ANSI escapes to the original values passed.\n\nFor example fhe following adds color escape codes to the input and color reset escape at the end:\n```go\ngreenprinter := termtools.Printer{} \t\t// initializes new Printer\ngreenprinter.SetColor(\"green\") \t\t\t\t// sets Printer color to green\ns := greenprinter.Sprint(\"Hello, world!\") \t// s now holds \"Hello, world!\" with green color prefix and reset suffix attached.\n```\nNote that **len(greenprinter.Sprint(\"Hello, world!\"))** in the above example will not be the same as **len(fmt.Sprint(\"Hello, world!\"))** because ANSI escapes actually add to the length of the output string. This might be annoying if you're trying to keep output centered horizontally and rely on calculation of string length.\n\nFor a detailed list of printing methods **[see package documention at pkg.go.dev](https://pkg.go.dev/github.com/dmfed/termtools)**\n\n## Moving cursor around\n\n**termtools** includes functions and methods of Printer type to manipulate cursor position on screen, clear screen and delete lines of text.\n\n```go\nfunc PrintCentered(s string) {\n\tx, y, _ := termtools.GetTermSize() \t\t\t\t// returns number of columns and rows in current terminal\n\ttermtools.ClearScreen()\t\t\t\t\t\t// clears screen\n\tfmt.Print(strings.Repeat(\"\\n\", y))\n\ts = termtools.ColorSprint(\"blue\", s)\t\t\t\t// sets input string color to blue\n\ttermtools.PrintAtPositionAndReturn(x/2-len(s)/2, y/2, s)\t// prints at requested position and returns cursor\n}\n```\nOr using **termtools.Printer**\n```go\nvar p termtools.Printer\np.MoveTo(10,10)\np.Print(\"This starts at column 10, row 10\")\n```\n**termtools** has the following functions to control cursor position (signatures are self-explanatory):\n\n**func MoveCursorTo(column, row int), func MoveCursorHome(), func MoveCursorUp(rows int), func MoveCursorDown(rows int), MoveCursorLeft(columns int), MoveCursorRight(columns int), MoveCursorToRow(row int), func MoveCursorToNextRow()**\n\nMost of this functionality is also implemented for **termtools.Printer** type with shorter and bit different names. **[See docs at pkg.go.dev](https://pkg.go.dev/github.com/dmfed/termtools)**\n\n## Clearing screen, deleting lines of text\n\n**termtools** has the following set of functions available to delete lines of text and clear screen:\n\n**ClearScreen(), ClearScreenUp(), ClearScreenDown(), ClearLine(), ClearLineLeft(), ClearLineRight()**\n\n## Using PrintSuite to style your program output\n\n**termtools.PrintSuite** can act as an (almost) full replacement to fmt module from standard library. It is intended to hold one or more configurations of **termtools.Printer** and switch them on the fly. This way you\ncan get different output styles for different kinds of messages in your program. \n\n```go\ntype PrintSuite struct {\n\tPrinter\n\t// Has unexported field.\n}\n```\n**termtools.PrintSuite** embeds default Printer, so you can call any printing method on it directly.\n\nIn example below we set up PrintSuite to be available globally in the program then configure two printers (red and green underlined). \n\nWe then can use (for example) red printer to display error messages and green printer to display success notifications.\n\nConsider code below:\n```go\npackage main\n\nimport \"github.com/dmfed/termtools\"\n\nvar prnt = termtools.PrintSuite{} // here we define prnt globally to reuse it from any part of program\n\nfunc setupPrinters() {\n\tconfigs := []termtools.PrinterConfig{\n\t\t{Name: \"error\", Color: \"red\"},\n\t\t{Name: \"notify\", Color: \"green\", Underline: true}}\n\tif err := prnt.Configure(configs...); err != nil {\n\t\tprnt.Println(err)\n\t}\n}\n\nfunc main() {\n\tsetupPrinters()\n\t// We now can use different printers for different kinds of messages anywhere in out program.\n\t// For example print errors in red\n\tprnt.Use(\"error\").Print(\"We call prnt.Use(\\\"error\\\").Print() to output using printer named \\\"error\\\"\\n\")\n\n\t// or print notifications in green\n\tprnt.Use(\"notify\").Print(\"and prnt.Use(\\\"notify\\\").Print() to use printer named \\\"notify\\\"\\n\")\n\n\t// or use unstyled output of embedded printer for everything else like this:\n\tprnt.Println(\"This will print without any styling.\")\n\n\t// or like this:\n\tprnt.UseDefault().Println(\"This will print without any styling.\")\n}\n```\n**IMPORTANT: When passing termtools.PrinterConfig configuration(s) to PrintSuite Configure() method always make sure that Name field ot config(s) is NOT EMPTY. Otherwise Configure will fail with an error.** Some of passed configurations (precceding the one that is missing name) may be processed and PrintSuite will still be usable but the mathod will terminate upon encountering config with empty Name field.\n\nNote that **Use()** method in example above returns pointer to named printer, so you can call any Printer method directly. \nAlso note that PrintSuite embeds Printer instance so any Printer method can be called on it without Use() (i.e **prnt.Println(\"This will print without any styling.\")**). This will use embedded Printer instance.\n\nTo change embedded printer style use SwitchTo(printername string).\n\n```go\nprnt.SwitchTo(\"notify\")\nprnt.Println(\"Call to prnt.Println (and other methods) from this point on will use \\\"notify\\\" style.\")\n```\n\nTo reset embedded Printer instance use **SwitchToDefault()**\n\n```go\nprnt.SwitchToDefault()\nprnt.Println(\"Call to prnt.Println will now act as simple call to fmt.Println again.\"\n```\nFor a full list of PrintSuite methods **[see package documention at pkg.go.dev](https://pkg.go.dev/github.com/dmfed/termtools)**\n\n## Example programs\n\nSome example programs are included in **samples** directory of the repo at https://github.com/dmfed/termtools/tree/main/samples\n\nHere's the listing of one of the examples:\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"math/rand\"\n\t\"time\"\n\n\ttt \"github.com/dmfed/termtools\"\n)\n\n// PrintStair is an example function\nfunc PrintStair(a ...interface{}) {\n\trand.Seed(time.Now().UnixNano())\n\tvar p tt.Printer            // initializes Printer\n\t_, y, _ := tt.GetTermSize() // gets size of terminal window\n\ty = y/2 - 6\n\tfor xpos := 0; xpos \u003c= 80; xpos = xpos + 5 {\n\t\tp.SetColorID(rand.Intn(256))\n\t\tp.PrintAtPosition(xpos, y, a...)\n\t\ty++\n\t}\n\tp.Reset()\n}\n\nfunc main() {\n\t// Simplest use is to call ColorSprint (same signature as in fmt.Sprint, but the\n\t// first argument is the name of the color).\n\ttt.ClearScreen()                                            // Clears Screen\n\ttt.MoveCursorTo(0, 0)                                       // Moves cursor to top left\n\tmystring := tt.ColorSprint(\"red\", \"This will print in red\") // Colorizes input string\n\tfmt.Println(mystring)\n\n\t// Now using the Printer\n\tvar p tt.Printer                                        // Initialize new Printer\n\tp.ToggleUnderline()                                     // Set Printer to print underlined\n\tp.SetColor(\"green\")                                     // Set font color to green\n\tp.Println(\"Printing in green underlined with Printer.\") // This will print in green underlined\n\n\tPrintStair(\"I'm a walrus!\")\n}\n```\nPlease see **[https://pkg.go.dev/github.com/dmfed/termtools](https://pkg.go.dev/github.com/dmfed/termtools)** for a complete documentation of **termtools**.\n\n## That's all folks!\n\nThank you for reading this far :)\n\nI hope you might find **termtools** useful. Any feedback is welcome. \n\nI'm planning to freeze all function signatures in v1.0.0. Until then some functions signatures might change and I'm also considering adding and/or removing some stuff. \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdmfed%2Ftermtools","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdmfed%2Ftermtools","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdmfed%2Ftermtools/lists"}