UNPKG

74.5 kBMarkdownView Raw
1# blessed
2
3A curses-like library with a high level terminal interface API for node.js.
4
5![blessed](https://raw.githubusercontent.com/chjj/blessed/master/img/v0.1.0-3.gif)
6
7Blessed is over 16,000 lines of code and terminal goodness. It's completely
8implemented in javascript, and its goal consists of two things:
9
101. Reimplement ncurses entirely by parsing and compiling terminfo and termcap,
11and exposing a `Program` object which can output escape sequences compatible
12with _any_ terminal.
13
142. Implement a widget API which is heavily optimized for terminals.
15
16The blessed renderer makes use of CSR (change-scroll-region), and BCE
17(back-color-erase). It draws the screen using the painter's algorithm and is
18sped up with smart cursor movements and a screen damage buffer. This means
19rendering of your application will be extremely efficient: blessed only draws
20the changes (damage) to the screen.
21
22Blessed is arguably as accurate as ncurses, but even more optimized in some
23ways. The widget library gives you an API which is reminiscent of the DOM.
24Anyone is able to make an awesome terminal application with blessed. There are
25terminal widget libraries for other platforms (primarily [python][urwid] and
26[perl][curses-ui]), but blessed is possibly the most DOM-like (dare I say the
27most user-friendly?).
28
29Blessed has been used to implement other popular libraries and programs.
30Examples include: the [slap text editor][slap] and [blessed-contrib][contrib].
31The blessed API itself has gone on to inspire [termui][termui] for Go.
32
33## Install
34
35``` bash
36$ npm install blessed
37```
38
39## Example
40
41This will render a box with line borders containing the text `'Hello world!'`,
42perfectly centered horizontally and vertically.
43
44__NOTE__: It is recommend you use either `smartCSR` or `fastCSR` as a
45`blessed.screen` option. This will enable CSR when scrolling text in elements
46or when manipulating lines.
47
48``` js
49var blessed = require('blessed');
50
51// Create a screen object.
52var screen = blessed.screen({
53 smartCSR: true
54});
55
56screen.title = 'my window title';
57
58// Create a box perfectly centered horizontally and vertically.
59var box = blessed.box({
60 top: 'center',
61 left: 'center',
62 width: '50%',
63 height: '50%',
64 content: 'Hello {bold}world{/bold}!',
65 tags: true,
66 border: {
67 type: 'line'
68 },
69 style: {
70 fg: 'white',
71 bg: 'magenta',
72 border: {
73 fg: '#f0f0f0'
74 },
75 hover: {
76 bg: 'green'
77 }
78 }
79});
80
81// Append our box to the screen.
82screen.append(box);
83
84// Add a png icon to the box
85var icon = blessed.image({
86 parent: box,
87 top: 0,
88 left: 0,
89 type: 'overlay',
90 width: 'shrink',
91 height: 'shrink',
92 file: __dirname + '/my-program-icon.png',
93 search: false
94});
95
96// If our box is clicked, change the content.
97box.on('click', function(data) {
98 box.setContent('{center}Some different {red-fg}content{/red-fg}.{/center}');
99 screen.render();
100});
101
102// If box is focused, handle `enter`/`return` and give us some more content.
103box.key('enter', function(ch, key) {
104 box.setContent('{right}Even different {black-fg}content{/black-fg}.{/right}\n');
105 box.setLine(1, 'bar');
106 box.insertLine(1, 'foo');
107 screen.render();
108});
109
110// Quit on Escape, q, or Control-C.
111screen.key(['escape', 'q', 'C-c'], function(ch, key) {
112 return process.exit(0);
113});
114
115// Focus our element.
116box.focus();
117
118// Render the screen.
119screen.render();
120```
121
122## Documentation
123
124### Widgets
125
126- [Base Nodes](#base-nodes)
127 - [Node](#node-from-eventemitter) (abstract)
128 - [Screen](#screen-from-node)
129 - [Element](#element-from-node) (abstract)
130- [Boxes](#boxes)
131 - [Box](#box-from-element)
132 - [Text](#text-from-element)
133 - [Line](#line-from-box)
134 - [ScrollableBox](#scrollablebox-from-box) (deprecated)
135 - [ScrollableText](#scrollabletext-from-scrollablebox) (deprecated)
136 - [BigText](#bigtext-from-box)
137- [Lists](#lists)
138 - [List](#list-from-box)
139 - [FileManager](#filemanager-from-list)
140 - [ListTable](#listtable-from-list)
141 - [Listbar](#listbar-from-box)
142- [Forms](#forms)
143 - [Form](#form-from-box)
144 - [Input](#input-from-box) (abstract)
145 - [Textarea](#textarea-from-input)
146 - [Textbox](#textbox-from-textarea)
147 - [Button](#button-from-input)
148 - [Checkbox](#checkbox-from-input)
149 - [RadioSet](#radioset-from-box)
150 - [RadioButton](#radiobutton-from-checkbox)
151- [Prompts](#prompts)
152 - [Prompt](#prompt-from-box)
153 - [Question](#question-from-box)
154 - [Message](#message-from-box)
155 - [Loading](#loading-from-box)
156- [Data Display](#data-display)
157 - [ProgressBar](#progressbar-from-input)
158 - [Log](#log-from-scrollabletext)
159 - [Table](#table-from-box)
160- [Special Elements](#special-elements)
161 - [Terminal](#terminal-from-box)
162 - [Image](#image-from-box)
163 - [ANSIImage](#ansiimage-from-box)
164 - [OverlayImage](#overlayimage-from-box)
165 - [Video](#video-from-box)
166 - [Layout](#layout-from-element)
167
168### Other
169
170- [Helpers](#helpers)
171
172### Mechanics
173
174- [Content & Tags](#content--tags)
175 - [Colors](#colors)
176 - [Attributes](#attributes)
177 - [Alignment](#alignment)
178 - [Escaping](#escaping)
179 - [SGR Sequences](#sgr-sequences)
180- [Style](#style)
181 - [Colors](#colors-1)
182 - [Attributes](#attributes-1)
183 - [Transparency](#transparency)
184 - [Shadow](#shadow)
185 - [Effects](#effects)
186- [Events](#events)
187 - [Event Bubbling](#event-bubbling)
188- [Poisitioning](#positioning)
189- [Rendering](#rendering)
190- [Artificial Cursors](#artificial-cursors)
191- [Multiple Screens](#multiple-screens)
192- [Server Side Usage](#server-side-usage)
193
194### Notes
195
196- [Windows Compatibility](#windows-compatibility)
197- [Low-level Usage](#low-level-usage)
198- [Testing](#testing)
199- [Examples](#examples)
200- [FAQ](#faq)
201
202
203## Widgets
204
205Blessed comes with a number of high-level widgets so you can avoid all the
206nasty low-level terminal stuff.
207
208
209### Base Nodes
210
211
212#### Node (from EventEmitter)
213
214The base node which everything inherits from.
215
216##### Options:
217
218- __screen__ - The screen to be associated with.
219- __parent__ - The desired parent.
220- __children__ - An arrray of children.
221
222##### Properties:
223
224- Inherits all from EventEmitter.
225- __type__ - Type of the node (e.g. `box`).
226- __options__ - Original options object.
227- __parent__ - Parent node.
228- __screen__ - Parent screen.
229- __children__ - Array of node's children.
230- __data, _, $__ - An object for any miscellanous user data.
231- __index__ - Render index (document order index) of the last render call.
232
233##### Events:
234
235- Inherits all from EventEmitter.
236- __adopt__ - Received when node is added to a parent.
237- __remove__ - Received when node is removed from it's current parent.
238- __reparent__ - Received when node gains a new parent.
239- __attach__ - Received when node is attached to the screen directly or
240 somewhere in its ancestry.
241- __detach__ - Received when node is detached from the screen directly or
242 somewhere in its ancestry.
243
244##### Methods:
245
246- Inherits all from EventEmitter.
247- __prepend(node)__ - Prepend a node to this node's children.
248- __append(node)__ - Append a node to this node's children.
249- __remove(node)__ - Remove child node from node.
250- __insert(node, i)__ - Insert a node to this node's children at index `i`.
251- __insertBefore(node, refNode)__ - Insert a node to this node's children
252 before the reference node.
253- __insertAfter(node, refNode)__ - Insert a node from node after the reference
254 node.
255- __detach()__ - Remove node from its parent.
256- __emitDescendants(type, args..., [iterator])__ - Emit event for element, and
257 recursively emit same event for all descendants.
258- __get(name, [default])__ - Get user property with a potential default value.
259- __set(name, value)__ - Set user property to value.
260
261
262#### Screen (from Node)
263
264The screen on which every other node renders.
265
266##### Options:
267
268- __program__ - The blessed `Program` to be associated with. Will be
269 automatically instantiated if none is provided.
270- __smartCSR__ - Attempt to perform CSR optimization on all possible elements
271 (not just full-width ones, elements with uniform cells to their sides).
272 This is known to cause flickering with elements that are not full-width,
273 however, it is more optimal for terminal rendering.
274- __fastCSR__ - Do CSR on any element within 20 cols of the screen edge on
275 either side. Faster than `smartCSR`, but may cause flickering depending on
276 what is on each side of the element.
277- __useBCE__ - Attempt to perform `back_color_erase` optimizations for terminals
278 that support it. It will also work with terminals that don't support it, but
279 only on lines with the default background color. As it stands with the current
280 implementation, it's uncertain how much terminal performance this adds at the
281 cost of overhead within node.
282- __resizeTimeout__ - Amount of time (in ms) to redraw the screen after the
283 terminal is resized (Default: 300).
284- __tabSize__ - The width of tabs within an element's content.
285- __autoPadding__ - Automatically position child elements with border and
286 padding in mind (__NOTE__: this is a recommended option. It may become
287 default in the future).
288- __cursor.artificial__ - Have blessed draw a custom cursor and hide the
289 terminal cursor (__experimental__).
290- __cursor.shape__ - Shape of the cursor. Can be: block, underline, or line.
291- __cursor.blink__ - Whether the cursor blinks.
292- __cursor.color__ - Color of the color. Accepts any valid color value (`null`
293 is default).
294- __log__ - Create a log file. See `log` method.
295- __dump__ - Dump all output and input to desired file. Can be used together
296 with `log` option if set as a boolean.
297- __debug__ - Debug mode. Enables usage of the `debug` method. Also creates a
298 debug console which will display when pressing F12. It will display all log
299 and debug messages.
300- __ignoreLocked__ - Array of keys in their full format (e.g. `C-c`) to ignore
301 when keys are locked or grabbed. Useful for creating a key that will _always_
302 exit no matter whether the keys are locked.
303- __dockBorders__ - Automatically "dock" borders with other elements instead of
304 overlapping, depending on position (__experimental__). For example:
305 These border-overlapped elements:
306```
307┌─────────┌─────────┐
308│ box1 │ box2 │
309└─────────└─────────┘
310```
311 Become:
312```
313┌─────────┬─────────┐
314│ box1 │ box2 │
315└─────────┴─────────┘
316```
317- __ignoreDockContrast__ - Normally, dockable borders will not dock if the
318 colors or attributes are different. This option will allow them to dock
319 regardless. It may produce some odd looking multi-colored borders though.
320- __fullUnicode__ - Allow for rendering of East Asian double-width characters,
321 utf-16 surrogate pairs, and unicode combining characters. This allows you to
322 display text above the basic multilingual plane. This is behind an option
323 because it may affect performance slightly negatively. Without this option
324 enabled, all double-width, surrogate pair, and combining characters will be
325 replaced by `'??'`, `'?'`, `''` respectively. (NOTE: iTerm2 cannot display
326 combining characters properly. Blessed simply removes them from an element's
327 content if iTerm2 is detected).
328- __sendFocus__ - Send focus events after mouse is enabled.
329- __warnings__ - Display warnings (such as the output not being a TTY, similar
330 to ncurses).
331- __forceUnicode__ - Force blessed to use unicode even if it is not detected
332 via terminfo, env variables, or windows code page. If value is `true` unicode
333 is forced. If value is `false` non-unicode is forced (default: `null`).
334- __input/output__ - Input and output streams. `process.stdin`/`process.stdout`
335 by default, however, it could be a `net.Socket` if you want to make a program
336 that runs over telnet or something of that nature.
337- __terminal__ - `TERM` name used for terminfo parsing. The `$TERM` env variable is
338 used by default.
339- __title__ - Set the terminal window title if possible.
340
341##### Properties:
342
343- Inherits all from Node.
344- __program__ - The blessed Program object.
345- __tput__ - The blessed Tput object (only available if you passed `tput: true`
346 to the Program constructor.)
347- __focused__ - Top of the focus history stack.
348- __width__ - Width of the screen (same as `program.cols`).
349- __height__ - Height of the screen (same as `program.rows`).
350- __cols__ - Same as `screen.width`.
351- __rows__ - Same as `screen.height`.
352- __left__ - Relative left offset, always zero.
353- __right__ - Relative right offset, always zero.
354- __top__ - Relative top offset, always zero.
355- __bottom__ - Relative bottom offset, always zero.
356- __aleft__ - Absolute left offset, always zero.
357- __aright__ - Absolute right offset, always zero.
358- __atop__ - Absolute top offset, always zero.
359- __abottom__ - Absolute bottom offset, always zero.
360- __grabKeys__ - Whether the focused element grabs all keypresses.
361- __lockKeys__ - Prevent keypresses from being received by any element.
362- __hover__ - The currently hovered element. Only set if mouse events are bound.
363- __terminal__ - Set or get terminal name. `Set` calls `screen.setTerminal()`
364 internally.
365- __title__ - Set or get window title.
366
367##### Events:
368
369- Inherits all from Node.
370- __resize__ - Received on screen resize.
371- __mouse__ - Received on mouse events.
372- __keypress__ - Received on key events.
373- __element [name]__ - Global events received for all elements.
374- __key [name]__ - Received on key event for [name].
375- __focus, blur__ - Received when the terminal window focuses/blurs. Requires a
376 terminal supporting the focus protocol and focus needs to be passed to
377 program.enableMouse().
378- __prerender__ - Received before render.
379- __render__ - Received on render.
380- __warning__ - Received when blessed notices something untoward (output is not
381 a tty, terminfo not found, etc).
382- __destroy__ - Received when the screen is destroyed (only useful when using
383 multiple screens).
384
385##### Methods:
386
387- Inherits all from Node.
388- __log(msg, ...)__ - Write string to the log file if one was created.
389- __debug(msg, ...)__ - Same as the log method, but only gets called if the
390 `debug` option was set.
391- __alloc()__ - Allocate a new pending screen buffer and a new output screen
392 buffer.
393- __realloc()__ - Reallocate the screen buffers and clear the screen.
394- __draw(start, end)__ - Draw the screen based on the contents of the screen
395 buffer.
396- __render()__ - Render all child elements, writing all data to the screen
397 buffer and drawing the screen.
398- __clearRegion(x1, x2, y1, y2)__ - Clear any region on the screen.
399- __fillRegion(attr, ch, x1, x2, y1, y2)__ - Fill any region with a character
400 of a certain attribute.
401- __focusOffset(offset)__ - Focus element by offset of focusable elements.
402- __focusPrevious()__ - Focus previous element in the index.
403- __focusNext()__ - Focus next element in the index.
404- __focusPush(element)__ - Push element on the focus stack (equivalent to
405 `screen.focused = el`).
406- __focusPop()__ - Pop element off the focus stack.
407- __saveFocus()__ - Save the focused element.
408- __restoreFocus()__ - Restore the saved focused element.
409- __rewindFocus()__ - "Rewind" focus to the last visible and attached element.
410- __key(name, listener)__ - Bind a keypress listener for a specific key.
411- __onceKey(name, listener)__ - Bind a keypress listener for a specific key
412 once.
413- __unkey(name, listener)__ - Remove a keypress listener for a specific key.
414- __spawn(file, args, options)__ - Spawn a process in the foreground, return to
415 blessed app after exit.
416- __exec(file, args, options, callback)__ - Spawn a process in the foreground,
417 return to blessed app after exit. Executes callback on error or exit.
418- __readEditor([options], callback)__ - Read data from text editor.
419- __setEffects(el, fel, over, out, effects, temp)__ - Set effects based on
420 two events and attributes.
421- __insertLine(n, y, top, bottom)__ - Insert a line into the screen (using csr:
422 this bypasses the output buffer).
423- __deleteLine(n, y, top, bottom)__ - Delete a line from the screen (using csr:
424 this bypasses the output buffer).
425- __insertBottom(top, bottom)__ - Insert a line at the bottom of the screen.
426- __insertTop(top, bottom)__ - Insert a line at the top of the screen.
427- __deleteBottom(top, bottom)__ - Delete a line at the bottom of the screen.
428- __deleteTop(top, bottom)__ - Delete a line at the top of the screen.
429- __enableMouse([el])__ - Enable mouse events for the screen and optionally an
430 element (automatically called when a form of on('mouse') is bound).
431- __enableKeys([el])__ - Enable keypress events for the screen and optionally
432 an element (automatically called when a form of on('keypress') is bound).
433- __enableInput([el])__ - Enable key and mouse events. Calls bot enableMouse
434 and enableKeys.
435- __copyToClipboard(text)__ - Attempt to copy text to clipboard using iTerm2's
436 proprietary sequence. Returns true if successful.
437- __cursorShape(shape, blink)__ - Attempt to change cursor shape. Will not work
438 in all terminals (see artificial cursors for a solution to this). Returns
439 true if successful.
440- __cursorColor(color)__ - Attempt to change cursor color. Returns true if
441 successful.
442- __cursorReset()__ - Attempt to reset cursor. Returns true if successful.
443- __screenshot([xi, xl, yi, yl])__ - Take an SGR screenshot of the screen
444 within the region. Returns a string containing only characters and SGR codes.
445 Can be displayed by simply echoing it in a terminal.
446- __destroy()__ - Destroy the screen object and remove it from the global list.
447 Also remove all global events relevant to the screen object. If all screen
448 objects are destroyed, the node process is essentially reset to its initial
449 state.
450- __setTerminal(term)__ - Reset the terminal to `term`. Reloads terminfo.
451
452
453#### Element (from Node)
454
455The base element.
456
457##### Options:
458
459- __fg, bg, bold, underline__ - Attributes.
460- __style__ - May contain attributes in the format of:
461``` js
462 {
463 fg: 'blue',
464 bg: 'black',
465 border: {
466 fg: 'blue'
467 },
468 scrollbar: {
469 bg: 'blue'
470 },
471 focus: {
472 bg: 'red'
473 },
474 hover: {
475 bg: 'red'
476 }
477 }
478```
479- __border__ - Border object, see below.
480- __content__ - Element's text content.
481- __clickable__ - Element is clickable.
482- __input, keyable__ - Element is focusable and can receive key input.
483- __focused__ - Element is focused.
484- __hidden__ - Whether the element is hidden.
485- __label__ - A simple text label for the element.
486- __hoverText__ - A floating text label for the element which appears on mouseover.
487- __align__ - Text alignment: `left`, `center`, or `right`.
488- __valign__ - Vertical text alignment: `top`, `middle`, or `bottom`.
489- __shrink__ - Shrink/flex/grow to content and child elements. Width/height
490 during render.
491- __padding__ - Amount of padding on the inside of the element. Can be a number
492 or an object containing the properties: `left`, `right`, `top`, and `bottom`.
493- __width, height__ - Width/height of the element, can be a number, percentage
494 (`0-100%`), or keyword (`half` or `shrink`). Percentages can also have
495 offsets (`50%+1`, `50%-1`).
496- __left, right, top, bottom__ - Offsets of the element __relative to its
497 parent__. Can be a number, percentage (`0-100%`), or keyword (`center`).
498 `right` and `bottom` do not accept keywords. Percentages can also have
499 offsets (`50%+1`, `50%-1`).
500- __position__ - Can contain the above options.
501- __scrollable__ - Whether the element is scrollable or not.
502- __ch__ - Background character (default is whitespace ` `).
503- __draggable__ - Allow the element to be dragged with the mouse.
504- __shadow__ - Draw a translucent offset shadow behind the element.
505
506##### Properties:
507
508- Inherits all from Node.
509- __name__ - Name of the element. Useful for form submission.
510- __border__ - Border object.
511 - __type__ - Type of border (`line` or `bg`). `bg` by default.
512 - __ch__ - Character to use if `bg` type, default is space.
513 - __bg, fg__ - Border foreground and background, must be numbers (-1 for
514 default).
515 - __bold, underline__ - Border attributes.
516- __style__ - Contains attributes (e.g. `fg/bg/underline`). See above.
517- __position__ - Raw width, height, and offsets.
518- __content__ - Raw text content.
519- __hidden__ - Whether the element is hidden or not.
520- __visible__ - Whether the element is visible or not.
521- __detached__ - Whether the element is attached to a screen in its ancestry
522 somewhere.
523- __fg, bg__ - Foreground and background, must be numbers (-1 for default).
524- __bold, underline__ - Attributes.
525- __width__ - Calculated width.
526- __height__ - Calculated height.
527- __left__ - Calculated relative left offset.
528- __right__ - Calculated relative right offset.
529- __top__ - Calculated relative top offset.
530- __bottom__ - Calculated relative bottom offset.
531- __aleft__ - Calculated absolute left offset.
532- __aright__ - Calculated absolute right offset.
533- __atop__ - Calculated absolute top offset.
534- __abottom__ - Calculated absolute bottom offset.
535- __draggable__ - Whether the element is draggable. Set to true to allow
536 dragging.
537
538##### Events:
539
540- Inherits all from Node.
541- __blur, focus__ - Received when an element is focused or unfocused.
542- __mouse__ - Received on mouse events for this element.
543 - __mousedown, mouseup__ - Mouse button was pressed or released.
544 - __wheeldown, wheelup__ - Wheel was scrolled down or up.
545 - __mouseover, mouseout__ - Element was hovered or unhovered.
546 - __mousemove__ - Mouse was moved somewhere on this element.
547 - __click__ - Element was clicked (slightly smarter than mouseup).
548- __keypress__ - Received on key events for this element.
549- __move__ - Received when the element is moved.
550- __resize__ - Received when the element is resized.
551- __key [name]__ - Received on key event for [name].
552- __prerender__ - Received before a call to render.
553- __render__ - Received after a call to render.
554- __hide__ - Received when element becomes hidden.
555- __show__ - Received when element is shown.
556- __destroy__ - Received when element is destroyed.
557
558##### Methods:
559
560- Inherits all from Node.
561- Note: If the `scrollable` option is enabled, Element inherits all methods
562 from ScrollableBox.
563- __render()__ - Write content and children to the screen buffer.
564- __hide()__ - Hide element.
565- __show()__ - Show element.
566- __toggle()__ - Toggle hidden/shown.
567- __focus()__ - Focus element.
568- __key(name, listener)__ - Bind a keypress listener for a specific key.
569- __onceKey(name, listener)__ - Bind a keypress listener for a specific key
570 once.
571- __unkey(name, listener)__ - Remove a keypress listener for a specific key.
572- __onScreenEvent(type, handler)__ - Same as`el.on('screen', ...)` except this
573 will automatically keep track of which listeners are bound to the screen
574 object. For use with `removeScreenEvent()`, `free()`, and `destroy()`.
575- __removeScreenEvent(type, handler)__ - Same as`el.removeListener('screen',
576 ...)` except this will automatically keep track of which listeners are bound
577 to the screen object. For use with `onScreenEvent()`, `free()`, and
578 `destroy()`.
579- __free()__ - Free up the element. Automatically unbind all events that may
580 have been bound to the screen object. This prevents memory leaks. For use
581 with `onScreenEvent()`, `removeScreenEvent()`, and `destroy()`.
582- __destroy()__ - Same as the `detach()` method, except this will automatically
583 call `free()` and unbind any screen events to prevent memory leaks. for use
584 with `onScreenEvent()`, `removeScreenEvent()`, and `free()`.
585- __setIndex(z)__ - Set the z-index of the element (changes rendering order).
586- __setFront()__ - Put the element in front of its siblings.
587- __setBack()__ - Put the element in back of its siblings.
588- __setLabel(text/options)__ - Set the label text for the top-left corner.
589 Example options: `{text:'foo',side:'left'}`
590- __removeLabel()__ - Remove the label completely.
591- __setHover(text/options)__ - Set a hover text box to follow the cursor.
592 Similar to the "title" DOM attribute in the browser.
593 Example options: `{text:'foo'}`
594- __removeHover()__ - Remove the hover label completely.
595- __enableMouse()__ - Enable mouse events for the element (automatically called
596 when a form of on('mouse') is bound).
597- __enableKeys()__ - Enable keypress events for the element (automatically
598 called when a form of on('keypress') is bound).
599- __enableInput()__ - Enable key and mouse events. Calls bot enableMouse and
600 enableKeys.
601- __enableDrag()__ - Enable dragging of the element.
602- __disableDrag()__ - Disable dragging of the element.
603- __screenshot([xi, xl, yi, yl])__ - Take an SGR screenshot of the element
604 within the region. Returns a string containing only characters and SGR codes.
605 Can be displayed by simply echoing it in a terminal.
606
607###### Content Methods
608
609Methods for dealing with text content, line by line. Useful for writing a
610text editor, irc client, etc.
611
612Note: All of these methods deal with pre-aligned, pre-wrapped text. If you use
613deleteTop() on a box with a wrapped line at the top, it may remove 3-4 "real"
614lines (rows) depending on how long the original line was.
615
616The `lines` parameter can be a string or an array of strings. The `line`
617parameter must be a string.
618
619- __setContent(text)__ - Set the content. Note: When text is input, it will be
620 stripped of all non-SGR escape codes, tabs will be replaced with 8 spaces,
621 and tags will be replaced with SGR codes (if enabled).
622- __getContent()__ - Return content, slightly different from `el.content`.
623 Assume the above formatting.
624- __setText(text)__ - Similar to `setContent`, but ignore tags and remove escape
625 codes.
626- __getText()__ - Similar to `getContent`, but return content with tags and
627 escape codes removed.
628- __insertLine(i, lines)__ - Insert a line into the box's content.
629- __deleteLine(i)__ - Delete a line from the box's content.
630- __getLine(i)__ - Get a line from the box's content.
631- __getBaseLine(i)__ - Get a line from the box's content from the visible top.
632- __setLine(i, line)__ - Set a line in the box's content.
633- __setBaseLine(i, line)__ - Set a line in the box's content from the visible
634 top.
635- __clearLine(i)__ - Clear a line from the box's content.
636- __clearBaseLine(i)__ - Clear a line from the box's content from the visible
637 top.
638- __insertTop(lines)__ - Insert a line at the top of the box.
639- __insertBottom(lines)__ - Insert a line at the bottom of the box.
640- __deleteTop()__ - Delete a line at the top of the box.
641- __deleteBottom()__ - Delete a line at the bottom of the box.
642- __unshiftLine(lines)__ - Unshift a line onto the top of the content.
643- __shiftLine(i)__ - Shift a line off the top of the content.
644- __pushLine(lines)__ - Push a line onto the bottom of the content.
645- __popLine(i)__ - Pop a line off the bottom of the content.
646- __getLines()__ - An array containing the content lines.
647- __getScreenLines()__ - An array containing the lines as they are displayed on
648 the screen.
649- __strWidth(text)__ - Get a string's displayed width, taking into account
650 double-width, surrogate pairs, combining characters, tags, and SGR escape
651 codes.
652
653
654### Boxes
655
656
657#### Box (from Element)
658
659A box element which draws a simple box containing `content` or other elements.
660
661##### Options:
662
663- Inherits all from Element.
664
665##### Properties:
666
667- Inherits all from Element.
668
669##### Events:
670
671- Inherits all from Element.
672
673##### Methods:
674
675- Inherits all from Element.
676
677
678#### Text (from Element)
679
680An element similar to Box, but geared towards rendering simple text elements.
681
682##### Options:
683
684- Inherits all from Element.
685- __fill__ - Fill the entire line with chosen bg until parent bg ends, even if
686 there is not enough text to fill the entire width. __(deprecated)__
687- __align__ - Text alignment: `left`, `center`, or `right`.
688
689Inherits all options, properties, events, and methods from Element.
690
691
692#### Line (from Box)
693
694A simple line which can be `line` or `bg` styled.
695
696##### Options:
697
698- Inherits all from Box.
699- __orientation__ - Can be `vertical` or `horizontal`.
700- __type, bg, fg, ch__ - Treated the same as a border object.
701 (attributes can be contained in `style`).
702
703Inherits all options, properties, events, and methods from Box.
704
705
706#### ScrollableBox (from Box)
707
708__DEPRECATED__ - Use Box with the `scrollable` option instead.
709
710A box with scrollable content.
711
712##### Options:
713
714- Inherits all from Box.
715- __baseLimit__ - A limit to the childBase. Default is `Infinity`.
716- __alwaysScroll__ - A option which causes the ignoring of `childOffset`. This
717 in turn causes the childBase to change every time the element is scrolled.
718- __scrollbar__ - Object enabling a scrollbar.
719- __scrollbar.style__ - Style of the scrollbar.
720- __scrollbar.track__ - Style of the scrollbar track if present (takes regular
721 style options).
722
723##### Properties:
724
725- Inherits all from Box.
726- __childBase__ - The offset of the top of the scroll content.
727- __childOffset__ - The offset of the chosen item/line.
728
729##### Events:
730
731- Inherits all from Box.
732- __scroll__ - Received when the element is scrolled.
733
734##### Methods:
735
736- __scroll(offset)__ - Scroll the content by a relative offset.
737- __scrollTo(index)__ - Scroll the content to an absolute index.
738- __setScroll(index)__ - Same as `scrollTo`.
739- __setScrollPerc(perc)__ - Set the current scroll index in percentage (0-100).
740- __getScroll()__ - Get the current scroll index in lines.
741- __getScrollHeight()__ - Get the actual height of the scrolling area.
742- __getScrollPerc()__ - Get the current scroll index in percentage.
743- __resetScroll()__ - Reset the scroll index to its initial state.
744
745
746#### ScrollableText (from ScrollableBox)
747
748__DEPRECATED__ - Use Box with the `scrollable` and `alwaysScroll` options
749instead.
750
751A scrollable text box which can display and scroll text, as well as handle
752pre-existing newlines and escape codes.
753
754##### Options:
755
756- Inherits all from ScrollableBox.
757- __mouse__ - Whether to enable automatic mouse support for this element.
758- __keys__ - Use predefined keys for navigating the text.
759- __vi__ - Use vi keys with the `keys` option.
760
761##### Properties:
762
763- Inherits all from ScrollableBox.
764
765##### Events:
766
767- Inherits all from ScrollableBox.
768
769##### Methods:
770
771- Inherits all from ScrollableBox.
772
773
774#### BigText (from Box)
775
776A box which can render content drawn as 8x14 cell characters using the terminus
777font.
778
779##### Options:
780
781- Inherits all from Box.
782- __font__ - bdf->json font file to use (see [ttystudio][ttystudio] for
783 instructions on compiling BDFs to JSON).
784- __fontBold__ - bdf->json bold font file to use (see [ttystudio][ttystudio]
785 for instructions on compiling BDFs to JSON).
786- __fch__ - foreground character. (default: `' '`)
787
788##### Properties:
789
790- Inherits all from Box.
791
792##### Events:
793
794- Inherits all from Box.
795
796##### Methods:
797
798- Inherits all from Box.
799
800
801### Lists
802
803
804#### List (from Box)
805
806A scrollable list which can display selectable items.
807
808##### Options:
809
810- Inherits all from Box.
811- __style.selected__ - Style for a selected item.
812- __style.item__ - Style for an unselected item.
813- __mouse__ - Whether to automatically enable mouse support for this list
814 (allows clicking items).
815- __keys__ - Use predefined keys for navigating the list.
816- __vi__ - Use vi keys with the `keys` option.
817- __items__ - An array of strings which become the list's items.
818- __search__ - A function that is called when `vi` mode is enabled and the key
819 `/` is pressed. This function accepts a callback function which should be
820 called with the search string. The search string is then used to jump to an
821 item that is found in `items`.
822- __interactive__ - Whether the list is interactive and can have items selected
823 (Default: true).
824- __invertSelected__ - Whether to automatically override tags and invert fg of
825 item when selected (Default: `true`).
826
827##### Properties:
828
829- Inherits all from Box.
830
831##### Events:
832
833- Inherits all from Box.
834- __select__ - Received when an item is selected.
835- __cancel__ - List was canceled (when `esc` is pressed with the `keys` option).
836- __action__ - Either a select or a cancel event was received.
837
838##### Methods:
839
840- Inherits all from Box.
841- __add/addItem(text)__ - Add an item based on a string.
842- __removeItem(child)__ - Removes an item from the list. Child can be an
843 element, index, or string.
844- __pushItem(child)__ - Push an item onto the list.
845- __popItem()__ - Pop an item off the list.
846- __unshiftItem(child)__ - Unshift an item onto the list.
847- __shiftItem()__ - Shift an item off the list.
848- __insertItem(i, child)__ - Inserts an item to the list. Child can be an
849 element, index, or string.
850- __getItem(child)__ - Returns the item element. Child can be an element,
851 index, or string.
852- __setItem(child, content)__ - Set item to content.
853- __spliceItem(i, n, item1, ...)__ - Remove and insert items to the list.
854- __clearItems()__ - Clears all items from the list.
855- __setItems(items)__ - Sets the list items to multiple strings.
856- __getItemIndex(child)__ - Returns the item index from the list. Child can be
857 an element, index, or string.
858- __select(index)__ - Select an index of an item.
859- __move(offset)__ - Select item based on current offset.
860- __up(amount)__ - Select item above selected.
861- __down(amount)__ - Select item below selected.
862- __pick(callback)__ - Show/focus list and pick an item. The callback is
863 executed with the result.
864- __fuzzyFind([string/regex/callback])__ - Find an item based on its text
865 content.
866
867
868#### FileManager (from List)
869
870A very simple file manager for selecting files.
871
872##### Options:
873
874- Inherits all from List.
875- __cwd__ - Current working directory.
876
877##### Properties:
878
879- Inherits all from List.
880- __cwd__ - Current working directory.
881
882##### Events:
883
884- Inherits all from List.
885- __cd__ - Directory was selected and navigated to.
886- __file__ - File was selected.
887
888##### Methods:
889
890- Inherits all from List.
891- __refresh([cwd], [callback])__ - Refresh the file list (perform a `readdir` on `cwd`
892 and update the list items).
893- __pick([cwd], callback)__ - Pick a single file and return the path in the callback.
894- __reset([cwd], [callback])__ - Reset back to original cwd.
895
896
897#### ListTable (from List)
898
899A stylized table of text elements with a list.
900
901##### Options:
902
903- Inherits all from List.
904- __rows/data__ - Array of array of strings representing rows.
905- __pad__ - Spaces to attempt to pad on the sides of each cell. `2` by default:
906 one space on each side (only useful if the width is shrunken).
907- __noCellBorders__ - Do not draw inner cells.
908- __style.header__ - Header style.
909- __style.cell__ - Cell style.
910
911##### Properties:
912
913- Inherits all from List.
914
915##### Events:
916
917- Inherits all from List.
918
919##### Methods:
920
921- Inherits all from List.
922- __setRows/setData(rows)__ - Set rows in table. Array of arrays of strings.
923``` js
924 table.setData([
925 [ 'Animals', 'Foods' ],
926 [ 'Elephant', 'Apple' ],
927 [ 'Bird', 'Orange' ]
928 ]);
929```
930
931
932#### Listbar (from Box)
933
934A horizontal list. Useful for a main menu bar.
935
936##### Options:
937
938- Inherits all from Box.
939- __style.selected__ - Style for a selected item.
940- __style.item__ - Style for an unselected item.
941- __commands/items__ - Set buttons using an object with keys as titles of
942 buttons, containing of objects containing keys of `keys` and `callback`.
943- __autoCommandKeys__ - Automatically bind list buttons to keys 0-9.
944
945##### Properties:
946
947- Inherits all from Box.
948
949##### Events:
950
951- Inherits all from Box.
952
953##### Methods:
954
955- Inherits all from Box.
956- __setItems(commands)__ - Set commands (see `commands` option above).
957- __add/addItem/appendItem(item, callback)__ - Append an item to the bar.
958- __select(offset)__ - Select an item on the bar.
959- __removeItem(child)__ - Remove item from the bar.
960- __move(offset)__ - Move relatively across the bar.
961- __moveLeft(offset)__ - Move left relatively across the bar.
962- __moveRight(offset)__ - Move right relatively across the bar.
963- __selectTab(index)__ - Select button and execute its callback.
964
965
966### Forms
967
968
969#### Form (from Box)
970
971A form which can contain form elements.
972
973##### Options:
974
975- Inherits all from Box.
976- __keys__ - Allow default keys (tab, vi keys, enter).
977- __vi__ - Allow vi keys.
978
979##### Properties:
980
981- Inherits all from Box.
982- __submission__ - Last submitted data.
983
984##### Events:
985
986- Inherits all from Box.
987- __submit__ - Form is submitted. Receives a data object.
988- __cancel__ - Form is discarded.
989- __reset__ - Form is cleared.
990
991##### Methods:
992
993- Inherits all from Box.
994- __focusNext()__ - Focus next form element.
995- __focusPrevious()__ - Focus previous form element.
996- __submit()__ - Submit the form.
997- __cancel()__ - Discard the form.
998- __reset()__ - Clear the form.
999
1000
1001#### Input (from Box)
1002
1003A form input.
1004
1005
1006#### Textarea (from Input)
1007
1008A box which allows multiline text input.
1009
1010##### Options:
1011
1012- Inherits all from Input.
1013- __keys__ - Use pre-defined keys (`i` or `enter` for insert, `e` for editor,
1014 `C-e` for editor while inserting).
1015- __mouse__ - Use pre-defined mouse events (right-click for editor).
1016- __inputOnFocus__ - Call `readInput()` when the element is focused.
1017 Automatically unfocus.
1018
1019##### Properties:
1020
1021- Inherits all from Input.
1022- __value__ - The input text. __read-only__.
1023
1024##### Events:
1025
1026- Inherits all from Input.
1027- __submit__ - Value is submitted (enter).
1028- __cancel__ - Value is discared (escape).
1029- __action__ - Either submit or cancel.
1030
1031##### Methods:
1032
1033- Inherits all from Input.
1034- __submit__ - Submit the textarea (emits `submit`).
1035- __cancel__ - Cancel the textarea (emits `cancel`).
1036- __readInput(callback)__ - Grab key events and start reading text from the
1037 keyboard. Takes a callback which receives the final value.
1038- __readEditor(callback)__ - Open text editor in `$EDITOR`, read the output from
1039 the resulting file. Takes a callback which receives the final value.
1040- __getValue()__ - The same as `this.value`, for now.
1041- __clearValue()__ - Clear input.
1042- __setValue(text)__ - Set value.
1043
1044
1045#### Textbox (from Textarea)
1046
1047A box which allows text input.
1048
1049##### Options:
1050
1051- Inherits all from Textarea.
1052- __secret__ - Completely hide text.
1053- __censor__ - Replace text with asterisks (`*`).
1054
1055##### Properties:
1056
1057- Inherits all from Textarea.
1058- __secret__ - Completely hide text.
1059- __censor__ - Replace text with asterisks (`*`).
1060
1061##### Events:
1062
1063- Inherits all from Textarea.
1064
1065##### Methods:
1066
1067- Inherits all from Textarea.
1068
1069
1070#### Button (from Input)
1071
1072A button which can be focused and allows key and mouse input.
1073
1074##### Options:
1075
1076- Inherits all from Input.
1077
1078##### Properties:
1079
1080- Inherits all from Input.
1081
1082##### Events:
1083
1084- Inherits all from Input.
1085- __press__ - Received when the button is clicked/pressed.
1086
1087##### Methods:
1088
1089- Inherits all from Input.
1090- __press()__ - Press button. Emits `press`.
1091
1092
1093#### Checkbox (from Input)
1094
1095A checkbox which can be used in a form element.
1096
1097##### Options:
1098
1099- Inherits all from Input.
1100- __checked__ - Whether the element is checked or not.
1101- __mouse__ - Enable mouse support.
1102
1103##### Properties:
1104
1105- Inherits all from Input.
1106- __text__ - The text next to the checkbox (do not use setContent, use
1107 `check.text = ''`).
1108- __checked__ - Whether the element is checked or not.
1109- __value__ - Same as `checked`.
1110
1111##### Events:
1112
1113- Inherits all from Input.
1114- __check__ - Received when element is checked.
1115- __uncheck__ received when element is unchecked.
1116
1117##### Methods:
1118
1119- Inherits all from Input.
1120- __check()__ - Check the element.
1121- __uncheck()__ - Uncheck the element.
1122- __toggle()__ - Toggle checked state.
1123
1124
1125#### RadioSet (from Box)
1126
1127An element wrapping RadioButtons. RadioButtons within this element will be
1128mutually exclusive with each other.
1129
1130##### Options:
1131
1132- Inherits all from Box.
1133
1134##### Properties:
1135
1136- Inherits all from Box.
1137
1138##### Events:
1139
1140- Inherits all from Box.
1141
1142##### Methods:
1143
1144- Inherits all from Box.
1145
1146
1147#### RadioButton (from Checkbox)
1148
1149A radio button which can be used in a form element.
1150
1151##### Options:
1152
1153- Inherits all from Checkbox.
1154
1155##### Properties:
1156
1157- Inherits all from Checkbox.
1158
1159##### Events:
1160
1161- Inherits all from Checkbox.
1162
1163##### Methods:
1164
1165- Inherits all from Checkbox.
1166
1167
1168### Prompts
1169
1170
1171#### Prompt (from Box)
1172
1173A prompt box containing a text input, okay, and cancel buttons (automatically
1174hidden).
1175
1176##### Options:
1177
1178- Inherits all from Box.
1179
1180##### Properties:
1181
1182- Inherits all from Box.
1183
1184##### Events:
1185
1186- Inherits all from Box.
1187
1188##### Methods:
1189
1190- Inherits all from Box.
1191- __input/setInput/readInput(text, value, callback)__ - Show the prompt and
1192 wait for the result of the textbox. Set text and initial value.
1193
1194
1195#### Question (from Box)
1196
1197A question box containing okay and cancel buttons (automatically hidden).
1198
1199##### Options:
1200
1201- Inherits all from Box.
1202
1203##### Properties:
1204
1205- Inherits all from Box.
1206
1207##### Events:
1208
1209- Inherits all from Box.
1210
1211##### Methods:
1212
1213- Inherits all from Box.
1214- __ask(question, callback)__ - Ask a `question`. `callback` will yield the
1215 result.
1216
1217
1218#### Message (from Box)
1219
1220A box containing a message to be displayed (automatically hidden).
1221
1222##### Options:
1223
1224- Inherits all from Box.
1225
1226##### Properties:
1227
1228- Inherits all from Box.
1229
1230##### Events:
1231
1232- Inherits all from Box.
1233
1234##### Methods:
1235
1236- Inherits all from Box.
1237- __log/display(text, [time], callback)__ - Display a message for a time
1238 (default is 3 seconds). Set time to 0 for a perpetual message that is
1239 dismissed on keypress.
1240- __error(text, [time], callback)__ - Display an error in the same way.
1241
1242
1243#### Loading (from Box)
1244
1245A box with a spinning line to denote loading (automatically hidden).
1246
1247##### Options:
1248
1249- Inherits all from Box.
1250
1251##### Properties:
1252
1253- Inherits all from Box.
1254
1255##### Events:
1256
1257- Inherits all from Box.
1258
1259##### Methods:
1260
1261- Inherits all from Box.
1262- __load(text)__ - Display the loading box with a message. Will lock keys until
1263 `stop` is called.
1264- __stop()__ - Hide loading box. Unlock keys.
1265
1266
1267### Data Display
1268
1269
1270#### ProgressBar (from Input)
1271
1272A progress bar allowing various styles. This can also be used as a form input.
1273
1274##### Options:
1275
1276- Inherits all from Input.
1277- __orientation__ - Can be `horizontal` or `vertical`.
1278- __style.bar__ - Style of the bar contents itself.
1279- __pch__ - The character to fill the bar with (default is space).
1280- __filled__ - The amount filled (0 - 100).
1281- __value__ - Same as `filled`.
1282- __keys__ - Enable key support.
1283- __mouse__ - Enable mouse support.
1284
1285##### Properties:
1286
1287- Inherits all from Input.
1288
1289##### Events:
1290
1291- Inherits all from Input.
1292- __reset__ - Bar was reset.
1293- __complete__ - Bar has completely filled.
1294
1295##### Methods:
1296
1297- Inherits all from Input.
1298- __progress(amount)__ - Progress the bar by a fill amount.
1299- __setProgress(amount)__ - Set progress to specific amount.
1300- __reset()__ - Reset the bar.
1301
1302
1303#### Log (from ScrollableText)
1304
1305A log permanently scrolled to the bottom.
1306
1307##### Options:
1308
1309- Inherits all from ScrollableText.
1310- __scrollback__ - Amount of scrollback allowed. Default: Infinity.
1311- __scrollOnInput__ - Scroll to bottom on input even if the user has scrolled
1312 up. Default: false.
1313
1314##### Properties:
1315
1316- Inherits all from ScrollableText.
1317- __scrollback__ - Amount of scrollback allowed. Default: Infinity.
1318- __scrollOnInput__ - Scroll to bottom on input even if the user has scrolled
1319 up. Default: false.
1320
1321##### Events:
1322
1323- Inherits all from ScrollableText.
1324- __log__ - Emitted on a log line. Passes in line.
1325
1326##### Methods:
1327
1328- Inherits all from ScrollableText.
1329- __log/add(text)__ - Add a log line.
1330
1331
1332#### Table (from Box)
1333
1334A stylized table of text elements.
1335
1336##### Options:
1337
1338- Inherits all from Box.
1339- __rows/data__ - Array of array of strings representing rows.
1340- __pad__ - Spaces to attempt to pad on the sides of each cell. `2` by default:
1341 one space on each side (only useful if the width is shrunken).
1342- __noCellBorders__ - Do not draw inner cells.
1343- __fillCellBorders__ - Fill cell borders with the adjacent background color.
1344- __style.header__ - Header style.
1345- __style.cell__ - Cell style.
1346
1347##### Properties:
1348
1349- Inherits all from Box.
1350
1351##### Events:
1352
1353- Inherits all from Box.
1354
1355##### Methods:
1356
1357- Inherits all from Box.
1358- __setRows/setData(rows)__ - Set rows in table. Array of arrays of strings.
1359``` js
1360 table.setData([
1361 [ 'Animals', 'Foods' ],
1362 [ 'Elephant', 'Apple' ],
1363 [ 'Bird', 'Orange' ]
1364 ]);
1365```
1366
1367
1368### Special Elements
1369
1370
1371#### Terminal (from Box)
1372
1373A box which spins up a pseudo terminal and renders the output. Useful for
1374writing a terminal multiplexer, or something similar to an mc-like file
1375manager. Requires term.js and pty.js to be installed. See
1376`example/multiplex.js` for an example terminal multiplexer.
1377
1378##### Options:
1379
1380- Inherits all from Box.
1381- __handler__ - Handler for input data.
1382- __shell__ - Name of shell. `$SHELL` by default.
1383- __args__ - Args for shell.
1384- __cursor__ - Can be `line`, `underline`, and `block`.
1385- __terminal__ - Terminal name (Default: `xterm`).
1386- __env__ - Object for process env.
1387- Other options similar to term.js'.
1388
1389##### Properties:
1390
1391- Inherits all from Box.
1392- __term__ - Reference to the headless term.js terminal.
1393- __pty__ - Reference to the pty.js pseudo terminal.
1394
1395##### Events:
1396
1397- Inherits all from Box.
1398- __title__ - Window title from terminal.
1399- Other events similar to ScrollableBox.
1400
1401##### Methods:
1402
1403- Inherits all from Box.
1404- __write(data)__ - Write data to the terminal.
1405- __screenshot([xi, xl, yi, xl])__ - Nearly identical to `element.screenshot`,
1406 however, the specified region includes the terminal's _entire_ scrollback,
1407 rather than just what is visible on the screen.
1408- Other methods similar to ScrollableBox.
1409
1410
1411#### Image (from Box)
1412
1413Display an image in the terminal (jpeg, png, gif) using either blessed's
1414internal png/gif-to-terminal renderer (using a [ANSIImage element](#ansiimage-from-box)) or
1415using `w3mimgdisplay` (using a [OverlayImage element](#overlayimage-from-box)).
1416
1417##### Options:
1418
1419- Inherits all from Box.
1420- __file__ - Path to image.
1421- __type__ - `ansi` or `overlay`. Whether to render the file as ANSI art or
1422 using `w3m` to overlay. See the [ANSIImage element](#ansiimage-from-box) for
1423 more information/options. (__default__: `ansi`).
1424
1425##### Properties:
1426
1427- Inherits all from Box.
1428- See [ANSIImage element](#ansiimage-from-box)
1429- See [OverlayImage element](#overlayimage-from-box)
1430
1431##### Events:
1432
1433- Inherits all from Box.
1434- See [ANSIImage element](#ansiimage-from-box)
1435- See [OverlayImage element](#overlayimage-from-box)
1436
1437##### Methods:
1438
1439- Inherits all from Box.
1440- See [ANSIImage element](#ansiimage-from-box)
1441- See [OverlayImage element](#overlayimage-from-box)
1442
1443
1444#### ANSIImage (from Box)
1445
1446Convert any `.png` file (or `.gif`, see below) to an ANSI image and display it
1447as an element. This differs from the `OverlayImage` element in that it uses
1448blessed's internal PNG/GIF parser and does not require external dependencies.
1449
1450Blessed uses an internal from-scratch PNG/GIF reader because no other javascript
1451PNG reader supports Adam7 interlaced images (much less pass the png test
1452suite).
1453
1454The blessed PNG reader supports adam7 deinterlacing, animation (APNG), all
1455color types, bit depths 1-32, alpha, alpha palettes, and outputs scaled bitmaps
1456(cellmaps) in blessed for efficient rendering to the screen buffer. It also
1457uses some code from libcaca/libcucul to add density ASCII characters in order
1458to give the image more detail in the terminal.
1459
1460If a corrupt PNG or a non-PNG is passed in, blessed will display error text in
1461the element.
1462
1463`.gif` files are also supported via a javascript implementation (they are
1464internally converted to bitmaps and fed to the PNG renderer). Any other image
1465format is support only if the user has imagemagick (`convert` and `identify`)
1466installed.
1467
1468##### Options:
1469
1470- Inherits all from Box.
1471- __file__ - URL or path to PNG/GIF file. Can also be a buffer.
1472- __scale__ - Scale cellmap down (`0-1.0`) from its original pixel width/height
1473 (Default: `1.0`).
1474- __width/height__ - This differs from other element's `width` or `height` in
1475 that only one of them is needed: blessed will maintain the aspect ratio of
1476 the image as it scales down to the proper number of cells. __NOTE__: PNG/GIF's
1477 are always automatically shrunken to size (based on scale) if a `width` or
1478 `height` is not given.
1479- __ascii__ - Add various "density" ASCII characters over the rendering to give
1480 the image more detail, similar to libcaca/libcucul (the library mplayer uses
1481 to display videos in the terminal).
1482- __animate__ - Whether to animate if the image is an APNG/animating GIF. If
1483 false, only display the first frame or IDAT (Default: `true`).
1484- __speed__ - Set the speed of animation. Slower: `0.0-1.0`. Faster: `1-1000`.
1485 It cannot go faster than 1 frame per millisecond, so 1000 is the fastest.
1486 (Default: 1.0)
1487- __optimization__ - `mem` or `cpu`. If optimizing for memory, animation frames
1488 will be rendered to bitmaps _as the animation plays_, using less memory.
1489 Optimizing for cpu will precompile all bitmaps beforehand, which may be
1490 faster, but might also OOM the process on large images. (Default: `mem`).
1491
1492##### Properties:
1493
1494- Inherits all from Box.
1495- __img__ - Image object from the png reader.
1496- __img.width__ - Pixel width.
1497- __img.height__ - Pixel height.
1498- __img.bmp__ - Image bitmap.
1499- __img.cellmap__ - Image cellmap (bitmap scaled down to cell size).
1500
1501##### Events:
1502
1503- Inherits all from Box.
1504
1505##### Methods:
1506
1507- Inherits all from Box.
1508- __setImage(file)__ - Set the image in the box to a new path. File can be a
1509 path, url, or buffer.
1510- __clearImage()__ - Clear the image.
1511- __play()__ - Play animation if it has been paused or stopped.
1512- __pause()__ - Pause animation.
1513- __stop()__ - Stop animation.
1514
1515
1516#### OverlayImage (from Box)
1517
1518Display an image in the terminal (jpeg, png, gif) using w3mimgdisplay. Requires
1519w3m to be installed. X11 required: works in xterm, urxvt, and possibly other
1520terminals.
1521
1522##### Options:
1523
1524- Inherits all from Box.
1525- __file__ - Path to image.
1526- __ansi__ - Render the file as ANSI art instead of using `w3m` to overlay
1527 Internally uses the ANSIImage element. See the [ANSIImage element](#ansiimage-from-box) for
1528 more information/options. (Default: `true`).
1529- __w3m__ - Path to w3mimgdisplay. If a proper `w3mimgdisplay` path is not
1530 given, blessed will search the entire disk for the binary.
1531- __search__ - Whether to search `/usr`, `/bin`, and `/lib` for
1532 `w3mimgdisplay` (Default: `true`).
1533
1534##### Properties:
1535
1536- Inherits all from Box.
1537
1538##### Events:
1539
1540- Inherits all from Box.
1541
1542##### Methods:
1543
1544- Inherits all from Box.
1545- __setImage(img, [callback])__ - Set the image in the box to a new path.
1546- __clearImage([callback])__ - Clear the current image.
1547- __imageSize(img, [callback])__ - Get the size of an image file in pixels.
1548- __termSize([callback])__ - Get the size of the terminal in pixels.
1549- __getPixelRatio([callback])__ - Get the pixel to cell ratio for the terminal.
1550- _Note:_ All methods above can be synchronous as long as the host version of
1551 node supports `spawnSync`.
1552
1553
1554#### Video (from Box)
1555
1556A box which spins up a pseudo terminal in order to render a video via `mplayer
1557-vo caca` or `mpv --vo caca`. Requires `mplayer` or `mpv` to be installed with
1558libcaca support.
1559
1560##### Options:
1561
1562- Inherits all from Box.
1563- __file__ - Video to play.
1564- __start__ - Start time in seconds.
1565
1566##### Properties:
1567
1568- Inherits all from Box.
1569- __tty__ - The terminal element running `mplayer` or `mpv`.
1570
1571##### Events:
1572
1573- Inherits all from Box.
1574
1575##### Methods:
1576
1577- Inherits all from Box.
1578
1579
1580#### Layout (from Element)
1581
1582A layout which can position children automatically based on a `renderer` method
1583(__experimental__ - the mechanics of this element may be changed in the
1584future!).
1585
1586By default, the Layout element automatically positions children as if they were
1587`display: inline-block;` in CSS.
1588
1589##### Options:
1590
1591- Inherits all from Element.
1592- __renderer__ - A callback which is called right before the children are
1593 iterated over to be rendered. Should return an iterator callback which is
1594 called on each child element: __iterator(el, i)__.
1595- __layout__ - Using the default renderer, it provides two layouts: inline, and
1596 grid. `inline` is the default and will render akin to `inline-block`. `grid`
1597 will create an automatic grid based on element dimensions. The grid cells'
1598 width and height are always determined by the largest children in the layout.
1599
1600##### Properties:
1601
1602- Inherits all from Element.
1603
1604##### Events:
1605
1606- Inherits all from Element.
1607
1608##### Methods:
1609
1610- Inherits all from Element.
1611- __renderer(coords)__ - A callback which is called right before the children
1612 are iterated over to be rendered. Should return an iterator callback which is
1613 called on each child element: __iterator(el, i)__.
1614- __isRendered(el)__ - Check to see if a previous child element has been
1615 rendered and is visible on screen. This is __only__ useful for checking child
1616 elements that have already been attempted to be rendered! see the example
1617 below.
1618- __getLast(i)__ - Get the last rendered and visible child element based on an
1619 index. This is useful for basing the position of the current child element on
1620 the position of the last child element.
1621- __getLastCoords(i)__ - Get the last rendered and visible child element coords
1622 based on an index. This is useful for basing the position of the current
1623 child element on the position of the last child element. See the example
1624 below.
1625
1626##### Rendering a Layout for child elements
1627
1628###### Notes
1629
1630You must __always__ give `Layout` a width and height. This is a chicken-and-egg
1631problem: blessed cannot calculate the width and height dynamically _before_ the
1632children are positioned.
1633
1634`border` and `padding` are already calculated into the `coords` object the
1635`renderer` receives, so there is no need to account for it in your renderer.
1636
1637Try to set position for children using `el.position`. `el.position` is the most
1638primitive "to-be-rendered" way to set coordinates. Setting `el.left` directly
1639has more dynamic behavior which may interfere with rendering.
1640
1641Some definitions for `coords` (otherwise known as `el.lpos`):
1642
1643- `coords.xi` - the absolute x coordinate of the __left__ side of a rendered
1644 element. It is absolute: relative to the screen itself.
1645- `coords.xl` - the absolute x coordinate of the __right__ side of a rendered
1646 element. It is absolute: relative to the screen itself.
1647- `coords.yi` - the absolute y coordinate of the __top__ side of a rendered
1648 element. It is absolute: relative to the screen itself.
1649- `coords.yl` - the absolute y coordinate of the __bottom__ side of a rendered
1650 element. It is absolute: relative to the screen itself.
1651
1652Note again: the `coords` the renderer receives for the Layout already has
1653border and padding subtracted, so you do not have to account for these. The
1654children do not.
1655
1656###### Example
1657
1658Here is an example of how to provide a renderer. Note that this is also the
1659default renderer if none is provided. This renderer will render each child as
1660though they were `display: inline-block;` in CSS, as if there were a
1661dynamically sized horizontal grid from left to right.
1662
1663``` js
1664var layout = blessed.layout({
1665 parent: screen,
1666 top: 'center',
1667 left: 'center',
1668 width: '50%',
1669 height: '50%',
1670 border: 'line',
1671 style: {
1672 bg: 'red',
1673 border: {
1674 fg: 'blue'
1675 }
1676 },
1677 // NOTE: This is already the default renderer if none is provided!
1678 renderer: function(coords) {
1679 var self = this;
1680
1681 // The coordinates of the layout element
1682 var width = coords.xl - coords.xi
1683 , height = coords.yl - coords.yi
1684 , xi = coords.xi
1685 , xl = coords.xl
1686 , yi = coords.yi
1687 , yl = coords.yl;
1688
1689 // The current row offset in cells (which row are we on?)
1690 var rowOffset = 0;
1691
1692 // The index of the first child in the row
1693 var rowIndex = 0;
1694
1695 return function iterator(el, i) {
1696 // Make our children shrinkable. If they don't have a height, for
1697 // example, calculate it for them.
1698 el.shrink = true;
1699
1700 // Find the previous rendered child's coordinates
1701 var last = self.getLastCoords(i);
1702
1703 // If there is no previously rendered element, we are on the first child.
1704 if (!last) {
1705 el.position.left = 0;
1706 el.position.top = 0;
1707 } else {
1708 // Otherwise, figure out where to place this child. We'll start by
1709 // setting it's `left`/`x` coordinate to right after the previous
1710 // rendered element. This child will end up directly to the right of it.
1711 el.position.left = last.xl - xi;
1712
1713 // If our child does not overlap the right side of the Layout, set it's
1714 // `top`/`y` to the current `rowOffset` (the coordinate for the current
1715 // row).
1716 if (el.position.left + el.width <= width) {
1717 el.position.top = rowOffset;
1718 } else {
1719 // Otherwise we need to start a new row and calculate a new
1720 // `rowOffset` and `rowIndex` (the index of the child on the current
1721 // row).
1722 rowOffset += self.children.slice(rowIndex, i).reduce(function(out, el) {
1723 if (!self.isRendered(el)) return out;
1724 out = Math.max(out, el.lpos.yl - el.lpos.yi);
1725 return out;
1726 }, 0);
1727 rowIndex = i;
1728 el.position.left = 0;
1729 el.position.top = rowOffset;
1730 }
1731 }
1732
1733 // If our child overflows the Layout, do not render it!
1734 // Disable this feature for now.
1735 if (el.position.top + el.height > height) {
1736 // Returning false tells blessed to ignore this child.
1737 // return false;
1738 }
1739 };
1740 }
1741});
1742
1743for (var i = 0; i < 10; i++) {
1744 blessed.box({
1745 parent: layout,
1746 width: i % 2 === 0 ? 10 : 20,
1747 height: i % 2 === 0 ? 5 : 10,
1748 border: 'line'
1749 });
1750}
1751```
1752
1753
1754### Other
1755
1756
1757#### Helpers
1758
1759All helpers reside on `blessed.helpers` or `blessed`.
1760
1761- __merge(a, b)__ - Merge objects `a` and `b` into object `a`.
1762- __asort(obj)__ - Sort array alphabetically by `name` prop.
1763- __hsort(obj)__ - Sort array numerically by `index` prop.
1764- __findFile(start, target)__ - Find a file at `start` directory with name
1765 `target`.
1766- __escape(text)__ - Escape content's tags to be passed into `el.setContent()`.
1767 Example: `box.setContent('escaped tag: ' + blessed.escape('{bold}{/bold}'));`
1768- __parseTags(text)__ - Parse tags into SGR escape codes.
1769- __generateTags(style, text)__ - Generate text tags based on `style` object.
1770- __attrToBinary(style, element)__ - Convert `style` attributes to binary
1771 format.
1772- __stripTags(text)__ - Strip text of tags and SGR sequences.
1773- __cleanTags(text)__ - Strip text of tags, SGR escape code, and
1774 leading/trailing whitespace.
1775- __dropUnicode(text)__ - Drop text of any >U+FFFF characters.
1776
1777
1778### Mechanics
1779
1780
1781#### Content & Tags
1782
1783Every element can have text content via `setContent`. If `tags: true` was
1784passed to the element's constructor, the content can contain tags. For example:
1785
1786``` js
1787box.setContent('hello {red-fg}{green-bg}{bold}world{/bold}{/green-bg}{/red-fg}');
1788```
1789
1790To make this more concise `{/}` cancels all character attributes.
1791
1792``` js
1793box.setContent('hello {red-fg}{green-bg}{bold}world{/}');
1794```
1795
1796
1797##### Colors
1798
1799Blessed tags support the basic 16 colors for colors, as well as up to 256
1800colors.
1801
1802``` js
1803box.setContent('hello {red-fg}{green-bg}world{/}');
1804```
1805
1806Tags can also use hex colors (which will be reduced to the most accurate
1807terminal color):
1808
1809``` js
1810box.setContent('hello {#ff0000-fg}{#00ff00-bg}world{/}');
1811```
1812
1813
1814##### Attributes
1815
1816Blessed supports all terminal attributes, including `bold`, `underline`,
1817`blink`, `inverse`, and `invisible`.
1818
1819``` js
1820box.setContent('hello {bold}world{/bold}');
1821```
1822
1823
1824##### Alignment
1825
1826Newlines and alignment are also possible in content.
1827
1828``` js
1829box.setContent('hello\n'
1830 + '{right}world{/right}\n'
1831 + '{center}foo{/center}\n');
1832 + 'left{|}right');
1833```
1834
1835This will produce a box that looks like:
1836
1837```
1838| hello |
1839| world |
1840| foo |
1841| left right |
1842```
1843
1844
1845##### Escaping
1846
1847Escaping can either be done using `blessed.escape()`
1848
1849```
1850box.setContent('here is an escaped tag: ' + blessed.escape('{bold}{/bold}'));
1851```
1852
1853Or with the special `{open}` and `{close}` tags:
1854
1855```
1856box.setContent('here is an escaped tag: {open}bold{close}{open}/bold{close}');
1857```
1858
1859Either will produce:
1860
1861```
1862here is an escaped tag: {bold}{/bold}
1863```
1864
1865
1866##### SGR Sequences
1867
1868Content can also handle SGR escape codes. This means if you got output from a
1869program, say `git log` for example, you can feed it directly to an element's
1870content and the colors will be parsed appropriately.
1871
1872This means that while `{red-fg}foo{/red-fg}` produces `^[[31mfoo^[[39m`, you
1873could just feed `^[[31mfoo^[[39m` directly to the content.
1874
1875
1876#### Style
1877
1878The style option controls most of the visual aspects of an element.
1879
1880``` js
1881 style: {
1882 fg: 'blue',
1883 bg: 'black',
1884 bold: true,
1885 underline: false,
1886 blink: false,
1887 inverse: false,
1888 invisible: false,
1889 transparent: false,
1890 border: {
1891 fg: 'blue',
1892 bg: 'red'
1893 },
1894 scrollbar: {
1895 bg: 'blue'
1896 },
1897 focus: {
1898 bg: 'red'
1899 },
1900 hover: {
1901 bg: 'red'
1902 }
1903 }
1904```
1905
1906
1907##### Colors
1908
1909Colors can be the names of any of the 16 basic terminal colors, along with hex
1910values (e.g. `#ff0000`) for 256 color terminals. If 256 or 88 colors is not
1911supported. Blessed with reduce the color to whatever is available.
1912
1913
1914##### Attributes
1915
1916Blessed supports all terminal attributes, including `bold`, `underline`,
1917`blink`, `inverse`, and `invisible`. Attributes are represented as bools in the
1918`style` object.
1919
1920
1921##### Transparency
1922
1923Blessed can set the opacity of an element to 50% using `style.transparent =
1924true;`. While this seems like it normally shouldn't be possible in a terminal,
1925blessed will use a color blending algorithm to blend the element of the
1926foremost element with the background behind it. Obviously characters cannot be
1927blended, but background colors can.
1928
1929
1930##### Shadow
1931
1932Translucent shadows are also an option when it comes to styling an element.
1933This option will create a 50% opacity 2-cell wide, 1-cell high shadow offset to
1934the bottom-right.
1935
1936``` js
1937shadow: true
1938```
1939
1940
1941##### Effects
1942
1943Blessed supports hover and focus styles. (Hover is only useful is mouse input
1944is enabled).
1945
1946``` js
1947 style: {
1948 hover: {
1949 bg: 'red'
1950 },
1951 focus: {
1952 border: {
1953 fg: 'blue'
1954 }
1955 }
1956 }
1957```
1958
1959
1960##### Scrollbar
1961
1962On scrollable elements, blessed will support style options for the scrollbar,
1963such as:
1964
1965``` js
1966style: {
1967 scrollbar: {
1968 bg: 'red',
1969 fg: 'blue'
1970 }
1971}
1972```
1973
1974As a main option, scrollbar will either take a bool or an object:
1975
1976``` js
1977scrollbar: {
1978 ch: ' '
1979}
1980```
1981
1982Or:
1983
1984``` js
1985scrollbar: true
1986```
1987
1988
1989#### Events
1990
1991Events in Blessed work similar to the traditional node.js model, with one
1992important difference: they have a concept of a tree and event bubbling.
1993
1994
1995##### Event Bubbling
1996
1997Events can bubble in blessed. For example:
1998
1999Receiving all click events for `box` (a normal event listener):
2000
2001``` js
2002box.on('click', function(mouse) {
2003 box.setContent('You clicked ' + mouse.x + ', ' + mouse.y + '.');
2004 screen.render();
2005});
2006```
2007
2008Receiving all click events for `box`, as well as all of its children:
2009
2010``` js
2011box.on('element click', function(el, mouse) {
2012 box.setContent('You clicked '
2013 + el.type + ' at ' + mouse.x + ', ' + mouse.y + '.');
2014 screen.render();
2015 if (el === box) {
2016 return false; // Cancel propagation.
2017 }
2018});
2019```
2020
2021`el` gets passed in as the first argument. It refers to the target element the
2022event occurred on. Returning `false` will cancel propagation up the tree.
2023
2024
2025#### Positioning
2026
2027Offsets may be a number, a percentage (e.g. `50%`), or a keyword (e.g.
2028`center`).
2029
2030Dimensions may be a number, or a percentage (e.g. `50%`).
2031
2032Positions are treated almost _exactly_ the same as they are in CSS/CSSOM when
2033an element has the `position: absolute` CSS property.
2034
2035When an element is created, it can be given coordinates in its constructor:
2036
2037``` js
2038var box = blessed.box({
2039 left: 'center',
2040 top: 'center',
2041 bg: 'yellow',
2042 width: '50%',
2043 height: '50%'
2044});
2045```
2046
2047This tells blessed to create a box, perfectly centered __relative to its
2048parent__, 50% as wide and 50% as tall as its parent.
2049
2050Percentages can also have offsets applied to them:
2051
2052``` js
2053 ...
2054 height: '50%-1',
2055 left: '45%+1',
2056 ...
2057```
2058
2059To access the calculated offsets, relative to the parent:
2060
2061``` js
2062console.log(box.left);
2063console.log(box.top);
2064```
2065
2066To access the calculated offsets, absolute (relative to the screen):
2067
2068``` js
2069console.log(box.aleft);
2070console.log(box.atop);
2071```
2072
2073
2074##### Overlapping offsets and dimensions greater than parents'
2075
2076This still needs to be tested a bit, but it should work.
2077
2078
2079#### Rendering
2080
2081To actually render the screen buffer, you must call `render`.
2082
2083``` js
2084box.setContent('Hello {#0fe1ab-fg}world{/}.');
2085screen.render();
2086```
2087
2088Elements are rendered with the lower elements in the children array being
2089painted first. In terms of the painter's algorithm, the lowest indicies in the
2090array are the furthest away, just like in the DOM.
2091
2092
2093#### Artificial Cursors
2094
2095Terminal cursors can be tricky. They all have different custom escape codes to
2096alter. As an _experimental_ alternative, blessed can draw a cursor for you,
2097allowing you to have a custom cursor that you control.
2098
2099``` js
2100var screen = blessed.screen({
2101 cursor: {
2102 artificial: true,
2103 shape: 'line',
2104 blink: true,
2105 color: null // null for default
2106 }
2107});
2108```
2109
2110That's it. It's controlled the same way as the regular cursor.
2111
2112To create a custom cursor:
2113
2114``` js
2115var screen = blessed.screen({
2116 cursor: {
2117 artificial: true,
2118 shape: {
2119 bg: 'red',
2120 fg: 'white',
2121 bold: true,
2122 ch: '#'
2123 },
2124 blink: true
2125 }
2126});
2127```
2128
2129
2130#### Multiple Screens
2131
2132Blessed supports the ability to create multiple screens. This may not seem
2133useful at first, but if you're writing a program that serves terminal
2134interfaces over http, telnet, or any other protocol, this can be very useful.
2135
2136##### Server Side Usage
2137
2138A simple telnet server might look like this (see examples/blessed-telnet.js for
2139a full example):
2140
2141``` js
2142var blessed = require('blessed');
2143var telnet = require('telnet');
2144
2145telnet.createServer(function(client) {
2146 client.do.transmit_binary();
2147 client.do.terminal_type();
2148 client.do.window_size();
2149
2150 client.on('terminal type', function(data) {
2151 if (data.command === 'sb' && data.name) {
2152 screen.terminal = data.name;
2153 screen.render();
2154 }
2155 });
2156
2157 client.on('window size', function(data) {
2158 if (data.command === 'sb') {
2159 client.columns = data.columns;
2160 client.rows = data.rows;
2161 client.emit('resize');
2162 }
2163 });
2164
2165 // Make the client look like a tty:
2166 client.setRawMode = function(mode) {
2167 client.isRaw = mode;
2168 if (!client.writable) return;
2169 if (mode) {
2170 client.do.suppress_go_ahead();
2171 client.will.suppress_go_ahead();
2172 client.will.echo();
2173 } else {
2174 client.dont.suppress_go_ahead();
2175 client.wont.suppress_go_ahead();
2176 client.wont.echo();
2177 }
2178 };
2179 client.isTTY = true;
2180 client.isRaw = false;
2181 client.columns = 80;
2182 client.rows = 24;
2183
2184 var screen = blessed.screen({
2185 smartCSR: true,
2186 input: client,
2187 output: client,
2188 terminal: 'xterm-256color',
2189 fullUnicode: true
2190 });
2191
2192 client.on('close', function() {
2193 if (!screen.destroyed) {
2194 screen.destroy();
2195 }
2196 });
2197
2198 screen.key(['C-c', 'q'], function(ch, key) {
2199 screen.destroy();
2200 });
2201
2202 screen.on('destroy', function() {
2203 if (client.writable) {
2204 client.destroy();
2205 }
2206 });
2207
2208 screen.data.main = blessed.box({
2209 parent: screen,
2210 left: 'center',
2211 top: 'center',
2212 width: '80%',
2213 height: '90%',
2214 border: 'line',
2215 content: 'Welcome to my server. Here is your own private session.'
2216 });
2217
2218 screen.render();
2219}).listen(2300);
2220```
2221
2222Once you've written something similar and started it, you can simply telnet
2223into your blessed app:
2224
2225``` bash
2226$ telnet localhost 2300
2227```
2228
2229Creating a netcat server would also work as long as you disable line buffering
2230and terminal echo on the commandline via `stty`:
2231`$ stty -icanon -echo; ncat localhost 2300; stty icanon echo`
2232
2233Or by using netcat's `-t` option: `$ ncat -t localhost 2300`
2234
2235Creating a streaming http 1.1 server than runs in the terminal is possible by
2236curling it with special arguments: `$ curl -sSNT. localhost:8080`.
2237
2238There are currently no examples of netcat/nc/ncat or http->curl servers yet.
2239
2240---
2241
2242The `blessed.screen` constructor can accept `input`, `output`, and `term`
2243arguments to aid with this. The multiple screens will be managed internally by
2244blessed. The programmer just has to keep track of the references, however, to
2245avoid ambiguity, it's possible to explicitly dictate which screen a node is
2246part of by using the `screen` option when creating an element.
2247
2248The `screen.destroy()` method is also crucial: this will clean up all event
2249listeners the screen has bound and make sure it stops listening on the event
2250loop. Make absolutely certain to remember to clean up your screens once you're
2251done with them.
2252
2253A tricky part is making sure to include the ability for the client to send the
2254TERM which is reset on the serverside, and the terminal size, which is should
2255also be reset on the serverside. Both of these capabilities are demonstrated
2256above.
2257
2258For a working example of a blessed telnet server, see
2259`examples/blessed-telnet.js`.
2260
2261
2262### Notes
2263
2264
2265#### Windows Compatibility
2266
2267Currently there is no `mouse` or `resize` event support on Windows.
2268
2269Windows users will need to explicitly set `term` when creating a screen like so
2270(__NOTE__: This is no longer necessary as of the latest versions of blessed.
2271This is now handled automatically):
2272
2273``` js
2274var screen = blessed.screen({ terminal: 'windows-ansi' });
2275```
2276
2277
2278#### Low-level Usage
2279
2280This will actually parse the xterm terminfo and compile every
2281string capability to a javascript function:
2282
2283``` js
2284var blessed = require('blessed');
2285
2286var tput = blessed.tput({
2287 terminal: 'xterm-256color',
2288 extended: true
2289});
2290
2291process.stdout.write(tput.setaf(4) + 'Hello' + tput.sgr0() + '\n');
2292```
2293
2294To play around with it on the command line, it works just like tput:
2295
2296``` bash
2297$ tput.js setaf 2
2298$ tput.js sgr0
2299$ echo "$(tput.js setaf 2)Hello World$(tput.js sgr0)"
2300```
2301
2302The main functionality is exposed in the main `blessed` module:
2303
2304``` js
2305var blessed = require('blessed')
2306 , program = blessed.program();
2307
2308program.key('q', function(ch, key) {
2309 program.clear();
2310 program.disableMouse();
2311 program.showCursor();
2312 program.normalBuffer();
2313 process.exit(0);
2314});
2315
2316program.on('mouse', function(data) {
2317 if (data.action === 'mousemove') {
2318 program.move(data.x, data.y);
2319 program.bg('red');
2320 program.write('x');
2321 program.bg('!red');
2322 }
2323});
2324
2325program.alternateBuffer();
2326program.enableMouse();
2327program.hideCursor();
2328program.clear();
2329
2330program.move(1, 1);
2331program.bg('black');
2332program.write('Hello world', 'blue fg');
2333program.setx((program.cols / 2 | 0) - 4);
2334program.down(5);
2335program.write('Hi again!');
2336program.bg('!black');
2337program.feed();
2338```
2339
2340
2341#### Testing
2342
2343Most tests contained in the `test/` directory are interactive. It's up to the
2344programmer to determine whether the test is properly displayed. In the future
2345it might be better to do something similar to vttest.
2346
2347
2348#### Examples
2349
2350Examples can be found in `examples/`.
2351
2352
2353#### FAQ
2354
23551. Why doesn't the Linux console render lines correctly on Ubuntu?
2356 - You need to install the `ncurses-base` package __and__ the `ncurses-term`
2357 package. (#98)
23582. Why do vertical lines look chopped up in iTerm2?
2359 - All ACS vertical lines look this way in iTerm2 with the default font.
23603. Why can't I use my mouse in Terminal.app?
2361 - Terminal.app does not support mouse events.
23624. Why doesn't the OverlayImage element appear in my terminal?
2363 - The OverlayImage element uses w3m to display images. This generally only
2364 works on X11+xterm/urxvt, but it _may_ work on other unix terminals.
23655. Why can't my mouse clicks register beyond 255 cells?
2366 - Older versions of VTE do not support any modern mouse protocol. On top of
2367 that, the old X10 protocol it _does_ implement is bugged. Through several
2368 workarounds we've managed to get the cell limit from `127` to `255`. If
2369 you're not happy with this, you may want to look into using xterm or urxvt,
2370 or a terminal which uses a modern VTE, like gnome-terminal.
23716. Is blessed efficient?
2372 - Yes. Blessed implements CSR and uses the painter's algorithm to render the
2373 screen. It maintains two screen buffers so it only needs to render what
2374 has changed on the terminal screen.
23757. Will blessed work with all terminals?
2376 - Yes. Blessed has a terminfo/termcap parser and compiler that was written
2377 from scratch. It should work with every terminal as long as a terminfo
2378 file is provided. If you notice any compatibility issues in your termial,
2379 do not hesitate to post an issue.
23808. What is "curses" and "ncurses"?
2381 - ["curses"][curses] was an old library written in the early days of unix
2382 which allowed a programmer to easily manipulate the cursor in order to
2383 render the screen. ["ncurses"][ncurses] is a free reimplementation of
2384 curses. It improved upon it quite a bit by focusing more on terminal
2385 compatibility and is now the standard library for implementing terminal
2386 programs. Blessed uses neither of these, and instead handles terminal
2387 compatibility itself.
23889. What is the difference between blessed and blessed-contrib?
2389 - blessed is a major piece of code which reimplements curses from the ground
2390 up. A UI API is then layered on top of this. [blessed-contrib][contrib] is
2391 a popular library built on top of blessed which makes clever use of modules
2392 to implement useful widgets like graphs, ascii art, and so on.
239310. Are there blessed-like solutions for non-javascript platforms?
2394 - Yes. There are some fantastic solutions out there.
2395 - Perl: [Curses::UI][curses-ui]
2396 - Python: [Urwid][urwid]
2397 - Go: [termui][termui] & [termbox-go][termbox]
2398
2399
2400## Contribution and License Agreement
2401
2402If you contribute code to this project, you are implicitly allowing your code
2403to be distributed under the MIT license. You are also implicitly verifying that
2404all code is your original work. `</legalese>`
2405
2406
2407## License
2408
2409Copyright (c) 2013-2015, Christopher Jeffrey. (MIT License)
2410
2411See LICENSE for more info.
2412
2413[slap]: https://github.com/slap-editor/slap
2414[contrib]: https://github.com/yaronn/blessed-contrib
2415[termui]: https://github.com/gizak/termui
2416[curses]: https://en.wikipedia.org/wiki/Curses_(programming_library)
2417[ncurses]: https://en.wikipedia.org/wiki/Ncurses
2418[urwid]: http://urwid.org/reference/index.html
2419[curses-ui]: http://search.cpan.org/~mdxi/Curses-UI-0.9609/lib/Curses/UI.pm
2420[termbox]: https://github.com/nsf/termbox-go
2421[ttystudio]: https://github.com/chjj/ttystudio#choosing-a-new-font-for-your-terminal-recording