Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Terminal.getRangeAsHTML() #2223

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/Terminal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1011,4 +1011,56 @@ describe('Terminal', () => {
expect(term.buffer.lines.get(0).loadCell(79, cell).getChars()).eql(''); // empty cell after fullwidth
});
});

describe('get range as HTML', () => {
beforeEach(() => {
term.wraparoundMode = true;
term.write(Array(INIT_COLS + 1).join('0'));
term.write(Array(INIT_COLS + 1).join('1'));
term.write(Array(INIT_COLS + 1).join('2'));
(term as any)._colorManager = {
colors: {
foreground: { css: 'white' },
background: { css: 'black' },
ansi: {
1: { css: 'red' },
2: { css: 'green' },
209: { css: '#ff875f' }
}
}
};
});

afterEach(() => {
term.clear();
});

it('should work within single lines', () => {
const html = term.getRangeAsHTML({ startRow: 1, startColumn: 10, endRow: 1, endColumn: 15 });
expect(html).eq('<div style="font-family: courier-new, courier, monospace; white-space: pre"><div><span style="color: white; background: black;">11111</span></div></div>');
});

it('should work within multiple lines', () => {
const html = term.getRangeAsHTML({ startRow: 0, startColumn: INIT_COLS - 5, endRow: 1, endColumn: 5 });
expect(html).eq('<div style="font-family: courier-new, courier, monospace; white-space: pre"><div><span style="color: white; background: black;">00000</span></div><div><span style="color: white; background: black;">11111</span></div></div>');
});

it('should work with multiple styles', () => {
term.write('1\x1b[1m2');
const html = term.getRangeAsHTML({ startRow: 3, startColumn: 0, endRow: 3, endColumn: 2 });
expect(html).eq('<div style="font-family: courier-new, courier, monospace; white-space: pre"><div><span style="color: white; background: black;">1</span><span style="color: white; background: black; font-weight: bold;">2</span></div></div>');
});

it('should work with italics and underlines', () => {
term.write('\x1b[3mitalic\x1b[0m\x1b[4munderline');
const html = term.getRangeAsHTML({ startRow: 3, startColumn: 0, endRow: 3, endColumn: 15 });
expect(html).eq('<div style="font-family: courier-new, courier, monospace; white-space: pre"><div><span style="color: white; background: black; font-style: italic;">italic</span><span style="color: white; background: black; text-decoration: underline;">underline</span></div></div>');
});

it('should work with ANSI palette, 256 color palette and TrueColor', () => {
term.write('\x1b[31mred\x1b[0m\x1b[42mgreenbg\x1b[0m\x1b[38;5;209msalmon1\x1b[38;2;255;100;0mtruecolor');
const html = term.getRangeAsHTML({ startRow: 3, startColumn: 0, endRow: 3, endColumn: 26 });
expect(html).eq('<div style="font-family: courier-new, courier, monospace; white-space: pre"><div><span style="color: red; background: black;">red</span><span style="color: white; background: green;">greenbg</span><span style="color: #ff875f; background: black;">salmon1</span><span style="color: #ff6400; background: black;">truecolor</span></div></div>');
});
});
});
68 changes: 67 additions & 1 deletion src/Terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ import { DomRenderer } from './renderer/dom/DomRenderer';
import { IKeyboardEvent, KeyboardResultType, ICharset, IBufferLine, IAttributeData } from 'common/Types';
import { evaluateKeyboardEvent } from 'common/input/Keyboard';
import { EventEmitter, IEvent } from 'common/EventEmitter';
import { Attributes, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
import { Attributes, AttributeData, CellData, DEFAULT_ATTR_DATA } from 'common/buffer/BufferLine';
import { applyWindowsMode } from './WindowsMode';
import { ColorManager } from 'browser/ColorManager';
import { RenderService } from 'browser/services/RenderService';
Expand Down Expand Up @@ -1904,6 +1904,72 @@ export class Terminal extends Disposable implements ITerminal, IDisposable, IInp
this.buffer.tabs[this.buffer.x] = true;
}

