Git Product home page Git Product logo

escapade's Introduction

GitHub Workflow

Escapade

The adventure of ANSI escape codes

Escapade makes it easy to work safely with strings containing ANSI escape codes.

Features

  • provides a representation of strings containing ANSI escape codes
  • support for 24-bit color, integrated with Iridescence color representations
  • introduces the typechecked e"" string interpolator
  • constant-time reduction to "plain" strings
  • extensible support for different substitution types
  • introduces "virtual" escapes with stack-based region tracking

Availability Plan

Escapade has not yet been published. The medium-term plan is to build Escapade with Fury and to publish it as a source build on Vent. This will enable ordinary users to write and build software which depends on Escapade.

Subsequently, Escapade will also be made available as a binary in the Maven Central repository. This will enable users of other build tools to use it.

For the overeager, curious and impatient, see building.

Getting Started

About ANSI Codes

ANSI escape codes provide a variety of features in terminal emulators for performing operations such as positioning the cursor, changing the appearance of text with styles like bold, italic and strike-through, as well as foreground and background colors.

Creating ANSI strings

To create an ANSI string, we use the e"" interpolator. This works like an ordinary string interpolator, allowing substitutions of stringlike values.

But substitutions may also be Escape instances, which do not insert any visible characters, but may change the appearance or style of subsequent characters. Many Escape instances are defined in the escapes object, for example, Bold, Underline and BrightRedFg.

These escapes may be used in an ANSI string, like so:

import escapes.*
val txt = e"This text is ${Bold}bold, ${Underline}underlined and ${BrightRedFg}bright red."

This introduces the bold and underline styles and the bright red color to the string, but once introduced, they continue indefinitely.

Thankfully, Escapade provides a convenient way to terminate styles introduced by ANSI escapes. If the character immediately following the escape is a recognized opening bracket ((, [, {, «, <), then the style will continue until a corresponding closing brace is found in the string, i.e. ), ], }, » or >.

For example,

e"This text is $Bold[bold], $Underline{underlined} and $BrightRedFg<bright red>."

will apply each style only to the words inside the brackets.

Plenty of choice is given over which type of brackets to use, so that a choice can (hopefully) be made which does not conflict with the real content of the string. Regions may be nested arbitrarily deep, and different bracketing styles may be used, but nested regions form a stack which must be terminated in order. So any closing bracket other than the type corresponding to the most recent opening bracket will not be given special treatment.

For example,

e"This text is $Bold[bold and $Italic{italic] text.}"

