heapwolf / prompt-sync

a synchronous prompt for node.js
MIT License
211 stars 42 forks source link

Wrong cursor position with history and colored label #41

Open marmotz opened 4 years ago

marmotz commented 4 years ago

Hi,

I have a problem when I use a colored label (with \u001b[* characters) and I navigate throw history. On UP there is no problem, but on DOWN, cursor is at a wrong place.

I see that UP and DOWN have different code to display label and history and I don't know why.

So, I don't know if you should modify line 114 to be identical to line 99:

@@ -111,7 +111,7 @@ function create(config) {
               str = history.next();
               insert = str.length;
             }
-            process.stdout.write('\u001b[2K\u001b[0G'+ ask + str + '\u001b['+(insert+ask.length+1)+'G');
+            process.stdout.write('\u001b[2K\u001b[0G'+ ask + str);
             break;
           case '\u001b[D': //left arrow
             if (masked) break;

or if you should clean ask variable:

@@ -58,6 +58,7 @@ function create(config) {
       value = opts.value;
     }
     ask = ask || '';
+    var rawAsk = ask.replace(/\u001b\[(?:\d+;)\d+[a-zA-Z]/g, '');
     var echo = opts.echo;
     var masked = 'echo' in opts;
     autocomplete = opts.autocomplete || autocomplete;
@@ -111,7 +112,7 @@ function create(config) {
               str = history.next();
               insert = str.length;
             }
-            process.stdout.write('\u001b[2K\u001b[0G'+ ask + str + '\u001b['+(insert+ask.length+1)+'G');
+            process.stdout.write('\u001b[2K\u001b[0G'+ ask + str + '\u001b['+(insert+rawAsk.length+1)+'G');
             break;
           case '\u001b[D': //left arrow
             if (masked) break;

or another solution I didn't see.