
Syntax Highlighting
Syntax Highlighting 관련
As we discussed earlier, we can use custom syntax highlighting of our shell by pushing a function into $.terminal.defaults.formatters
.We can also use the $.terminal.new_formatter
helper function.
Let's make our commands white as we type them. The formatter can be an array (of regex and replacement), or a function. We have a fixed number of commands and we only want to make those that are on the list white. We can do this by adding a regular expression:
const any_command_re = new RegExp(`^\s*(${command_list.join('|')})`);
This regular expression will check if, at the beginning of the string, there is an optional whitespace and one of the commands. Right now the regex will look like this: /^\s*(help|echo)/
. This is how to create new formatter:
$.terminal.new_formatter([any_command_re, '<white>$1</white>']);
If you would like to make command arguments in different colors, you'll need a function, where you will use String::replace()
.
const re = new RegExp(`^\s*(${command_list.join('|')}) (.*)`);
$.terminal.new_formatter(function(string) {
return string.replace(re, function(_, command, args) {
return `<white>${command}</white> <aqua>${args}</aqua>`;
});
});
This is just an example of using String::replace
. If you have just one replacement, you can use an array. This will be the same:
const re = new RegExp(`^\s*(${command_list.join('|')})(\s?.*)`);
$.terminal.new_formatter([re, function(_, command, args) {
return `<white>${command}</white><aqua>${args}</aqua>`;
}]);
Note
If you add the class <white class="command">
to the formatter, you will be able to click on the typed command to execute it again.