===== JQuery Terminal Emulator Plugin - Api Reference =====
[[http://terminal.jcubic.pl/api_reference.php|Originalartikel]]
[[https://www.qgelm.de/wb2html/wb93.html|Backup]]
To create terminal you must pass interpreter function (as first argument) which will be called when you type enter. Function has two argumentss command that user type in terminal and terminal instance. Optionally you can pass string as first argument, in this case interpreter function will be created for you using passed string as URI (path to file) of JSON-RPC service (it's ajax so must be on the same server).
$('#some_id').terminal(function(command) {
if (command == 'test') {
this.echo("you just typed 'test'");
} else {
this.echo('unknown command');
}
}, { prompt: '>', name: 'test' });
You can pass object as first argument - the methods will be invoked by commands typed by a user. In those methods this will point to terminal object.
$('#some_id').terminal({
echo: function(arg1) {
this.echo(arg1);
},
rpc: 'some_file.php',
calc: {
add: function(a, b) {
this.echo(a+b);
},
sub: function(a, b) {
this.echo(a-b);
}
}
}, { prompt: '>', greeting: false });
This code will create two command echo that will print first argument and add that will add two integers.
From version 0.8.0 you can also use array with strings, objects and functions. You can use multiple number of objects and strings and one function (that will be called last if no other commands found). If you have ignoreSystemDescribe function enabled you will be able to use only one string (JSON-RPC url). If you have completion enabled then your commands will be that from objects and JSON-RPC that have system.describe
$('#some_id').terminal(["rpc.php", {
"mysql": function() {
this.push(function(command, term) {
$.jrpc("rpc.php", 'mysql', [command], function(json) {
term.echo(json.result);
});
}, {
prompt: 'mysql> '
);
}
}], {
prompt: '>',
greeting: false
});
In previous example mysql will be exception, even that rpc have that method it will not call it but create new interpreter.
Terminal will always process numbers if processArguments is set to true (by default).
This is list of options (for second argument):
You will have access to terminal object in this object when you put object as first argument. In second argument if you put a function. That object is also returned by the plugin itself. The terminal is created only once so you can call that plugin multiple times. The terminal object is jQuery object extended by methods listed below.
This is list of available methods (you can also use jQuery methods):
- clear() — clear terminal.
- pause([boolean])/resume() — if your command will take some time to compute (like in AJAX call) you can pause terminal (terminal will be disable and command line will be hidden) and resume it in AJAX response is called. (if you want proper timing when call exec on array of commands you need to use those functions). From version 0.11.1 pause accept optional boolean argument that indicate if command line should be visible (this can be used with animation).
- paused() — return true if terminal is paused.
- echo([string|function], [options]) — display string on terminal — (additionally if you can call this function with a function as argument it will call that function and print the result, this function will be called every time you resize the terminal or browser).
There are five options:
- raw — it will allow to display raw html,
- finalize — which is callback function with one argument the div container,
- flush — default is true, if it's false it will not print echo text to terminal until you call flush method,
- wrap — default is undefined, if set to true or false it will overwritten global option,
- keepWords — it will not break text in the middle of the word (available from version 0.10.0).
You can also use basic text formating using syntax as folow: [[!guib;<COLOR>;<BACKGROUND>]some text] will display some text:
- [[ — open formating.
- u — underline.
- s — strike.
- o — overline.
- i — italic.
- b — bold.
- g — glow (using css text-shadow).
- ! — it will create link instead of span,
you need to turn off convertLinks option for this to work.
- ; — separator
- color — color of text (hex, short hex or html name of the color).
- ; — separator.
- color — background color (hex, short hex or html name of the color).
- ; — separator [optional].
- class — class adeed to format span element [optional].
- ; — separator [optional].
- text — text that will be used in data-text attribute or href it used with ! this is added automatically by split_equal function.
- ] — end of format specification.
- text — text that will be formated (most of the time for internal use, when you format text that's wrap in more then one line you'll get full text in data-text attribute, it's used also for href attribute for links).
- ] — end of formating.
From version 0.4.19 terminal support ANSI formatting like \x1b[1;31mhello[0m will produce red color hello. Here is shorter description of ansi escape codes.
From version 0.7.3 it also support Xterm 8bit (256) colors (you can test using this GNU Head) and formatting output from man command (overtyping).
From version 0.8.0 it support html colors like blue, navy or red
From version 0.9.0 Ansi escape code require unix_formatting.js file.
From version 0.9.0 you can execute commands using echo (you can return command to be executed from server) using same syntax as for formatting, if you echo: [[command arg1 arg2...]] it will execute that command.
If you want to execute terminal methods from JSON-RPC you can use code like this:
$(function() {
$('body').terminal([{
exec: function(name) {
var args = [].slice.call(arguments, 1);
if (this[name]) {
if (name == 'signature') {
// if you echo signature function it will change on resize
this.echo(this[name]);
} else {
var ret = this[name].apply(this, args);
if (ret != this) {
this.echo(ret);
}
}
} else {
this.error('Command not found');
}
}
}, "rpc-service"], {
checkArity: false
});
});
Then you can execute command from server by returning string "[[exec command arg1 arg2 ...]]" for instance "[[exec clear]]" or "[[exec purge]]".
- error([string|function]) — it display string in in red.
- exception(Error, [Label]) — display exception with stack trace on terminal (second paramter is optional is used by terminal to show who throw the exception).
- level() — return how deeply nested in interpreters you correctly in (It start from 1).
- last_index() — return index of last line that can be use with update method after you echo something and you lost the reference using -1.
- login([function(user, password, callback), boolean]) — execute login function the same as login option but first argument need to be a function. The function will be called with 3 arguments, user, password and a function that need to be called with truthy value that will be stored as token. Each interpreter can have it's own login function (you will need call push function and then login. The token will be stored localy, you can get it passing true to token function. Second argument indicate if terminal should ask for login and password infinitely.
- exec([string, bool]) — Execute command that like you where type it into terminal (it will execute user defined function). Second argument is optional if set to true, it will not display prompt and command that you execute. If you want to have proper timing of executed function when commands are asynchronous (use ajax) then you need to call pause and resume (make sure that you call pause before ajax call and resume as last in ajax response).
- scroll([number]) — you can use this method to scroll manually terminal (you can pass positive or negative value).
- logout() — if you use authentication it will logout from terminal. If you don't set login option this function will throw exception.
- flush() — if you echo using option
flush: false (it will not display text immediately) then you can send that text to the terminal output using this function.
- token([boolean]) — return token which was set in authentication process or by calling login function. This is set to null if there is no login option. If you pass true as an argument you will have local token for the interpreter (created using push function) it will return null if that interpreter don't have token.
- set_token([string, boolean]) — update token.
- get_token([boolean]) — same as token().
- login_name() — return login name which was use in authentication. This is set to null if there is no login option.
- set_prompt([string|function(callback)]) — change the prompt.
- next() — if you have more then one terminal instance it will switch to next terminal (in order of creation) and return reference to that terminal.
- cols()/rows() — returns number of characters and number of lines of the terminal.
- history() — return command line History object (need documentation - for now you can check the source code)
- name() — return name of the interpreter.
- push([string|function], {object}) — push next interpreter on the stack and call that interpreter. First argument is new interpreter (the same as first argument to terminal). The second argument is a list of options as folow:
- name — to distinguish interpreters using command line history.
- prompt — new prompt for this terminal.
- onExit — callback function called on Exit.
- onStart — callback function called on Start.
- keydown — interpreter keydown event.
historyFilter — the same as in terminal in next version.
- completion — the same as in terminal.
- login — same as login main option or calling login method after push.
- keymap — same as keymap in terminal.
- mousewheel — interpreter based mousewheel handler.
- infiniteLogin — if set to true it will ask infinetly for username and password if login is set.
Additionally everything that is passed within the object will be stored with interpreter on the stack — so it can be pop later. See also Multiple intepreters example.
- pop() — remove current interpreter from the stack and run previous one.
- focus([bool]) — it will activate next terminal if argument is false or disable previous terminal and activate current one. If you have only one terminal instance it act the same as disable/enable.
- enable()/disable() — as names says it enable or disable terminal.
- destroy() — remove everything created by terminal. It will not touch local storage, if you want to remove it as weel use purge.
- purge() — remove all local storage left by terminal. It will act like logout because it will remove login and token from local storage but you will not be logout until you refresh the page.
- resize([number, number] — change size of terminal if is called with two arguments (width,height) it will resize using this values. If is called without arguments it will act like refresh and use current size of element (you can use this if you set size in some other way).
- signature() — return JQuery Singature depending on size of terminal.
- get_command() — return current command.
- insert(string) — insert text in cursor position.
- export_view() — return object that can be use to restore the view using import_view.
- import_view([view]) — restore the view of the terminal using object returned prevoiusly by export_view.
- set_prompt([string|function]) — set prompt.
- get_prompt() — return current prompt.
- set_command(string) — set command using string.
- set_mask([bool|string]) — toogle mask of command line if argument is true it will use maskChar as mask.
- get_output([boolean]) — return string contains whatever was print on terminal, if argument is set to true it will return raw lines data.
- freeze([boolean])/frozen() — freeze: disable/enable terminal that can't be enabled by clicking on terminal, frozen check if terminal has been frozen by freeze command.
- read([string, function]) — wrapper over push, it set prompt to string and wait for text from user then call user function with entered string.
- autologin([username, token]) — autologin if you get username and token in other way, like in sysend event.
- save_state([command, boolean]) — it save current state of the terminal and update the hash. If second argument is true it will not update hash.
- history_state([boolean]) — disable or enable history sate save in hash. You can create commads that will start or stop the recording of commands, the commands itself will not be recorded.
- clear_history_state() — clear saved history state.
- reset() — reinitialize the terminal.
- prefix_name([boolean]) — return name that is used for localStorage keys, if argument is true it will return name of local interpreter (added by push() method).
- settings() — return reference to settings object that can change options dynamicaly. Note that not all options can be change that way, like history based options.
- set_interpreter([interpreter, login]) — overwrite current interpreter.
- is_bottom() — return true if terminal scroll is at the bottom. It use scrollBottomOffset option to calculate how much from bottom it will consider at bottom.
- scroll_to_bottom() — as the name suggest is scroll to the bottom of the terminal.
- complete([array, options]) — automplete text based on array, usefull if custom autocomplete need to be implemended, see autocomplete example. There are two options word — to indicate of completion should be for whole command or only a word before cursor (default true) and echo that indicate if it should echo matched commands if more then one found (default false).
- before_cursor([boolean]) — get string before cursor if the only argument is true it will return word otherwise it will return whole text.
Object $.terminal contain bunch of utilities use by terminal, but they can also be used by user code.
- split_equal([string], [number]) — return array. It split text into equal length lines and keep terminal formatting in place for displaying each line separately.
- encode([string]) — encode &, new line, space, tabs, < and > with entities.
- format([string, object] — create html <span> elements from terminal formattings. Second argument are options with one option linksNoReferrer.
- format_split([string]) — return array of formatting and text between them.
- escape_brackets([string]) — replace [ and ] with number entities.
- escape_regex([string]) — covert string that can be use in regex (RegExp constructor) literally.
- have_formatting([string]) — test if string have terminal formatting inside.
- is_formatting([string]) — test it string is full formatting (contain only one formatted text and nothing else).
- strip([string]) — remove formatting from text.
- active() — return selected terminal.
- last_id() — return id of the last terminal. If you add 1 to that number it will be id of the next terminal.
- ansi_colors — object contain 4 objects normal, fainted, bold and pallete (8bit colors) that contains hex colors for ansi formatting (taken from linux terminal emulator), NOTE: from version 0.9.0 provided by unix_formatting.js file.
- palette — array of 8bit XTerm colors. NOTE: from version 0.9.0 provided by unix_formatting.js file.
- overtyping([string]) — convert string containing formatting from man command (overtyping) to terminal formatting. If used with format it will produce html from man. NOTE: from version 0.9.0 provided by unix_formatting.js file.
- from_ansi([string]) — convert ANSI encoding to terminal encoding. If used with format it will produce html from ANSI encoding. NOTE: from version 0.9.0 provided by unix_formatting.js file.
- parse_arguments([string]) — return array from command line string. It process number (integer and floats) and regexes, it also convert escaped \x \0 to real characters when inside double quote. It remove enclosing quotes from strings.
- split_arguments([string]) — similar to parse_arguments but convert only escape space to space and remove enclosing quotes from strings.
- parse_command([string]) — return object with keys: name, args and rest that contain name of the command, it's arguments and string without command name. It use parse_arguments function.
- split_command([string]) — similar to parse_command but use split_arguments.
- defaults — contain all default options used by terminal plugin. All strings are in defaults.strings and can be translated.
- normalize([string]) — function that add extra last item in formatting if not present (added in 1.3.0) .
- substring([string, start_index, end_index]) — return subset of the string keeping formatting, end_index is optional (added in 1.3.0) .
- unclosed_strings([string]) — return true if string have unclosed strings, it's used when parsing command for internal use (rpc or object interpreter) if return true it will throw exception (added in 1.3.0).
- iterate_formatting([string, callback(data)]) — helper function used in substring and split_equal that iterate over string and execute callback when in text with object:
- count: number of characters in text (it skip brackets and formatting)
- index: character index (including brackets and formatting)
- formatting: string containing current formatting if itration is in formatting or empyt string if not
- space: index of last space
Function added in 1.3.0
Command Line is created as separate plugin, so you can create instance of it (if you don't want whole terminal):
$('#some_id').cmd({
prompt: '$> ',
width: '100%',
commands: function(command) {
//process user commands
}
});
Command Line options: name, keypress, keydown, mask, enabled, width, prompt, commands, keymap.
This is a list of methods if you are what to use only command line.
- name([string]) — if you pass string it will set name of the command line (name is use for tracking command line histor) or if you call without argument it will return name.
- history() — returns instance of history object.
- set(string, [bool]) — set command line (optional parameter is is set to true will not change cursor position).
- insert(string, [bool]) — insert string to command line in place of the cursor if second argument is set to true it will not change position of the cursor.
- get() — return current command.
- commands([function]) — set or get function that will be called when user hit enter.
- destroy() — remove plugin.
- prompt([string|function]) — set prompt to function or string — if called without argument it will return current prompt.
- position([number]) — set or get position of the cursor.
- resize([number]) — set numbers of characters — if called with number it will set number of character if call without argument it will recalculate the number of characters depending on actual size.
- enable/disable/isenabled — guess what they do.
- mask([string]) — if argument is true it will mask all typed characters with provided string. If called without argument it will return current mask.
This is list of keyboard shortcuts (mostly taken from bash):
- TAB — tab completion is available or tab character.
- Shift+Enter — insert new line.
- Up Arrow/CTRL+P — show previous command from history.
- Down Arrow/CTRL+N — show next command from history.
- CTRL+R — Reverse Search through command line history.
- CTRL+G — Cancel Reverse Search.
- CTRL+L — Clear terminal.
- CTRL+Y — Paste text from kill area.
- Delete/backspace — remove one character from right/left to the cursor.
- Left Arrow/CTRL+B — move left.
- CTRL+TAB — swich to next terminal (use scrolling with animation) — don't work in Chrome.
- Right Arrow/CTRL+F — move right.
- CTRL+Left Arrow — move one word to the left.
- CTRL+Right Arrow — move one word to the right.
- CTRL+A/Home — move to beginning of the line.
- CTRL+E/End — move to end of the line.
- CTRL+K — remove the text after the cursor and save it in kill area.
- CTRL+U — remove the text before the cursor and save it in kill area.
- CTRL+V/SHIFT+Insert — insert text from system clipboard.
- CTRL+W — remove text to the begining of the word (don't work in Chrome).
- CTRL+H — remove text to the end of the line.
- ALT+D — remove one word after the cursor — don't work in IE.
- PAGE UP — scroll up — don't work in Chrome.
- PAGE DOWN — stroll down — don't work in Chrome.
- CTRL+D — run previous interpreter from the stack or call logout (if terminal is using authentication and current interpreter is the first one). It also cancel all ajax call, if terminal is paused, and resume it.
Additional terminal controls
All interpreters have attached mousewheel event so you can stroll them using mouse. To swich between terminals you can just click on terminal that you want to activate (you can also use focus method).
If you select text using mouse you can paste it using middle mouse button (from version 0.8.0).
To change color of terminal simply modify "jquery.terminal.css" file it's really short and not complicated, but you should set inverted class background-color to be the same as color of text.
To change color of one line you can call css jquery method in finalize function passed to echo function.
terminal.echo("hello blue", {
finalize: function(div) {
div.css("color", "blue");
}
});
You can also use formating using echo function. To change whole terminal colors see style section.
All strings used by the plugin are located in $.terminal.defaults.strings object, so you can translate them and have i18n.
All exceptions in user functions (interpreter, prompt, and greetings) are catch and proper error is displayed on terminal (with stack trace). If you want to handle exceptions differently you can add exceptionHandler option and create different logic, for instance send exceptions to server or show just exception name without stack trace.
From version 0.8.0 blinking cursor is created using CSS3 animations (if available) so you can change that animation anyway you like, just look at jquery.terminal.css file. If browser don't support CSS3 animation blinking is created using JavaScript.
To change color of the cursor to green and backgroud to white you can use this css:
.terminal, .cmd {
background: white;
color: #0f0;
}
.terminal .inverted, .cmd .inverted, .cmd .cursor.blink {
background-color: #0f0;
color: white;
}
@-webkit-keyframes terminal-blink {
0%, 100% {
background-color: #fff;
color: #0f0;
}
50% {
background-color: #0e0;
color: #fff;
}
}
@-ms-keyframes terminal-blink {
0%, 100% {
background-color: #fff;
color: #0f0;
}
50% {
background-color: #0e0;
color: #fff;
}
}
@-moz-keyframes terminal-blink {
0%, 100% {
background-color: #fff;
color: #0f0;
}
50% {
background-color: #0e0;
color: #fff;
}
}
@keyframes terminal-blink {
0%, 100% {
background-color: #fff;
color: #0f0;
}
50% {
background-color: #0e0;
color: #fff;
}
}
From version 1.0.0 you can use css variables with code like this:
.terminal {
--color: rgba(0, 128, 0, 0.99);
--background: white;
}
If you want to have consistent selection you should use rgba color with 0.99 transparency, see this stackoverflow answer.
The only caveat is that css variables are not supported by IE nor Edge.
To change cursor to vertical bar you can use this css:
.cmd .cursor.blink {
color: #aaa;
border-left: 1px solid #aaa;
background-color: black;
margin-left: -1px;
}
.terminal .inverted, .cmd .inverted, .cmd .cursor.blink {
border-left-color: #000;
}
@-webkit-keyframes terminal-blink {
0%, 100% {
border-left-color: #aaa;
}
50% {
border-left-color: #000;
}
}
@-ms-keyframes terminal-blink {
0%, 100% {
border-left-color: #aaa;
}
50% {
border-left-color: #000;
}
}
@-moz-keyframes terminal-blink {
0%, 100% {
border-left-color: #aaa;
}
50% {
border-left-color: #000;
}
}
@keyframes terminal-blink {
0%, 100% {
border-left-color: #aaa;
}
50% {
border-left-color: #000;
}
}
From 1.0.0 version you can simplify this using this css:
.terminal {
--color: rgba(0, 128, 0, 0.99);
--background: white;
--animation: terminal-bar;
}
If you need to support IE or Edge you can set animation using:
.cmd .cursor.blink {
-webkit-animation-name: terminal-underline;
-moz-animation-name: terminal-underline;
-ms-animation-name: terminal-underline;
animation-name: terminal-underline;
}
.terminal .inverted, .cmd .inverted {
border-bottom-color: #aaa;
}
Or this css for bar cursor:
.cmd .cursor.blink {
-webkit-animation-name: terminal-bar;
-moz-animation-name: terminal-bar;
-ms-animation-name: terminal-bar;
animation-name: terminal-bar;
}
.terminal .inverted, .cmd .inverted {
border-left-color: #aaa;
}
To change the color of the cursor with differerent animation that will work in IE or Edge you will need to create new @keyframes with different colors, like in previous examples.
To change font size of the terminal you can use this code:
.terminal, .cmd, .terminal .terminal-output div div, .cmd .prompt {
font-size: 20px;
line-height: 24px;
}
Or from version 1.0.0 (and if you don't care about IE or Edge) you can simplify the code using --size css variables like this:
.terminal {
--size: 2;
}
The size is relative to original size so 1 is normal size 2 is double size.
You can take a look at the demo.
There are 3 keyboard events (all of them you can add in terminal, cmd and push command):
- keymap — simpler events you can add uppercase shortcut like CTRL+V, the callback function is
function(e, original) {, the original is original function callback that can be called, because your function overwrite original behvaior.
- keydown — this event is fired before keymap so you can return false to prevent default keymap
- keypress — is used to handle inserting of characters if you want to prevent certain characters to be inserted you can return false for those characters.
Caveats: the shortcut CTRL+D is handled by both keydown and keymap. If terminal is paused is handled by keydown and if not in keymap. If you want to overwrite CTRL+D when terminal is paused you need to pass false to pauseEvents option and use keydown otherwise you need to add function to keymap.
You can provide your authentication function which will be called when user enter login and password. Function must have 3 arguments first is user name, second his password and third is callback function which must be called with token or falsy value if user enter wrong user and password. (You should call server via AJAX to authenticate the user).
You can retrieve token from terminal using token method on terminal instance. You can pass this token to functions on the server as first parameter and check if it's valid token.
If you set interpreter to string (it will use this string as URI for JSON-RPC service) you can set login function to string (to call custom method on service passed as interpreter) or true (it will call login method).
If you set URI of JSON-RPC service and login to true or string, it will always pass token as first argument to every JSON-RPC method.
Third party code and additional plugins
Terminal include this 3rd party libraries:
- Storage plugin by Dave Schindler.
- jQuery Timers.
- Cross-Browser Split 1.1.1 by Steven Levithan.
- jQuery Caret by Gideon Sireling.
- sprintf.js by Alexandru Mărășteanu.
terminal also define 2 helper functions:
- $.jrpc — JSON-RPC helper function.
- $.omap — version of map that handle objects.
$.json_stringify — terminal own JSON stringify, because prototype library used by biwascheme messed up JSON.stringify.
- $.fn.scroll_element — plugin that return scroll object for normal objects that the same object but for body element it return html or body depend on which one need to be scrolled.
- $.fn.resizer — helper plugin that execute callback when element is resized. If called with string 'unbind' it will remove the event. Based on ResizeSensor.js file from marcj/css-element-queries.