### Quick examples Source: https://github.com/cronvel/terminal-kit/blob/master/doc/documentation.md Some examples (note that if you execute all at once, some examples overwrite each other). ```javascript var term = require( 'terminal-kit' ).terminal ; // The term() function simply output a string to stdout, using current style // output "Hello world!" in default terminal's colors term( 'Hello world!\n' ) ; // This output 'red' in red term.red( 'red' ) ; // This output 'bold' in bold term.bold( 'bold' ) ; // output 'mixed' using bold, underlined & red, exposing the style-mixing syntax term.bold.underline.red( 'mixed' ) ; // printf() style formatting everywhere: // this will output 'My name is Jack, I'm 32.' in green term.green( "My name is %s, I'm %d.\n" , 'Jack' , 32 ) ; // Since v0.16.x, style markup are supported as a shorthand. // Those two lines produce the same result. term( "My name is " ).red( "Jack" )( " and I'm " ).green( "32\n" ) ; term( "My name is ^rJack^ and I'm ^g32\n" ) ; // Width and height of the terminal term( 'The terminal size is %dx%d' , term.width , term.height ) ; // Move the cursor at the upper-left corner term.moveTo( 1 , 1 ) ; // We can always pass additional arguments that will be displayed... term.moveTo( 1 , 1 , 'Upper-left corner' ) ; // ... and formated term.moveTo( 1 , 1 , "My name is %s, I'm %d.\n" , 'Jack' , 32 ) ; // ... or even combined with other styles term.moveTo.cyan( 1 , 1 , "My name is %s, I'm %d.\n" , 'Jack' , 32 ) ; // Get some user input term.magenta( "Enter your name: " ) ; var input = await term.inputField().promise ; term.green( "\nYour name is '%s'\n" , input ) ; // Cleanly exit : avoid having junk escape characters and restore default style. // Any interactive functions (like .inputFiled(), .yesOrNo(), etc) will open "stdin" and listen for events, // so the process will NOT exit except explicitly (or explicitly calling .grabInput( false )). term.processExit() ; ``` -------------------------------- ### Real Terminal (From TTY) Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/configuration.md For applications that need the actual terminal (not process stdio), this example shows how to get the real terminal instance, equivalent to creating a terminal with specific TTY and SIGWINCH handling. ```javascript const realTerm = termkit.realTerminal; // Equivalent to: const term = termkit.createTerminal({ stdin: termkit.tty.getInput(), stdout: termkit.tty.getOutput(), stderr: process.stderr, isTTY: true, processSigwinch: true }); ``` -------------------------------- ### Usage Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Palette.md Demonstrates how to create a custom palette with adaptive and extra colors, apply it to a ScreenBuffer, and use color names to get color indices. ```javascript const termkit = require('terminal-kit'); const term = termkit.terminal; // Create custom palette const palette = new termkit.Palette({ adaptivePaletteDef: [ { names: ['brandRed'], code: '#ff0000' }, { names: ['brandBlue'], code: '#0000ff' } ], extraPaletteDef: [ { names: ['gold'], code: '#ffd700' } ] }); // Apply to screen buffer const buffer = new termkit.ScreenBuffer({ width: 80, height: 24, dst: term, palette: palette }); // Use color names const colorIndex = palette.colorNameToIndex('brandRed'); const brightIndex = palette.colorNameToIndex('@brandBlue+'); const extraIndex = palette.colorNameToIndex('*gold'); console.log(`Red index: ${colorIndex}`); console.log(`Bright Blue index: ${brightIndex}`); console.log(`Gold index: ${extraIndex}`); // Or use terminal's color methods with palette term.setPalette(palette); term.color(palette.colorNameToIndex('brandRed'))('Red text\n'); term.color(palette.colorNameToIndex('@brandBlue+'))('Bright blue\n'); ``` -------------------------------- ### Usage Examples Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Utilities.md Various usage examples demonstrating terminal-kit functionalities. ```javascript const termkit = require('terminal-kit'); const term = termkit.terminal; // Convert hex color to RGB const rgb = termkit.hexToRgba('#ff0000'); console.log(`Red: RGB(${rgb.r}, ${rgb.g}, ${rgb.b})`); // Clean string with ANSI codes const text = '\x1b[31mRed text\x1b[0m with \x1b[1mbold\x1b[0m'; const width = termkit.stringWidth(text); // Correct width console.log(`Width: ${width}`); // Truncate with ANSI codes preserved const truncated = termkit.truncateAnsiString(text, 5); term(truncated); // Word wrap markup const markup = '^rThis ^gis ^bmulticolor ^-text'; const lines = termkit.wordWrapMarkup(markup, 10); lines.forEach(line => term(line + '\n')); // Format with markup const formatted = termkit.preserveMarkupFormat( '^r%s ^g%s', 'Hello', 'World' ); term(formatted); // Get color index from name const redIdx = termkit.colorNameToIndex('red'); term.color(redIdx)('Red text\n'); ``` -------------------------------- ### Global Configuration Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Terminal.md Example of setting a global configuration option for terminal-kit. ```javascript const termkit = require('terminal-kit'); termkit.globalConfig.preferProcessSigwinch = true; // Use process.SIGWINCH instead of stdout resize event ``` -------------------------------- ### Default Palette Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/configuration.md Example of how to get the default color palette for a terminal. ```javascript const termkit = require('terminal-kit'); // Get default palette const palette = new termkit.Palette({ term: termkit.terminal }); ``` -------------------------------- ### Usage Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/DocumentModel.md A comprehensive example demonstrating the creation of a terminal application document, including text, input fields, buttons, and event handling. ```javascript const termkit = require('terminal-kit'); const term = termkit.terminal; // Create document const doc = term.createDocument({ width: term.width, height: term.height }); // Create title doc.createElement(termkit.Text, { content: '^+^rMy Application', contentHasMarkup: true, x: 1, y: 1, key: 'title' }); // Create input field doc.createElement(termkit.InlineInput, { label: 'Name: ', x: 1, y: 3, width: 40, key: 'nameInput' }); // Create buttons const submitBtn = doc.createElement(termkit.Button, { text: 'Submit', x: 1, y: 5, key: 'submit' }); submitBtn.on('submit', () => { const name = doc.getElement('nameInput').value; console.log('Welcome, ' + name); doc.destroy(); term.processExit(); }); // Draw document doc.draw(); ``` -------------------------------- ### colorNameToIndex Method Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Palette.md Shows how to get the palette index for various color name syntaxes. ```javascript const index = palette.colorNameToIndex('red'); const index2 = palette.colorNameToIndex('@red+'); // Adaptive red (bright) const index3 = palette.colorNameToIndex('*crimson'); // Extra color ``` -------------------------------- ### Markup Syntax Examples Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/types.md Examples demonstrating the use of caret (^) for control sequences in markup, including colors, styles, and background colors. ```text "^rRed text" "^+^_Bold underline" "^#gGreen background" ``` -------------------------------- ### Quick example, featuring history and auto-completion Source: https://github.com/cronvel/terminal-kit/blob/master/doc/high-level.md This example demonstrates the usage of the .inputField() method with history and auto-completion features. ```javascript var term = require( 'terminal-kit' ).terminal ; var history = [ 'John' , 'Jack' , 'Joey' , 'Billy' , 'Bob' ] ; var autoComplete = [ 'Barack Obama' , 'George W. Bush' , 'Bill Clinton' , 'George Bush' , 'Ronald W. Reagan' , 'Jimmy Carter' , 'Gerald Ford' , 'Richard Nixon' , ``` -------------------------------- ### Default Terminal Instance Source: https://github.com/cronvel/terminal-kit/blob/master/doc/global-api.md Example of how to get the default terminal instance. ```javascript var term = require( 'terminal-kit' ).terminal ; ``` -------------------------------- ### Combined Example: Multi-Step Input Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/InputMethods.md A comprehensive example showcasing a multi-step user wizard using various input methods like inputField, yesOrNo, and singleLineMenu, along with a progressBar. ```javascript const term = termkit.terminal; async function userWizard() { try { // Step 1: Get name const name = await term.inputField({ prompt: 'Your name: ', minLength: 1 }).promise; term('\n'); // Step 2: Yes/No question const subscribe = await term.yesOrNo({ prompt: 'Subscribe to newsletter? ', default: true }).promise; term('\n'); // Step 3: Choose option const [index, choice] = await term.singleLineMenu( ['Email', 'SMS', 'Push'], { prompt: 'Preferred contact: ' } ).promise; term('\n'); // Show progress const progress = term.progressBar({ width: 40, title: 'Saving' }); for (let i = 0; i <= 100; i += 10) { progress.update(i / 100); await new Promise(r => setTimeout(r, 100)); } progress.stop(); term(`\nThank you, ${name}!\n`); return { name, subscribe, contact: choice }; } catch (error) { console.error('Input error:', error); throw error; } } // Run userWizard().then(result => { console.log('Result:', result); process.exit(0); }); ``` -------------------------------- ### Single Line Menu Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/high-level.md An example demonstrating how to create and use a single line menu with custom options and a callback function. ```javascript var term = require( 'terminal-kit' ).terminal ; var items = [ 'File' , 'Edit' , 'View' , 'History' , 'Bookmarks' , 'Tools' , 'Help' ] ; var options = { y: 1 , // the menu will be on the top of the terminal style: term.inverse , selectedStyle: term.dim.blue.bgGreen } ; term.clear() ; term.singleLineMenu( items , options , function( error , response ) { term( '\n' ).eraseLineAfter.green( "#%s selected: %s (%s,%s)\n" , response.selectedIndex , response.selectedText , response.x , response.y ) ; process.exit() ; } ) ; ``` -------------------------------- ### Progress Bar Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/high-level.md This example demonstrates how to create and manage a progress bar with items, showing the progress of various tasks. ```javascript var term = require( 'terminal-kit' ).terminal ; var progressBar ; var thingsToDo = [ 'update my lib' , 'data analyzing' , 'serious business' , 'decrunching data' , 'do my laundry' , 'optimizing' ] ; var countDown = thingsToDo.length ; function start() { if ( ! thingsToDo.length ) { return ; } var task = thingsToDo.shift() ; progressBar.startItem( task ) ; // Finish the task in... setTimeout( done.bind( null , task ) , 500 + Math.random() * 1200 ) ; // Start another parallel task in... setTimeout( start , 400 + Math.random() * 400 ) ; } function done( task ) { progressBar.itemDone( task ) ; countDown -- ; // Cleanup and exit if ( ! countDown ) { setTimeout( function() { term( '\n' ) ; process.exit() ; } , 200 ) ; } } progressBar = term.progressBar( { width: 80 , title: 'Daily tasks:' , eta: true , percent: true , items: thingsToDo.length } ) ; start() ; ``` -------------------------------- ### Usage Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/ScreenBufferHD.md Example of loading and displaying an image using ScreenBufferHD. ```javascript const termkit = require('terminal-kit'); const term = termkit.terminal; // Load and display image (async () => { try { const buffer = await termkit.ScreenBufferHD.loadImage( 'photo.png', { width: term.width, height: term.height, shrink: true, palette: new termkit.Palette({ term: term }) } ).promise; // Display image buffer.draw(); // Interactive mode term.grabInput(); term.on('key', (name) => { if (name === 'ESCAPE') { term.grabInput(false); process.exit(0); } }); } catch (error) { console.error('Error loading image:', error); process.exit(1); } })(); ``` -------------------------------- ### Quick example for yesOrNo Source: https://github.com/cronvel/terminal-kit/blob/master/doc/high-level.md This is a quick example demonstrating the usage of the terminal-kit's yesOrNo function to ask a user a yes/no question and handle their input. ```javascript var term = require( 'terminal-kit' ).terminal ; function question() { term( 'Do you like javascript? [Y|n]\n' ) ; // Exit on y and ENTER key // Ask again on n term.yesOrNo( { yes: [ 'y' , 'ENTER' ] , no: [ 'n' ] } , function( error , result ) { if ( result ) { term.green( "'Yes' detected! Good bye!\n" ) ; process.exit() ; } else { term.red( "'No' detected, are you sure?\n" ) ; question() ; } } ) ; } question() ; ``` -------------------------------- ### Interactive Menu Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/README.md An example demonstrating how to create and use an interactive single-column menu with terminal-kit. ```javascript const [index, text] = await term.singleColumnMenu( ['New Game', 'Load Game', 'Settings', 'Quit'] ).promise; ``` -------------------------------- ### Graphics and Animation Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/README.md An example showing how to use ScreenBuffer for graphics and animation in terminal-kit. ```javascript const buffer = new termkit.ScreenBuffer({ width: 80, height: 24, dst: term }); // ... draw to buffer buffer.draw(); ``` -------------------------------- ### Progress Bar Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/high-level.md An example demonstrating how to use the term.progressBar function to create and update a progress bar with title, ETA, and percentage display. ```javascript var term = require( 'terminal-kit' ).terminal ; var progressBar , progress = 0 ; function doProgress() { // Add random progress progress += Math.random() / 10 ; progressBar.update( progress ) ; if ( progress >= 1 ) { // Cleanup and exit setTimeout( function() { term( '\n' ) ; process.exit() ; } , 200 ) ; } else { setTimeout( doProgress , 100 + Math.random() * 400 ) ; } } progressBar = term.progressBar( { width: 80 , title: 'Serious stuff in progress:' , eta: true , percent: true } ) ; doProgress() ; ``` -------------------------------- ### parseMarkup Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/ScreenBuffer.md Example of parsing markup text with terminal-kit's style markup. ```javascript const text = buffer.parseMarkup( "^rRed^g Green ^-Dim^+Bold", { noMarkup: false } ); ``` -------------------------------- ### fileInput Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/high-level.md An example demonstrating the usage of the fileInput function to prompt the user for a file path with auto-completion relative to a specified base directory. ```javascript var term = require( 'terminal-kit' ).terminal ; term( 'Choose a file: ' ) ; term.fileInput( { baseDir: '../' } , function( error , input ) { if ( error ) { term.red.bold( "\nAn error occurs: " + error + "\n" ) ; } else { term.green( "\nYour file is '%s'\n" , input ) ; } process.exit() ; } ) ; ``` -------------------------------- ### Palette Integration Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/ScreenBufferHD.md Example of creating a ScreenBufferHD with a Palette for color mapping to terminal-compatible colors. ```javascript const palette = new termkit.Palette({ term: term }); const buffer = new termkit.ScreenBufferHD({ width: 80, height: 24, dst: term, palette: palette }); // Colors are mapped to nearest palette color for terminal output buffer.draw({ palette: palette }); ``` -------------------------------- ### Custom Terminal Configuration File Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/configuration.md Example of a custom terminal configuration file (`myterm.js`) defining escape sequences, terminal capabilities, and key mappings. ```javascript // lib/termconfig/myterm.js module.exports = { esc: { // Escape sequences red: { on: '\x1b[31m', off: '\x1b[0m' }, bold: { on: '\x1b[1m', off: '\x1b[0m' }, // ... more sequences }, support: { // Terminal capabilities '256colors': true, 'trueColor': false, // ... more capabilities }, keymap: { // Key mappings 'ESCAPE': '\x1b', 'ENTER': '\r', // ... more keys }, colorRegister: [ ... ], handler: { ... } }; ``` -------------------------------- ### ScreenBuffer Usage Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/ScreenBuffer.md A comprehensive example demonstrating the creation and usage of a ScreenBuffer, including filling, drawing text, and handling input. ```javascript const termkit = require('terminal-kit'); const term = termkit.terminal; // Create a buffer const buffer = new termkit.ScreenBuffer({ width: 60, height: 20, dst: term }); // Fill with background buffer.fill({ char: ' ', attr: { bgColor: 'blue' } }); // Draw some text buffer.put({ x: 5, y: 5, attr: { color: 'white', bold: true } }, 'Hello!'); buffer.put({ x: 5, y: 7, attr: { color: 'yellow' } }, 'Press any key...'); // Display the buffer buffer.draw(); // Handle input term.grabInput(); term.on('key', (name) => { if (name === 'ESCAPE') { term.grabInput(false); process.exit(0); } }); ``` -------------------------------- ### Single Column Menu Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/high-level.md An example demonstrating how to use the singleColumnMenu function to create an interactive menu in the terminal. ```javascript var term = require( 'terminal-kit' ).terminal ; term.cyan( 'The hall is spacious. Someone lighted few chandeliers.\n' ) ; term.cyan( 'There are doorways south and west.\n' ) ; var items = [ 'a. Go south' , 'b. Go west' , 'c. Go back to the street' ] ; term.singleColumnMenu( items , function( error , response ) { term( '\n' ).eraseLineAfter.green( "#%s selected: %s (%s,%s)\n" , response.selectedIndex , response.selectedText , response.x , response.y ) ; process.exit() ; } ) ; ``` -------------------------------- ### Image Composition Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/ScreenBufferHD.md Example of loading two images as ScreenBufferHD instances and compositing the foreground onto the background with blending. ```javascript // Create two buffers const bg = await termkit.ScreenBufferHD.loadImage('background.png', { width: 80, height: 24 }).promise; const fg = await termkit.ScreenBufferHD.loadImage('overlay.png', { width: 80, height: 24 }).promise; // Composite foreground onto background with blending bg.draw(); fg.draw({ blending: { mode: 'screen', opacity: 0.7 } }); ``` -------------------------------- ### Complex UI Application Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/README.md An example of building a complex UI application using the Document Model in terminal-kit. ```javascript const doc = term.createDocument({ width: term.width, height: term.height }); doc.createElement(termkit.Button, { text: 'Click me', x: 5, y: 2 }); doc.draw(); ``` -------------------------------- ### Example using .getDetectedTerminal() Source: https://github.com/cronvel/terminal-kit/blob/master/doc/global-api.md This example shows how to use .getDetectedTerminal() to get a terminal object with the best possible compatibility, using a callback to handle the result. ```javascript require( 'terminal-kit' ).getDetectedTerminal( function( error , term ) { term.cyan( 'Terminal name: %s\n' , term.appName ) ; term.cyan( 'Terminal app: %s\n' , term.app ) ; term.cyan( 'Terminal generic: %s\n' , term.generic ) ; term.cyan( 'Config file: %s\n' , term.termconfigFile ) ; } ) ; ``` -------------------------------- ### String Formatting Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/low-level.md Shows how to capture formatted output as a string using the .str() modifier. ```javascript var myString = term.str.blue( 'BLUE' ) ``` -------------------------------- ### get() method example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/ScreenBuffer.md Retrieves the character at a specific position in the buffer. ```javascript const char = buffer.get(5, 3); ``` -------------------------------- ### Example NOT using .getDetectedTerminal() Source: https://github.com/cronvel/terminal-kit/blob/master/doc/global-api.md This example demonstrates basic text output to the terminal using the .cyan() method, relying on environment variables for terminal detection. ```javascript var term = require( 'terminal-kit' ).terminal ; term.cyan( 'Hello world!' ) ; ``` -------------------------------- ### Grab Input Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/high-level.md Demonstrates how to grab keyboard and mouse input, and handle key, terminal, and mouse events. ```javascript var term = require( 'terminal-kit' ).terminal ; function terminate() { term.grabInput( false) ; setTimeout( function() { process.exit() } , 100 ) ; } term.bold.cyan( 'Type anything on the keyboard...\n' ) ; term.green( 'Hit CTRL-C to quit.\n\n' ) ; term.grabInput( { mouse: 'button' } ) ; term.on( 'key' , function( name , matches , data ) { console.log( "'key' event:" , name ) ; if ( name === 'CTRL_C' ) { terminate() ; } } ) ; term.on( 'terminal' , function( name , data ) { console.log( "'terminal' event:" , name , data ) ; } ) ; term.on( 'mouse' , function( name , data ) { console.log( "'mouse' event:" , name , data ) ; } ) ; ``` -------------------------------- ### Chaining Methods with Arguments Source: https://github.com/cronvel/terminal-kit/blob/master/doc/low-level.md Illustrates chaining methods like moveTo with formatting arguments. ```javascript term.moveTo.red( 1 , 1 , "My name is %s, I'm %d.\n" , 'Jack' , 32 ) ``` -------------------------------- ### getBackgroundEscapeSequence Method Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Palette.md Illustrates how to get the background ANSI escape sequence for a color index. ```javascript const bgEsc = palette.getBackgroundEscapeSequence(196); ``` -------------------------------- ### Custom Color Palette Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/README.md Example of creating a custom color palette and using a color name to get its index. ```javascript const palette = new termkit.Palette({ term }); const redIndex = palette.colorNameToIndex('red'); term.color(redIndex)('Red text\n'); ``` -------------------------------- ### Yes/No Prompt Usage Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/InputMethods.md Example of using the yesOrNo method to get a boolean answer from the user, with customizable keys for 'yes' and 'no'. ```javascript const answer = await term.yesOrNo({ yes: ['y', 'ENTER'], no: ['n'], default: true }).promise; if (answer) { console.log('User said yes'); } else { console.log('User said no'); } ``` -------------------------------- ### Get the closest 256-color index for hex color Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Terminal.md Example of using colorNameForHex to find the nearest color index for a given hex color. ```javascript const colorIndex = term.colorNameForHex('#FF0000'); ``` -------------------------------- ### Image Loading and Drawing Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/ScreenBufferHD.md Demonstrates how to load an image into a ScreenBufferHD, set up a target buffer with consistent colors, and draw the image onto it with blending enabled. ```javascript var screen = new ScreenBufferHD( { dst: term , noFill: true } ) ; screen.fill( attr: { // Both foreground and background must have the same color color: { r: 40 , g: 20 , b: 0 } , bgColor: { r: 40 , g: 20 , b: 0 } } ) ; ScreenBufferHD.loadImage( path_to_image , { shrink: { width: term.width , height: term.height * 2 } } , function( error , image ) { if ( error ) { throw error ; } // Doh! image.draw( { dst: screen , blending: true } ) ; screen.draw() ; } ) ; ``` -------------------------------- ### moveTo Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Terminal.md Shows how to move the cursor to a specific position and optionally output text, including chaining styles. ```javascript term.moveTo(1, 1); // Move to top-left term.moveTo(10, 5, 'Hello at column 10, row 5'); term.moveTo.cyan(10, 5, 'Colored text'); ``` -------------------------------- ### Spinner Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/InputMethods.md Demonstrates how to use the spinner component to show a loading animation during asynchronous operations. ```javascript const spinner = term.spinner({ animation: 'dots' }); spinner.start(); // Do work await doAsyncWork(); spinner.stop(); term('Work complete!\n'); ``` -------------------------------- ### Shift-F5 Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/XTerm Control Sequences.html Example of sending shift-F5 with parameters. ```text CSI 1 5 ; 2 ~ ``` -------------------------------- ### Create a Document for UI layouts Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Terminal.md Example of creating a Document instance with specified width and height. ```javascript const doc = term.createDocument({ width: term.width, height: term.height }); ``` -------------------------------- ### attrInverse Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/ScreenBuffer.md Example of inverting colors of an attribute. ```javascript const invertedAttr = termkit.ScreenBuffer.attrInverse(attr); ``` -------------------------------- ### Tabulation Clear Examples Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Examples of clearing tab stops. ```ansi [0g ``` ```ansi [1g ``` ```ansi [2g ``` ```ansi [3g ``` -------------------------------- ### Truecolor Bind Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/low-level.md Illustrates using .bindArgs() for truecolor styling with functions like term.bar(). ```javascript term.bar( 0.26 , { barStyle: term.colorRgbHex.bindArgs( '#650fbe' ) } ) ``` -------------------------------- ### Selection Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/TextBuffer.md Example demonstrating text selection, movement, retrieval, and deletion. ```javascript buffer.startSelection(0, 0); buffer.moveTo(40, 10); const selected = buffer.getSelectedText(); buffer.deleteSelectedText(); ``` -------------------------------- ### Set Mode Examples Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Examples of setting various terminal modes. ```ansi [0h ``` ```ansi [1h ``` ```ansi [2h ``` ```ansi [3h ``` ```ansi [4h ``` ```ansi [5h ``` ```ansi [6h ``` ```ansi [7h ``` ```ansi [8h ``` ```ansi [9h ``` ```ansi [10h ``` ```ansi [11h ``` ```ansi [12h ``` ```ansi [13h ``` ```ansi [14h ``` ```ansi [15h ``` ```ansi [16h ``` ```ansi [17h ``` ```ansi [18h ``` ```ansi [19h ``` ```ansi [20h ``` ```ansi [?1h ``` ```ansi [?2h ``` ```ansi [?3h ``` ```ansi [?4h ``` ```ansi [?5h ``` ```ansi [?6h ``` ```ansi [?7h ``` ```ansi [?8h ``` ```ansi [?9h ``` -------------------------------- ### Previous Page Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of scrolling backward to a previous page. ```ansi [1V ``` -------------------------------- ### Creating a Palette Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Palette.md Demonstrates how to create default, system, and custom palettes with different configurations. ```javascript const termkit = require('terminal-kit'); // Default adaptive palette const palette = new termkit.Palette({ term: termkit.terminal, system: false }); // System palette (uses terminal's built-in colors) const sysPalette = new termkit.Palette({ system: true }); // Custom palette with user-defined colors const customPalette = new termkit.Palette({ adaptivePaletteDef: [ { names: ['myred'], code: '#e32322' }, { names: ['mygreen'], code: '#25ad28' } ], extraPaletteDef: [ { names: ['custom'], code: '#ff00ff' } ] }); ``` -------------------------------- ### Scroll Down Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of scrolling the display down by a specified number of lines. ```ansi [4T ``` -------------------------------- ### Scroll Up Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of scrolling the display up by a specified number of lines. ```ansi [3S ``` -------------------------------- ### Auto-complete Source Examples Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/errors.md Shows valid and invalid configurations for the autoComplete option in input fields. ```javascript // Valid: array of strings term.inputField({ autoComplete: ['option1', 'option2'] }); // Valid: function returning string or array term.inputField({ autoComplete: (inputString) => { if (inputString.startsWith('op')) { return ['option1', 'option2']; } return inputString; } }); // Valid: async function term.inputField({ autoComplete: async (inputString) => { const results = await fetch(...); return results; } }); // Invalid: function with wrong signature // (Wrong: should accept 1 or 2 args, not 0) ``` -------------------------------- ### System Palette Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/configuration.md Example of creating a Palette instance that uses the terminal's built-in colors. ```javascript const sysPalette = new termkit.Palette({ system: true }); ``` -------------------------------- ### Escape Sequence Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/hterm-control-sequences-doc/hterm Control Sequences.html An example of an escape sequence with a two-byte structure, like ESC + #. ```text ESC+# (0x1b 0x23) ``` -------------------------------- ### Unsupported Image Format Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/errors.md Illustrates handling errors for unsupported image formats during loading. ```javascript // Supported formats: PNG, JPEG, GIF // Error if file format unsupported try { const buffer = await termkit.ScreenBuffer.loadImage( 'image.bmp' // BMP not supported ).promise; } catch (error) { console.error('Unsupported image format'); } ``` -------------------------------- ### Example Usage of .gridMenu() Source: https://github.com/cronvel/terminal-kit/blob/master/doc/high-level.md Demonstrates how to use .gridMenu() to display a list of files and folders from the current directory as an interactive grid menu. Upon selection, it prints the index, text, and coordinates of the chosen item. ```javascript var term = require( 'terminal-kit' ).terminal ; var fs = require( 'fs' ) ; term.cyan( 'Choose a file:\n' ) ; var items = fs.readdirSync( process.cwd() ) ; term.gridMenu( items , function( error , response ) { term( '\n' ).eraseLineAfter.green( "#%s selected: %s (%s,%s)\n" , response.selectedIndex , response.selectedText , response.x , response.y ) ; process.exit() ; } ) ; ``` -------------------------------- ### Image File Not Found Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/errors.md Demonstrates how to handle 'ENOENT' errors when an image file is not found. ```javascript try { const buffer = await termkit.ScreenBuffer.loadImage( '/nonexistent/image.png' ).promise; } catch (error) { if (error.code === 'ENOENT') { console.error('Image file not found'); } else { console.error('Image loading error:', error); } } ``` -------------------------------- ### Device Attributes Examples Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Examples of Device Attributes (DA) requests for terminal identification. ```ansi [c ``` ```ansi [?1;2c ``` ```ansi [>0c ``` -------------------------------- ### Simple CLI Application Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/configuration.md An example of a simple Command Line Interface (CLI) application using terminal-kit. It displays welcome messages, prompts the user to press any key, and then exits gracefully. ```javascript const termkit = require('terminal-kit'); const term = termkit.terminal; term.cyan('Welcome to MyApp\n'); term.yellow('Press any key...\n'); term.grabInput(); term.once('key', () => { term.grabInput(false); term.processExit(); }); ``` -------------------------------- ### Repeat Character Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of repeating a displayable character a specified number of times. ```ansi [80b ``` -------------------------------- ### Next Page Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of moving to the next page in terminals with multi-page memory. ```ansi [2U ``` -------------------------------- ### Real Terminal Access Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/global-api.md Example script demonstrating the use of realTerminal to escape pipes. ```javascript realTerm = require( "terminal-kit" ).realTerminal ; realTerm.blue( "Enter your name: " ) ; realTerm.inputField( function( error , name ) { realTerm.green( "\nHello %s!\n" , name ) ; process.exit() ; } ) ; ``` -------------------------------- ### Basic Markup Example Source: https://github.com/cronvel/terminal-kit/blob/master/doc/markup.md Demonstrates basic markup for changing text color. ```plaintext This is ^Ggreen^ and this is ^Rred^ ! ``` -------------------------------- ### Basic Color Toggle and Output Source: https://github.com/cronvel/terminal-kit/blob/master/doc/low-level.md Demonstrates how to turn on/off a color feature and output text, and how to output text with a color applied temporarily. ```javascript term.red( true ); term( 'Hello world!' ); term.red( false ); ``` ```javascript term.red( 'Hello world!' ); ``` -------------------------------- ### Cursor Vertical Tab Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of moving forward to a specified vertical tab stop. ```ansi [2Y ``` -------------------------------- ### Creating a ScreenBuffer Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/ScreenBuffer.md Demonstrates various ways to create a ScreenBuffer instance: simple creation, from string data, and from an image file. ```javascript const term = require('terminal-kit').terminal; // Simple creation const buffer = new termkit.ScreenBuffer({ width: 80, height: 24, dst: term // Destination (terminal or another buffer) }); // From string data const buffer = termkit.ScreenBuffer.createFromString({ attr: { color: 'red', bold: true } }, `Line 1 Line 2 Line 3`); // From image file const buffer = await termkit.ScreenBuffer.loadImage( '/path/to/image.png', { width: 40, height: 20 } ); ``` -------------------------------- ### Erase Character Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of changing the state of the next specified number of characters to 'erased'. ```ansi [4X ``` -------------------------------- ### Chaining Styles and Colors Source: https://github.com/cronvel/terminal-kit/blob/master/doc/low-level.md Shows how to chain multiple style and color properties for complex text formatting. ```javascript term.red.bgBlue.bold.italic( 'Hello world!' ) ``` ```javascript term.bgBlue.italic.bold.red( 'Hello world!' ) ``` -------------------------------- ### Clear All Vertical Tabs Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of clearing all vertical tab stops for the entire terminal. ```ansi [6W ``` -------------------------------- ### String Formatting with Colors Source: https://github.com/cronvel/terminal-kit/blob/master/doc/low-level.md Example of using printf-like formatting within a colored string. ```javascript term.red( "My name is %s, I'm %d." , 'Jack' , 32 ) ``` -------------------------------- ### Image Display Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/README.md Demonstrates loading and displaying an image using ScreenBuffer in terminal-kit. ```javascript const buf = await termkit.ScreenBuffer.loadImage('photo.png', { width: term.width, height: term.height, shrink: true }).promise; buf.draw(); ``` -------------------------------- ### Clear All Horizontal Tabs Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of clearing all horizontal tab stops in the entire terminal. ```ansi [5W ``` -------------------------------- ### Basic usage Source: https://github.com/cronvel/terminal-kit/blob/master/README.md Demonstrates basic output, styling, string formatting, and cursor positioning. ```javascript var term = require( 'terminal-kit' ).terminal ; // The term() function simply output a string to stdout, using current style // output "Hello world!" in default terminal's colors term( 'Hello world!\n' ) ; // This output 'red' in red term.red( 'red' ) ; // This output 'bold' in bold term.bold( 'bold' ) ; // output 'mixed' using bold, underlined & red, exposing the style-mixing syntax term.bold.underline.red( 'mixed' ) ; // printf() style formatting everywhere: // this will output 'My name is Jack, I\'m 32.' in green term.green( "My name is %s, I\'m %d.\n" , 'Jack' , 32 ) ; // Since v0.16.x, style markup are supported as a shorthand. // Those two lines produce the same result. term( "My name is " ).red( "Jack" )( " and I\'m " ).green( "32\n" ) ; term( "My name is ^rJack^ and I\'m ^g32\n" ) ; // Width and height of the terminal term( 'The terminal size is %dx%d' , term.width , term.height ) ; // Move the cursor at the upper-left corner term.moveTo( 1 , 1 ) ; // We can always pass additional arguments that will be displayed... term.moveTo( 1 , 1 , 'Upper-left corner' ) ; // ... and formated term.moveTo( 1 , 1 , "My name is %s, I\'m %d.\n" , 'Jack' , 32 ) ; // ... or even combined with other styles term.moveTo.cyan( 1 , 1 , "My name is %s, I\'m %d.\n" , 'Jack' , 32 ) ; // Get some user input term.magenta( "Enter your name: " ) ; var input = await term.inputField().promise ; term.green( "\nYour name is '%s'\n" , input ) ; // Cleanly exit : avoid having junk escape characters and restore default style. // Any interactive functions (like .inputFiled(), .yesOrNo(), etc) will open "stdin" and listen for events, // so the process will NOT exit except explicitly (or explicitly calling .grabInput( false )). term.processExit() ; ``` -------------------------------- ### Set Horizontal Tab Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of setting a horizontal tab stop for the current line. ```ansi [0W ``` -------------------------------- ### Button-Event Tracking - Motion Event Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/XTerm Control Sequences.html Example escape sequence for a button-motion event in button-event tracking mode. ```xterm CSI M @ ``` -------------------------------- ### Loading and Drawing an Image Source: https://github.com/cronvel/terminal-kit/blob/master/doc/ScreenBuffer.md Example demonstrating how to load an image using ScreenBuffer.loadImage, shrink it to fit the terminal dimensions, and draw it onto another ScreenBuffer with blending enabled. ```javascript var screen = new ScreenBuffer( { dst: term , noFill: true } ) ; screen.fill( attr: { // Both foreground and background must have the same color color: 0 , bgColor: 0 } } ) ; ScreenBuffer.loadImage( path_to_image , { terminal: term , shrink: { width: term.width , height: term.height * 2 } } , function( error , image ) { if ( error ) { throw error ; } // Doh! image.draw( {dst: screen , blending: true} ) ; screen.draw() ; } ) ; ``` -------------------------------- ### Cursor Back Tab Example Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/ansicode.txt Example of moving backward to a specified previous horizontal tab stop. ```ansi [3Z ``` -------------------------------- ### Simple CLI Application Example Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/README.md A basic example of a command-line interface application using terminal-kit for input and output. ```javascript const term = require('terminal-kit').terminal; term.cyan('Welcome!\n'); const name = await term.inputField({ prompt: 'Name: ' }).promise; term.green(`Hello, ${name}!\n`); ``` -------------------------------- ### Custom Terminal with Specific Configuration Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/configuration.md Creates a custom terminal instance with explicit streams, configuration, and a custom palette. ```javascript const fs = require('fs'); const termkit = require('terminal-kit'); // Create with explicit streams and config const term = termkit.createTerminal({ stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, generic: 'xterm-256color', isTTY: process.stdout.isTTY, isSSH: !! process.env.SSH_CLIENT, processSigwinch: true }); // Custom palette const palette = new termkit.Palette({ term: term, adaptivePaletteDef: [ { names: ['brand'], code: '#ff5500' } ] }); term.setPalette(palette); // Now use term normally term.clear(); term.color(palette.colorNameToIndex('brand'))('Branded text\n'); ``` -------------------------------- ### Button-Event Tracking - Motion Event Example (Button 3) Source: https://github.com/cronvel/terminal-kit/blob/master/ext-doc/xterm-control-sequences-doc/XTerm Control Sequences.html Example escape sequence for a button-motion event with button 3 down. ```xterm CSI M B ``` -------------------------------- ### TUI Application with Document Model Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/configuration.md An example of a Text-based User Interface (TUI) application using terminal-kit's Document Model. It sets up a fullscreen terminal, creates a document, adds a title element, draws the document, and includes cleanup logic for graceful exit. ```javascript const termkit = require('terminal-kit'); const term = termkit.terminal; // Setup term.fullscreen(); // Create document const doc = term.createDocument({ width: term.width, height: term.height }); // Add elements doc.createElement(termkit.Text, { content: '^+^rApplication Title', contentHasMarkup: true, x: 1, y: 1, key: 'title' }); // Draw doc.draw(); // Cleanup on exit process.on('SIGINT', () => { doc.destroy(); term.fullscreen(false); term.processExit(); }); ``` -------------------------------- ### Creating a Terminal Source: https://github.com/cronvel/terminal-kit/blob/master/_autodocs/api-reference/Terminal.md Demonstrates how to create a terminal instance, either by auto-detection or by explicitly providing stream and configuration options. ```javascript const termkit = require('terminal-kit'); const term = termkit.terminal; // Auto-detects terminal, uses process.stdin/stdout // Or explicitly: const term = termkit.createTerminal({ stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, generic: 'xterm', // or 'linux', 'vt100', etc. isTTY: true, isSSH: false, processSigwinch: true, appId: 'my-app' }); ```