I am developing a small xterm.js
application (just getting started), and I am wondering how to get the text from the current line when the user presses enter. Here is the program:
var term = new Terminal();
term.open(document.getElementById('terminal'));
term.prompt = () => {
term.write('\r\n$ ');
};
term.writeln('This is a shell emulator.');
term.prompt();
term.on('key', function(key, ev) {
const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey;
if (ev.keyCode === 13) {
term.prompt();
console.log(curr_line);
var curr_line = ""
} else if (ev.keyCode === 8) {
// Do not delete the prompt
if (term.x > 2) {
curr_line = curr_line.slice(0, -1);
term.write('\b \b');
}
} else if (printable) {
curr_line += ev.key;
console.log(curr_line, ev.key)
term.write(key);
}
});
term.on('paste', function(data) {
term.write(data);
});
Example taken from the xterm.js homepage (and modified)
As you can see, my attempt involves adding to a line of text every time I get a key
event (or removing on backspace). However, this does not work because it is inside an asynchronous function.
Does xterm.js
ship with another function that allows you to get the current line content, or is there another workaround for it? My Google searches have been to no avail.
Not the most elegant solution, but by moving "curr_line" into the global scope, we can keep it persistent between "on key" events.
var term = new Terminal();
term.open(document.getElementById('terminal'));
term.prompt = () => {
term.write('\r\n$ ');
};
term.writeln('This is a shell emulator.');
term.prompt();
// Move curr_line outside of async scope.
var curr_line = '';
term.on('key', function(key, ev) {
const printable = !ev.altKey && !ev.altGraphKey && !ev.ctrlKey && !ev.metaKey;
if (ev.keyCode === 13) {
term.prompt();
console.log(curr_line);
curr_line = '';
} else if (ev.keyCode === 8) {
// Do not delete the prompt
if (term.x > 2) {
curr_line = curr_line.slice(0, -1);
term.write('\b \b');
}
} else if (printable) {
curr_line += ev.key;
console.log(curr_line, ev.key)
term.write(key);
}
});
term.on('paste', function(data) {
term.write(data);
});
Your question came up in my search for a similar solution, so thank you for submitting it! : )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With