public getRangeAsHTML(range: ISelectionPosition): string {
const fontFamily = this.optionsService.getOption('fontFamily');
let html = `<div style="font-family: ${fontFamily}; white-space: pre">`;
if (range.startRow === range.endRow) {
html += this._getRowAsHTML(range.startRow, range.startColumn, range.endColumn);
} else {
html += this._getRowAsHTML(range.startRow, range.startColumn, this.cols);
for (let y = range.startRow + 1; y < range.endRow; y++) {
html += this._getRowAsHTML(y, 0, this.cols);
}
html += this._getRowAsHTML(range.endRow, 0, range.endColumn);
}
html += '</div>';
return html;
}

private _getCSSColor(mode: Attributes, color: number): string | null {
if (mode === Attributes.CM_RGB) {
let css = '#';
for (const channel of AttributeData.toColorRGB(color)) {
if (channel < 16) {
css += '0';
}
css += channel.toString(16);
}
return css;
}
if (mode === Attributes.CM_P16 || mode === Attributes.CM_P256) {
return this._colorManager.colors.ansi[color].css;
}
return null;
}

private _getRowAsHTML(y: number, start: number, end: number): string {
let html = '<div>';
let lastStyle = null;
const line = this.buffers.active.lines.get(y);
const cell = new CellData();
for (let i = start; i < end; i++) {
line.loadCell(i, cell);
const fg = this._getCSSColor(cell.getFgColorMode(), cell.getFgColor()) || this._colorManager.colors.foreground.css;
const bg = this._getCSSColor(cell.getBgColorMode(), cell.getBgColor()) || this._colorManager.colors.background.css;

let style = `color: ${fg}; background: ${bg};`;
if (cell.isBold()) {
style += ' font-weight: bold;';
}
if (cell.isItalic()) {
style += ' font-style: italic;';
}
if (cell.isUnderline()) {
style += ' text-decoration: underline;';
}
if (style !== lastStyle) {
if (lastStyle) {
html += '</span>';
}
html += `<span style="${style.trim()}">`;
lastStyle = style;
}
html += line.getString(i) || ' ';
}
html += '</span></div>';
return html;
}

// TODO: Remove cancel function and cancelEvents option
public cancel(ev: Event, force?: boolean): boolean {
if (!this.options.cancelEvents && !force) {
Expand Down
3 changes: 3 additions & 0 deletions src/TestUtils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ export class MockTerminal implements ITerminal {
writeUtf8(data: Uint8Array): void {
throw new Error('Method not implemented.');
}
getRangeAsHTML(range: ISelectionPosition): string {
throw new Error('Method not implemented.');
}
bracketedPasteMode: boolean;
mouseHelper: IMouseHelper;
renderer: IRenderer;
Expand Down
1 change: 1 addition & 0 deletions src/Types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,7 @@ export interface IPublicTerminal extends IDisposable {
clear(): void;
write(data: string): void;
writeUtf8(data: Uint8Array): void;
getRangeAsHTML(range: ISelectionPosition): string;
refresh(start: number, end: number): void;
reset(): void;
}
Expand Down
3 changes: 3 additions & 0 deletions src/public/Terminal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,9 @@ export class Terminal implements ITerminalApi {
public writeUtf8(data: Uint8Array): void {
this._core.writeUtf8(data);
}
public getRangeAsHTML(range: ISelectionPosition): string {
return this._core.getRangeAsHTML(range)
}
public getOption(key: 'bellSound' | 'bellStyle' | 'cursorStyle' | 'fontFamily' | 'fontWeight' | 'fontWeightBold' | 'rendererType' | 'termName'): string;
public getOption(key: 'allowTransparency' | 'cancelEvents' | 'convertEol' | 'cursorBlink' | 'debug' | 'disableStdin' | 'macOptionIsMeta' | 'rightClickSelectsWord' | 'popOnBell' | 'screenKeys' | 'useFlowControl' | 'visualBell'): boolean;
public getOption(key: 'colors'): string[];
Expand Down
6 changes: 6 additions & 0 deletions typings/xterm.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -767,6 +767,12 @@ declare module 'xterm' {
*/
setOption(key: string, value: any): void;

/**
* Returns HTML representing the specified content range.
* @param range Range of cells to be converted.
*/
getRangeAsHTML(range: ISelectionPosition): string;

/**
* Tells the renderer to refresh terminal content between two rows
* (inclusive) at the next opportunity.
Expand Down