Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Writing colored output to the console


The writefln function has a lot of formatting options for strings, but they always come out with the same default color. How can we create colored text output in D?

Getting ready

Download terminal.d from my Github repository to your project's directory.

How to do it…

Let's write colored output to the console by executing the following steps:

  1. Import terminal.

  2. Create an instance of Terminal with a linear output type.

  3. Set the foreground and background color with the terminal.color method.

  4. Write text with the terminal.write, terminal.writeln, terminal.writef, or terminal.writefln functions. They work the same way as the homonym functions in std.stdio.

  5. You can flush output with terminal.flush() if it isn't done soon enough automatically.

  6. Compile the program and terminal.d together with dmd yourfile.d terminal.d.

The following is the code:

import terminal;

void main() {
  auto terminal = Terminal(ConsoleOutputType.linear);
  terminal.color(Color.green, Color.red);
 ...