javascriptjqueryjquery-terminal

How do I color text in JQuery Terminal that contains a backslash (\)?


I've been following this question to help me change the color of the output in JQuery Terminal, though the approach does not seem to work with backslashes.

Ideally, I'd want to be able to highlight certain text in a color (i.e., red) while the rest of the text is a color other than white (i.e., teal). The text regularly uses backslash, which results in a couple of errors that otherwise would not exist.

Here's a reproducible example below:

function highlight_all_occurences_of_x_in_text(text) {

text_list = text.split("");
output_list = [];

while (text_list.length > 0) {
    current_character = text_list.shift();
    
    if (current_character === 'x') {
        output_list.push('[[gb;red;black]');
        output_list.push('x');
        output_list.push(']');
    }
    else {
        output_list.push(current_character);
    }
}

return '[[gb;yellow;black]' + output_list.join('') + ']';
}

If I were to call highlight_all_occurences_of_x_in_text('\text') or even highlight_all_occurences_of_x_in_text('\\text'), I'd get the expected output.

But if I called highlight_all_occurences_of_x_in_text('\\x'), I'd get something like '][[gb;red;blackx]'.

How do I deal with this?


Solution

  • The solution is to use

    $.terminal.escape_brackets
    

    or

    $.terminal.escape_formatting
    

    both functions replace [ ] \ with HTML entities.

    The reason why this happens is that \] is an escaped bracket and if you have [[;yellow;]\] terminal will not close formatting and keep processing the rest as part of the text, event if after there is another formatting.

       
    function highlight_all_occurences_of_x_in_text(text) {
    
        var text_list = text.split("");
        var output_list = [];
        
        while (text_list.length > 0) {
            current_character = text_list.shift();
            
            if (current_character === 'x') {
                output_list.push('[[gb;red;black]');
                output_list.push('x');
                output_list.push(']');
            } else {
                var str = $.terminal.escape_formatting(current_character);
                output_list.push(str);
            }
        }
        
        return '[[gb;yellow;black]' + output_list.join('') + ']';
    
    }
    
    var term = $('body').terminal(highlight_all_occurences_of_x_in_text, {
      onInit() {
        this.echo('type any text to highlight x');
      }
    });
    :root {
      --size: 1.4;
    }
    <script src="https://cdn.jsdelivr.net/npm/jquery"></script>
    <script src="https://cdn.jsdelivr.net/npm/jquery.terminal/js/jquery.terminal.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/js-polyfills/keyboard.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/jquery.terminal/css/jquery.terminal.css" rel="stylesheet"/>