might be intending to display the final word, text, in italic but not bold. But the mismatched brackets would treat italic] text. as literal text, rendered in italic. And, in fact, the ANSI string would not compile due to the unclosed [ bracket.

Combining colors

While styles such as bold, italic, underline and reverse may be combined independently in a string, the situation is more complex with colors, as a new color simply replaces an old one, and it is not normally possible to restore the previous color; only to "reset" the color.

Indeed, this is what happens using the standard ANSI escapes provided in the escapes object.

But Escapade also provides stack-based tracking for colored text, so that regions may be nested, and the underlying color may be restored. This uses colors from Iridescence which may be substituted straight into an ANSI string, like so:

import iridescence.*
import colors.*
e"$Gold[gold, $Indigo[indigo, $HotPink[hot pink], indigo] $White[and] gold]"

Manipulating colors

Each substitution into an e"" string interpolator may apply a change to the existing style, represented by and tracked throughout the string as an instance of the case class, Style. Typically, these changes will specify the new state of properties such as bold, italic or the background color.

But the changes may also be a transformation of the existing style information. For example, the bold state could be flipped depending on what it was before, or the foreground color could be mixed with black to give a "faded" or "darkened" effect to the text, without changing its hue.

Any such transformation requires an object to be used as a substitution to an interpolated string to introduce it, plus a corresponding contextual Stylize instance, for example:

case class Fade(amount: Double)

given Stylize[Fade] = fade =>
  Stylize { style =>
    style.copy(fg = style.fg.hsv.shade(fade.amount).srgb)
  }

Status

Escapade is classified as fledgling. For reference, Soundness projects are categorized into one of the following five stability levels:

  • embryonic: for experimental or demonstrative purposes only, without any guarantees of longevity
  • fledgling: of proven utility, seeking contributions, but liable to significant redesigns
  • maturescent: major design decisions broady settled, seeking probatory adoption and refinement
  • dependable: production-ready, subject to controlled ongoing maintenance and enhancement; tagged as version 1.0.0 or later
  • adamantine: proven, reliable and production-ready, with no further breaking changes ever anticipated

Projects at any stability level, even embryonic projects, can still be used, as long as caution is taken to avoid a mismatch between the project's stability level and the required stability and maintainability of your own project.

Escapade is designed to be small. Its entire source code currently consists of 558 lines of code.

Building

Escapade will ultimately be built by Fury, when it is published. In the meantime, two possibilities are offered, however they are acknowledged to be fragile, inadequately tested, and unsuitable for anything more than experimentation. They are provided only for the necessity of providing some answer to the question, "how can I try Escapade?".

  1. Copy the sources into your own project

    Read the fury file in the repository root to understand Escapade's build structure, dependencies and source location; the file format should be short and quite intuitive. Copy the sources into a source directory in your own project, then repeat (recursively) for each of the dependencies.

    The sources are compiled against the latest nightly release of Scala 3. There should be no problem to compile the project together with all of its dependencies in a single compilation.

  2. Build with Wrath

    Wrath is a bootstrapping script for building Escapade and other projects in the absence of a fully-featured build tool. It is designed to read the fury file in the project directory, and produce a collection of JAR files which can be added to a classpath, by compiling the project and all of its dependencies, including the Scala compiler itself.

    Download the latest version of wrath, make it executable, and add it to your path, for example by copying it to /usr/local/bin/.

    Clone this repository inside an empty directory, so that the build can safely make clones of repositories it depends on as peers of escapade. Run wrath -F in the repository root. This will download and compile the latest version of Scala, as well as all of Escapade's dependencies.

    If the build was successful, the compiled JAR files can be found in the .wrath/dist directory.

Contributing

Contributors to Escapade are welcome and encouraged. New contributors may like to look for issues marked beginner.

We suggest that all contributors read the Contributing Guide to make the process of contributing to Escapade easier.

Please do not contact project maintainers privately with questions unless there is a good reason to keep them private. While it can be tempting to repsond to such questions, private answers cannot be shared with a wider audience, and it can result in duplication of effort.

Author

Escapade was designed and developed by Jon Pretty, and commercial support and training on all aspects of Scala 3 is available from Propensive OÜ.

Name

An escapade is a "wild and exciting undertaking" which is "not necessarily lawful"; like the variety of escape codes that are only valid inside an ANSI terminal.

In general, Soundness project names are always chosen with some rationale, however it is usually frivolous. Each name is chosen for more for its uniqueness and intrigue than its concision or catchiness, and there is no bias towards names with positive or "nice" meanings�since many of the libraries perform some quite unpleasant tasks.

Names should be English words, though many are obscure or archaic, and it should be noted how willingly English adopts foreign words. Names are generally of Greek or Latin origin, and have often arrived in English via a romance language.

Logo

The logo shows a hot-air balloon, indicative of an escapade.

License

Escapade is copyright © 2024 Jon Pretty & Propensive OÜ, and is made available under the Apache 2.0 License.

escapade's People

Contributors

propensive avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

escapade's Issues

Find a good way to test rendering

The way ANSI strings are rendered is not tested, except by looking at them to see if they seem right. It seems to work, but complex combinations of escapes are rarely used in practice, and any tests usually require a user to visually check that the text is rendered correctly in a terminal (and also to know what the correct rendering should look like).

Character escapes do not work in `ansi""` strings

Escapes such as \n and \t are treated as literals inside ansi"" interpolated strings. The workaround is to embed a character (e.g. ansi"${'\n'}", but it's a lot of ceremony and is easily forgotten. There's code in Gossamer to expand standard escaped characters.

Use TTY environment variable to decide on rendering

The $TTY environment variable should contain enough information to determine whether the current terminal supports all or any Escapade's output features, notably color. This environment could be provided through a context value in print methods.

Update documentation

Amongst other problems, the documentation still refers to the interpolator as ansi"" rather than e"".

Use an opaque type (`Long`) to represent style

The combination of foreground/background color, bold, underline, italic, etc, could all be represented with a single Long which would be much faster than the current implementation using object copying.

Define escapes as ranges instead of push/pop

Escapes are currently represented as a pair of objects, a "push" and a "pop", which add and then remove a style from the text. These are stored independently, which does not make so much sense as storing each pair as a single "range" object.

Zero-length ranges should not add escapes

A zero-length range, e.g. out"$Red(${t""})" should not emit any escape codes, since doing so may cause unreliable rendering. In particular, they can clobber subsequent escapes.

Investigate character widths

Escapade assumes that every character is rendered as a single "cell" in the terminal, however zero-width spaces and double-width characters may deviate from this assumption, and there's currently no way to know the rendered width, even though this would be useful for Escritoire.

Standard Java functions don't seem to exist for determining the render width from a character (and it might be font-dependent and terminal dependant—this should be checked). One possible way to work it out would be to attempt to render each and every character in the terminal, checking the cursor position before and after rendering. This "profile" could then be saved... but more likely it's standard anyway.

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.