5

I find that adding color to the prompt in repl really helps to separate the outputs. I achieved this by using NPM's chalk, but this adds a bunch of space between the prompt and the cursor.

var term = repl.start({
    prompt: chalk.blue('goose> '),
    eval: function(cmd, context, filename, cb){
        ...
    }
});

The prompt comes out like this ('|' is the cursor):

goose>              |

Any ideas on how to fix?

Bill Johnston
  • 1,160
  • 1
  • 14
  • 31
  • Found [Relevant problem](http://stackoverflow.com/questions/12075396/adding-colors-to-terminal-prompt-results-in-large-white-space). Looks like the prompt length is set to the entire prompt string including the escape color characters. Not sure if it's possible to get what I want using repl. – Bill Johnston May 09 '14 at 20:10

2 Answers2

5

It turns out to be very simple:

var prompt = 'My fancy prompt >>> ';
rl.setPrompt(chalk.blue(prompt), prompt.length);

You need to specify the count of characters because readline doesn't understand that escape sequences are really displayed as zero width.

(This is based on Felix's answer.)

mik01aj
  • 11,928
  • 15
  • 76
  • 119
1

Run this before repl.start():

var readline = require('readline');
var hasAnsi = require('has-ansi');
var stripAnsi = require('strip-ansi');

var _setPrompt = readline.Interface.prototype.setPrompt;
readline.Interface.prototype.setPrompt = function() {
  if (arguments.length === 1 && hasAnsi(arguments[0])) {
    return _setPrompt.call(this, arguments[0], stripAnsi(arguments[0]).length);
  } else {
    return _setPrompt.apply(this, arguments);
  }
};

Dependencies: npm install has-ansi strip-ansi

Felix Rabe
  • 4,206
  • 4
  • 25
  • 34