Ansi Modifier

Dart

Introduction

Ansi escape codes are used to modify the font style of console output and to move the terminal cursor (which is useful e.g. when displaying progress indicators).

Usage

Include ansi_modifier as a dependency in your pubspec.yaml file.

1. Changing the Font Style and Color of Console Output

The easiest way of changing the color and font style of console output is by using the String extension method style:

final s = 'The ' + 'red'.style(Ansi.red) + ' fox jumps '
  'over the ' + 'green'.style(Ansi.green + Ansi.italic) + ' fence.';
print(s);

On an Ansi compliant terminal, the code lines above produce the following console output: Console Output

The method style supports different edit modes that can be used to easily modify existing Ansi escape codes.

Click to show source code.
import 'package:ansi_modifier/ansi_modifier.dart';

void main(List<String> args) {
  // Create colorized strings.
  print('\nStyle string:'.style(Ansi.underline) + ': EditMethod.add (default)');
  final example =
      'blueberry'.style(Ansi.blueBright) +
      ' and ' +
      'green apple'.style(Ansi.greenBright);
  print(example);

  // Replace first font modifier code
  print(
    '\nReplace first Ansi escape code'.style(Ansi.underline) +
        ': EditMethod.replaceFirst',
  );
  print(
    example.style(Ansi.yellow + Ansi.bold, editMethod: EditMethod.replaceFirst),
  );

  // Replace all existing font modifier codes.
  print(
    '\nReplace all Ansi escape codes'.style(Ansi.underline) +
        ': EditMethod.replaceAll',
  );
  print(
    example.style(
      Ansi.redBright + Ansi.bold,
      editMethod: EditMethod.replaceAll,
    ),
  );

  // Clear previous font modifiers and re-style entire string.
  print(
    '\nClear previous Ansi codes and style entire string'.style(
          Ansi.underline,
        ) +
        ': EditMethod.clearExisting',
  );
  print(example.style(Ansi.magenta, editMethod: EditMethod.clearExisting));

  // Keep existing Ansi escape codes and add styling.
  print(
    '\nAmend existing modifiers'.style(Ansi.underline) +
        ': EditMethod.addToExisting'.style(Ansi.underline),
  );
  print(example.style(Ansi.italic, editMethod: EditMethod.addToExisting));

  // Strip all Ansi escape codes.
  print(
    '\nStrip all Ansi escape codes'.style(Ansi.underline) +
        ': clearStyle()'.style(Ansi.underline),
  );
  print(example.clearStyle());
}

The program above produces the following output: Console Output

Instead of using the convenience method style, one can use the Ansi escape codes that are available as constant static values of the extension type Ansi:

final s = 'The ${Ansi.red}fox${Ansi.reset} jumps over the
  ${Ansi.green}fence${Ansi.reset};

It is advisable to terminate styled strings with an Ansi code that resets the font style to the default style.

2. Moving the Current Cursor Position

Ansi escape codes for moving the current cursor position can be created by using the constructors Ansi.cursorUp, Ansi.cursorDown, Ansi.cursorForward, Ansi.cursorBack, Ansi.cursorNextLine, Ansi.cursorPreviousLine, and Ansi.cursorToColumn, and Ansi.cursorToPosition.

The example below shows how to change the cursor position using Dart's stdout function write in order to display a progress indicator:

import 'dart:io';

import 'package:ansi_modifier/src/ansi.dart';

void main(List<String> args) async {

  // Emit a periodic stream
  final stream = Stream<String>.periodic(
      const Duration(milliseconds: 500),
      (i) =>
          'Progress timer: '.style(Ansi.grey) +
          ((i * 500 / 1000).toString() + ' s').style(Ansi.green));

  // Listen to the stream and output progress indicator
  final subscription = stream.listen((event) {
    // Place cursor to first column to overwrite previous string.
    stdout.write(CursorModifier.toColumn(1));
    stdout.write(event);
  });

  /// Add delay ...
  await Future.delayed(Duration(seconds: 5), () {
    print('\n');
    print('After 5 seconds.'.style(Ansi.green));
  });

  await subscription.cancel();
}

The program above produces the following console output: Progress Indicator

Tips and Tricks

  • The function clearStyle can be used to remove all Ansi escape codes of type FontModifier from a string.
  • The String extension method style supports different replacement modes that can be adjusted using the optional argument editMethod.
  • Ansi codes can be combined using the addition operator Ansi.red + Ansi.bold.
  • Using the function `style to add Ansi codes provides the option of globally disabling Ansi output by setting:
    Ansi.status = AnsiOutput.disabled;
    
    When running a Dart script the same effect can be achieved by using the the option:
    $ dart --define=isMonochrome=true example/bin/color_example.dart
    

Features and bugs

If Ansi modifiers that are useful to you are missing, you are welcome to create a pull request or raise an enhancement request at the issue tracker.

Libraries

ansi_modifier