Merge pull request #2847 from LabhanshAgrawal/ligatures-addon

Merge ligatures addon into core repo
This commit is contained in:
Daniel Imms
2020-05-03 06:54:46 -07:00
committed by GitHub
19 changed files with 1184 additions and 5 deletions
+4 -2
View File
@@ -18,12 +18,14 @@
"addons/xterm-addon-web-links/src/tsconfig.json",
"addons/xterm-addon-webgl/src/tsconfig.json",
"addons/xterm-addon-serialize/src/tsconfig.json",
"addons/xterm-addon-serialize/benchmark/tsconfig.json"
"addons/xterm-addon-serialize/benchmark/tsconfig.json",
"addons/xterm-addon-ligatures/src/tsconfig.json"
],
"sourceType": "module"
},
"ignorePatterns": [
"**/typings/*.d.ts"
"**/typings/*.d.ts",
"**/node_modules"
],
"plugins": [
"@typescript-eslint"
+13
View File
@@ -0,0 +1,13 @@
node_modules/
.nyc_output/
coverage/
lib/
fonts/
.env
.vscode/
*.swp
*.tgz
npm-debug.log*
yarn-error.log*
+48
View File
@@ -0,0 +1,48 @@
# Blacklist - exclude everything except npm defaults such as LICENSE, etc
*
!*/
# Whitelist - entries to be included must be negated with "!"
!*.js
!*.json
# Whitelist - lib/
!lib/**/*.d.ts
!lib/**/*.js
!lib/**/*.js.map
# Whitelist - out/
!out/**/*.d.ts
!out/**/*.js
!out/**/*.js.map
# Whitelist - src/
!src/**/*.ts
!src/**/*.d.ts
!src/**/*.js
!src/**/*.js.map
# Whitelist - typings/
!typings/**/*.d.ts
# Blacklist - (normal behavior) these will override any whitelist
*.test.ts
*.test.d.ts
*.test.js
*.test.js.map
docs/
/.idea/
.vscode/
coverage/
.nyc_output/
fonts/
**/*.api.js
**/*.api.ts
tsconfig.json
.yarnrc
webpack.config.js
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2018
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+53
View File
@@ -0,0 +1,53 @@
## xterm-addon-ligatures
Add support for programming ligatures to [xterm.js] when running in environments with access to [Node.js] APIs (such as [Electron]).
### Requirements
* [Node.js] 8.x or higher (present in [Electron] 1.8.3 or higher)
* [xterm.js] 4.0.0 or higher using the default canvas renderer
### Install
```bash
npm install --save xterm-addon-ligatures
```
### Usage
```ts
import { Terminal } from 'xterm';
import { LigaturesAddon } from 'xterm-addon-ligatures';
const terminal = new Terminal();
const ligaturesAddon = new LigaturesAddon();
terminal.open(containerElement);
terminal.loadAddon(ligaturesAddon);
```
### How It Works
In a browser environment, font ligature information is read directly by the web browser and used to render text correctly without any intervention from the developer. As of version 3, xterm.js uses the canvas to render characters individually, resulting in a significant performance boost. However, this means that it can no longer lean on the browser to determine when to draw font ligatures.
This package locates the font file on disk for the font currently in use by the terminal and parses the ligature information out of it (via the [font-ligatures] package). As text is rendered in xterm.js, this package annotates it with the locations of ligatures, allowing xterm.js to render it correctly.
Since this package depends on being able to find and resolve a system font from disk, it has to have system access that isn't available in the web browser. As a result, this package is mainly useful in environments that combine browser and Node.js runtimes (such as [Electron]).
### Fonts
This package makes use of the following fonts for testing:
* [Fira Code][Fira Code] - [Licensed under the OFL][Fira Code License] by Nikita
Prokopov, Mozilla Foundation with reserved names Fira Code, Fira Mono, and
Fira Sans
* [Iosevka] - [Licensed under the OFL][Iosevka License] by Belleve Invis with
reserved name Iosevka
[xterm.js]: https://github.com/xtermjs/xterm.js
[Electron]: https://electronjs.org/
[Node.js]: https://nodejs.org/
[font-ligatures]: https://github.com/princjef/font-ligatures
[Fira Code]: https://github.com/tonsky/FiraCode
[Fira Code License]: https://github.com/tonsky/FiraCode/blob/master/LICENSE
[Iosevka]: https://github.com/be5invis/Iosevka
[Iosevka License]: https://github.com/be5invis/Iosevka/blob/master/LICENSE.md
@@ -0,0 +1,75 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
const fs = require('fs');
const path = require('path');
const util = require('util');
const axios = require('axios').default;
const mkdirp = require('mkdirp');
const yauzl = require('yauzl');
const urls = {
fira: 'https://github.com/tonsky/FiraCode/raw/master/distr/otf/FiraCode-Regular.otf',
iosevka: 'https://github.com/be5invis/Iosevka/releases/download/v1.14.3/01-iosevka-1.14.3.zip'
};
const writeFile = util.promisify(fs.writeFile);
const fontsFolder = path.join(__dirname, '../fonts');
async function download() {
await mkdirp(fontsFolder);
await downloadFiraCode();
await downloadIosevka();
console.log('Loaded all fonts for testing')
}
async function downloadFiraCode() {
const file = path.join(fontsFolder, 'firaCode.otf');
if (await util.promisify(fs.exists)(file)) {
console.log('Fira Code already loaded');
} else {
console.log('Downloading Fira Code...');
await writeFile(
file,
(await axios.get(urls.fira, { responseType: 'arraybuffer' })).data
);
}
}
async function downloadIosevka() {
const file = path.join(fontsFolder, 'iosevka.ttf');
if (await util.promisify(fs.exists)(file)) {
console.log('Iosevka already loaded');
} else {
console.log('Downloading Iosevka...');
const iosevkaContents = (await axios.get(urls.iosevka, { responseType: 'arraybuffer' })).data;
const iosevkaZipfile = await util.promisify(yauzl.fromBuffer)(iosevkaContents);
await new Promise((resolve, reject) => {
iosevkaZipfile.on('entry', entry => {
if (entry.fileName === 'ttf/iosevka-regular.ttf') {
iosevkaZipfile.openReadStream(entry, (err, stream) => {
if (err) {
return reject(err);
}
const writeStream = fs.createWriteStream(file);
stream.pipe(writeStream);
writeStream.on('close', () => resolve());
});
}
});
});
}
}
download();
process.on('unhandledRejection', e => {
console.error(e);
process.exit(1);
});
+47
View File
@@ -0,0 +1,47 @@
{
"name": "xterm-addon-ligatures",
"version": "0.2.1",
"description": "Add support for programming ligatures to xterm.js",
"author": {
"name": "The xterm.js authors",
"url": "https://xtermjs.org/"
},
"main": "lib/xterm-addon-ligatures.js",
"types": "typings/xterm-addon-ligatures.d.ts",
"repository": "https://github.com/xtermjs/xterm.js",
"engines": {
"node": ">8.0.0"
},
"scripts": {
"prepare": "node bin/download-fonts.js",
"build": "tsc -p src",
"watch": "tsc -w -p src",
"prepackage": "npm run build",
"package": "webpack",
"pretest": "npm run build",
"test": "nyc mocha out/**/*.test.js",
"prepublish": "npm run package"
},
"keywords": [
"font",
"ligature",
"xterm",
"xterm.js",
"terminal"
],
"license": "MIT",
"dependencies": {
"font-finder": "^1.0.4",
"font-ligatures": "^1.3.2"
},
"devDependencies": {
"@types/sinon": "^5.0.1",
"axios": "^0.18.0",
"mkdirp": "^0.5.1",
"sinon": "^6.1.3",
"yauzl": "^2.10.0"
},
"peerDependencies": {
"xterm": "^4.0.0"
}
}
@@ -0,0 +1,23 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { Terminal } from 'xterm';
import { enableLigatures } from '.';
export interface ITerminalAddon {
activate(terminal: Terminal): void;
dispose(): void;
}
export class LigaturesAddon implements ITerminalAddon {
constructor() {}
public activate(terminal: Terminal): void {
enableLigatures(terminal);
}
public dispose(): void {}
}
+53
View File
@@ -0,0 +1,53 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import * as fontFinder from 'font-finder';
import * as fontLigatures from 'font-ligatures';
import parse from './parse';
let fontsPromise: Promise<fontFinder.FontList> | undefined = undefined;
/**
* Loads the font ligature wrapper for the specified font family if it could be
* resolved, throwing if it is unable to find a suitable match.
* @param fontFamily The CSS font family definition to resolve
* @param cacheSize The size of the ligature cache to maintain if the font is resolved
*/
export default async function load(fontFamily: string, cacheSize: number): Promise<fontLigatures.Font | undefined> {
if (!fontsPromise) {
fontsPromise = fontFinder.list();
}
const fonts = await fontsPromise;
for (const family of parse(fontFamily)) {
// If we reach one of the generic font families, the font resolution
// will end for the browser and we can't determine the specific font
// used. Throw.
if (genericFontFamilies.includes(family)) {
return undefined;
}
if (fonts.hasOwnProperty(family) && fonts[family].length > 0) {
return await fontLigatures.loadFile(fonts[family][0].path, { cacheSize });
}
}
// If none of the fonts could resolve, throw an error
return undefined;
}
// https://drafts.csswg.org/css-fonts-4/#generic-font-families
const genericFontFamilies = [
'serif',
'sans-serif',
'cursive',
'fantasy',
'monospace',
'system-ui',
'emoji',
'math',
'fangsong'
];
@@ -0,0 +1,222 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import * as path from 'path';
import * as sinon from 'sinon';
import { assert } from 'chai';
import * as fontFinder from 'font-finder';
import * as fontLigatures from 'font-ligatures';
import * as ligatureSupport from '.';
describe('xterm-addon-ligatures', () => {
let onRefresh: sinon.SinonStub;
let term: MockTerminal;
// -> forms a ligature in Fira Code and Iosevka, but www only forms a ligature
// in Fira Code
const input = 'a -> b www c';
before(() => {
sinon.stub(fontFinder, 'list').returns(Promise.resolve({
// eslint-disable-next-line @typescript-eslint/naming-convention
'Fira Code': [{
path: path.join(__dirname, '../fonts/firaCode.otf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}],
// eslint-disable-next-line @typescript-eslint/naming-convention
'Iosevka': [{
path: path.join(__dirname, '../fonts/iosevka.ttf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}],
// eslint-disable-next-line @typescript-eslint/naming-convention
'Nonexistant Font': [{
path: path.join(__dirname, '../fonts/nonexistant.ttf'),
style: fontFinder.Style.Regular,
type: fontFinder.Type.Monospace,
weight: 400
}]
} as fontFinder.FontList));
});
beforeEach(() => {
onRefresh = sinon.stub();
term = new MockTerminal(onRefresh);
ligatureSupport.enableLigatures(term as any);
});
it('registers itself correctly', () => {
const term = new MockTerminal(sinon.spy());
assert.isUndefined(term.joiner);
ligatureSupport.enableLigatures(term as any);
assert.isFunction(term.joiner);
});
it('registers itself correctly when called directly', () => {
const term = new MockTerminal(sinon.spy());
assert.isUndefined(term.joiner);
ligatureSupport.enableLigatures(term as any);
assert.isFunction(term.joiner);
});
it('returns an empty set of ranges on the first call while the font is loading', () => {
assert.deepEqual(term.joiner!(input), []);
});
it('returns the correct set of ranges once the font has loaded', done => {
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
it('handles quoted font names', done => {
term.setOption('fontFamily', '"Fira Code", monospace');
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
it('falls back to later fonts if earlier ones are not present', done => {
term.setOption('fontFamily', 'notinstalled, Fira Code, monospace');
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
it('uses the current font value', done => {
// The first three calls are all synchronous so that we don't allow time for
// any fonts to load while we're switching things around
term.setOption('fontFamily', 'Fira Code');
assert.deepEqual(term.joiner!(input), []);
term.setOption('fontFamily', 'notinstalled');
assert.deepEqual(term.joiner!(input), []);
term.setOption('fontFamily', 'Iosevka');
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4]]);
// And switch it back to Fira Code for good measure
term.setOption('fontFamily', 'Fira Code');
// At this point, we haven't loaded the new font, so the result reverts
// back to empty until that happens
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
});
it('allows multiple terminal instances that use different fonts', done => {
const onRefresh2 = sinon.stub();
const term2 = new MockTerminal(onRefresh2);
term2.setOption('fontFamily', 'Iosevka');
ligatureSupport.enableLigatures(term2 as any);
assert.deepEqual(term.joiner!(input), []);
onRefresh.callsFake(() => {
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
assert.deepEqual(term2.joiner!(input), []);
onRefresh2.callsFake(() => {
assert.deepEqual(term2.joiner!(input), [[2, 4]]);
assert.deepEqual(term.joiner!(input), [[2, 4], [7, 10]]);
done();
});
});
});
it('fails if it finds but cannot load the font', async () => {
term.setOption('fontFamily', 'Nonexistant Font, monospace');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.throws(() => term.joiner!(input));
});
it('returns nothing if the font is not present on the system', async () => {
term.setOption('fontFamily', 'notinstalled');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.deepEqual(term.joiner!(input), []);
});
it('returns nothing if no specific font is specified', async () => {
term.setOption('fontFamily', 'monospace');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.deepEqual(term.joiner!(input), []);
});
it('returns nothing if no fonts are provided', async () => {
term.setOption('fontFamily', '');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.deepEqual(term.joiner!(input), []);
});
it('fails when given malformed inputs', async () => {
term.setOption('fontFamily', {} as any);
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.throws(() => term.joiner!(input));
});
it('ensures no empty errors are thrown', async () => {
sinon.stub(fontLigatures, 'loadFile').callsFake(async () => { throw undefined; });
term.setOption('fontFamily', 'Iosevka');
assert.deepEqual(term.joiner!(input), []);
await delay(500);
assert.isTrue(onRefresh.notCalled);
assert.throws(() => term.joiner!(input), 'Failure while loading font');
(fontLigatures.loadFile as sinon.SinonStub).restore();
});
});
class MockTerminal {
private _options: { [name: string]: string | number } = {
fontFamily: 'Fira Code, monospace',
rows: 50
};
public joiner?: (text: string) => [number, number][];
public refresh: (start: number, end: number) => void;
constructor(onRefresh: (start: number, end: number) => void) {
this.refresh = onRefresh;
}
public registerCharacterJoiner(handler: (text: string) => [number, number][]): number {
this.joiner = handler;
return 1;
}
public deregisterCharacterJoiner(id: number): void {
this.joiner = undefined;
}
public setOption(name: string, value: string | number): void {
this._options[name] = value;
}
public getOption(name: string): string | number {
return this._options[name];
}
}
function delay(delayMs: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, delayMs));
}
+85
View File
@@ -0,0 +1,85 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { Terminal } from 'xterm';
import { Font } from 'font-ligatures';
import load from './font';
const enum LoadingState {
UNLOADED,
LOADING,
LOADED,
FAILED
}
// Caches 100K characters worth of ligatures. In practice this works out to
// about 650 KB worth of cache, when a moderate number of ligatures are present.
const CACHE_SIZE = 100000;
/**
* Enable ligature support for the provided Terminal instance. To function
* properly, this must be called after `open()` is called on the therminal. If
* the font currently in use supports ligatures, the terminal will automatically
* start to render them.
* @param term Terminal instance from xterm.js
*/
export function enableLigatures(term: Terminal): void {
let currentFontName: string | undefined = undefined;
let font: Font | undefined = undefined;
let loadingState: LoadingState = LoadingState.UNLOADED;
let loadError: any | undefined = undefined;
term.registerCharacterJoiner((text: string): [number, number][] => {
// If the font hasn't been loaded yet, load it and return an empty result
const termFont = term.getOption('fontFamily');
if (
termFont &&
(loadingState === LoadingState.UNLOADED || currentFontName !== termFont)
) {
font = undefined;
loadingState = LoadingState.LOADING;
currentFontName = termFont;
const currentCallFontName = currentFontName;
load(currentCallFontName, CACHE_SIZE)
.then(f => {
// Another request may have come in while we were waiting, so make
// sure our font is still vaild.
if (currentCallFontName === term.getOption('fontFamily')) {
loadingState = LoadingState.LOADED;
font = f;
// Only refresh things if we actually found a font
if (f) {
term.refresh(0, term.getOption('rows') - 1);
}
}
})
.catch(e => {
// Another request may have come in while we were waiting, so make
// sure our font is still vaild.
if (currentCallFontName === term.getOption('fontFamily')) {
loadingState = LoadingState.FAILED;
font = undefined;
loadError = e;
}
});
}
if (font && loadingState === LoadingState.LOADED) {
// We clone the entries to avoid the internal cache of the ligature finder
// getting messed up.
return font.findLigatureRanges(text).map<[number, number]>(
range => [range[0], range[1]]
);
}
if (loadingState === LoadingState.FAILED) {
throw loadError || new Error('Failure while loading font');
}
return [];
});
}
@@ -0,0 +1,75 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
import { assert } from 'chai';
import parse from './parse';
// TODO: integrate tests from http://test.csswg.org/suites/css-fonts-4_dev/nightly-unstable/
describe('parse', () => {
it('parses individual families', () => {
assert.deepEqual(parse('monospace'), ['monospace']);
});
it('parses multiple families', () => {
assert.deepEqual(parse('Arial, Verdana, serif'), ['Arial', 'Verdana', 'serif']);
});
it('parses quoted families', () => {
assert.deepEqual(parse('"Times New Roman", serif'), ['Times New Roman', 'serif']);
});
it('parses single quoted families', () => {
assert.deepEqual(parse('\'Times New Roman\', serif'), ['Times New Roman', 'serif']);
});
it('parses families with spaces in their names', () => {
assert.deepEqual(parse('Times New Roman, serif'), ['Times New Roman', 'serif']);
});
it('collapses multiple spaces together in identifiers', () => {
assert.deepEqual(parse('Times New Roman, serif'), ['Times New Roman', 'serif']);
});
it('does not collapse multiple spaces together in quoted strings', () => {
assert.deepEqual(parse('"Times New Roman", serif'), ['Times New Roman', 'serif']);
});
it('handles escaped characters in strings', () => {
assert.deepEqual(parse('"quote \\" slash \\\\ slashquote \\\\\\"", serif'), ['quote " slash \\ slashquote \\"', 'serif']);
});
it('fails if a family has an unterminated string', () => {
assert.throws(() => parse('"Unterminated, serif'));
});
it('handles unicode escape sequences', () => {
assert.deepEqual(parse('"space\\20 between", serif'), ['space between', 'serif']);
});
it('swallows only the first space after a unicode escape', () => {
assert.deepEqual(parse('"two-space\\20 between", serif'), ['two-space between', 'serif']);
});
it('automatically ends the unicode escape after six digits', () => {
assert.deepEqual(parse('space\\000020between, serif'), ['space between', 'serif']);
});
it('handles unicode escapes at the end of the family', () => {
assert.deepEqual(parse('endswithbrace \\7b, serif'), ['endswithbrace {', 'serif']);
});
it('handles unicode escapes at the end of the input', () => {
assert.deepEqual(parse('endswithbrace \\7b'), ['endswithbrace {']);
});
it('handles other escaped characters in identifiers', () => {
assert.deepEqual(parse('has\\,comma'), ['has,comma']);
});
it('swallows escaped newlines in strings', () => {
assert.deepEqual(parse('"multi \\\nline", serif'), ['multi line', 'serif']);
});
});
+180
View File
@@ -0,0 +1,180 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*/
interface IParseContext {
input: string;
offset: number;
}
/**
* Parses a CSS font family value, returning the component font families
* contained within.
*
* @param family The CSS font family input string to parse
*/
export default function parse(family: string): string[] {
if (typeof family !== 'string') {
throw new Error('Font family must be a string');
}
const context: IParseContext = {
input: family,
offset: 0
};
const families = [];
let currentFamily = '';
// Work through the input character by character until there are none left.
// This lexing and parsing in one pass.
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
switch (char) {
// String
case '\'':
case '"':
currentFamily += parseString(context, char);
break;
// End of family
case ',':
families.push(currentFamily);
currentFamily = '';
break;
default:
// Identifiers (whitespace between families is swallowed)
if (!/\s/.test(char)) {
context.offset--;
currentFamily += parseIdentifier(context);
families.push(currentFamily);
currentFamily = '';
}
}
}
return families;
}
/**
* Parse a CSS string.
*
* @param context Parsing input and offset
* @param quoteChar The quote character for the string (' or ")
*/
function parseString(context: IParseContext, quoteChar: '\'' | '"'): string {
let str = '';
let escaped = false;
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
if (escaped) {
if (/[0-9a-fA-F]/.test(char)) {
// Unicode escape
context.offset--;
str += parseUnicode(context);
} else if (char !== '\n') {
// Newlines are ignored if escaped. Other characters are used as is.
str += char;
}
escaped = false;
} else {
switch (char) {
// Terminated quote
case quoteChar:
return str;
// Begin escape
case '\\':
escaped = true;
break;
// Add character to string
default:
str += char;
}
}
}
throw new Error('Unterminated string');
}
/**
* Parse a CSS custom identifier.
*
* @param context Parsing input and offset
*/
function parseIdentifier(context: IParseContext): string {
let str = '';
let escaped = false;
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
if (escaped) {
if (/[0-9a-fA-F]/.test(char)) {
// Unicode escape
context.offset--;
str += parseUnicode(context);
} else {
// Everything else is used as is
str += char;
}
escaped = false;
} else {
switch (char) {
// Begin escape
case '\\':
escaped = true;
break;
// Terminate identifier
case ',':
return str;
default:
if (/\s/.test(char)) {
// Whitespace is collapsed into a single space within an identifier
if (!str.endsWith(' ')) {
str += ' ';
}
} else {
// Add other characters directly
str += char;
}
}
}
}
return str;
}
/**
* Parse a CSS unicode escape.
*
* @param context Parsing input and offset
*/
function parseUnicode(context: IParseContext): string {
let str = '';
while (context.offset < context.input.length) {
const char = context.input[context.offset++];
if (/\s/.test(char)) {
// The first whitespace character after a unicode escape indicates the end
// of the escape and is swallowed.
return unicodeToString(str);
}
if (str.length >= 6 || !/[0-9a-fA-F]/.test(char)) {
// If the next character is not a valid hex digit or we have reached the
// maximum of 6 digits in the escape, terminate the escape.
context.offset--;
return unicodeToString(str);
}
// Otherwise, just add it to the escape
str += char;
}
return unicodeToString(str);
}
/**
* Convert a unicode code point from a hex string to a utf8 string.
*
* @param codePoint Unicode code point represented as a hex string
*/
function unicodeToString(codePoint: string): string {
return String.fromCodePoint(parseInt(codePoint, 16));
}
@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"sourceMap": true,
"outDir": "../out",
"rootDir": ".",
"strict": true,
"noUnusedLocals": true,
"preserveWatchOutput": true
},
"include": [
"./**/*",
"../../../typings/xterm.d.ts"
]
}
@@ -0,0 +1,34 @@
/**
* Copyright (c) 2018 The xterm.js authors. All rights reserved.
* @license MIT
*
* This contains the type declarations for the xterm-addon-ligatures library.
* Note that some interfaces may differ between this file and the actual
* implementation in src/, that's because this file declares the *public* API
* which is intended to be stable and consumed by external programs.
*/
import { Terminal, ITerminalAddon } from 'xterm';
declare module 'xterm-addon-ligatures' {
/**
* An xterm.js addon that enables web links.
*/
export class LigaturesAddon implements ITerminalAddon {
/**
* Creates a new ligatures addon.
*/
constructor();
/**
* Activates the addon
* @param terminal The terminal the addon is being loaded in.
*/
public activate(terminal: Terminal): void;
/**
* Disposes the addon.
*/
public dispose(): void;
}
}
@@ -0,0 +1,36 @@
/**
* Copyright (c) 2019 The xterm.js authors. All rights reserved.
* @license MIT
*/
const path = require('path');
const addonName = 'LigaturesAddon';
const mainFile = 'xterm-addon-ligatures.js';
module.exports = {
entry: `./out/${addonName}.js`,
devtool: 'source-map',
target: 'electron-renderer',
module: {
rules: [
{
test: /\.js$/,
use: ["source-map-loader"],
enforce: "pre",
exclude: /node_modules/
}
]
},
output: {
filename: mainFile,
path: path.resolve('./lib'),
library: addonName,
libraryTarget: 'umd'
},
mode: 'production',
externals: {
'font-finder':'font-finder',
'font-ligatures':'font-ligatures'
}
};
+194
View File
@@ -0,0 +1,194 @@
# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.
# yarn lockfile v1
"@sinonjs/formatio@^2.0.0":
version "2.0.0"
resolved "https://registry.yarnpkg.com/@sinonjs/formatio/-/formatio-2.0.0.tgz#84db7e9eb5531df18a8c5e0bfb6e449e55e654b2"
dependencies:
samsam "1.3.0"
"@sinonjs/samsam@^2.0.0":
version "2.0.0"
resolved "https://registry.yarnpkg.com/@sinonjs/samsam/-/samsam-2.0.0.tgz#9163742ac35c12d3602dece74317643b35db6a80"
"@types/sinon@^5.0.1":
version "5.0.1"
resolved "https://registry.yarnpkg.com/@types/sinon/-/sinon-5.0.1.tgz#a15b36ec42f1f53166617491feabd1734cb03e21"
axios@^0.18.0:
version "0.18.1"
resolved "https://registry.yarnpkg.com/axios/-/axios-0.18.1.tgz#ff3f0de2e7b5d180e757ad98000f1081b87bcea3"
dependencies:
follow-redirects "1.5.10"
is-buffer "^2.0.2"
buffer-crc32@~0.2.3:
version "0.2.13"
resolved "https://registry.yarnpkg.com/buffer-crc32/-/buffer-crc32-0.2.13.tgz#0d333e3f00eac50aa1454abd30ef8c2a5d9a7242"
debug@=3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261"
dependencies:
ms "2.0.0"
diff@^3.5.0:
version "3.5.0"
resolved "https://registry.yarnpkg.com/diff/-/diff-3.5.0.tgz#800c0dd1e0a8bfbc95835c202ad220fe317e5a12"
fd-slicer@~1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/fd-slicer/-/fd-slicer-1.1.0.tgz#25c7c89cb1f9077f8891bbe61d8f390eae256f1e"
dependencies:
pend "~1.2.0"
follow-redirects@1.5.10:
version "1.5.10"
resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.5.10.tgz#7b7a9f9aea2fdff36786a94ff643ed07f4ff5e2a"
dependencies:
debug "=3.1.0"
font-finder@^1.0.3, font-finder@^1.0.4:
version "1.0.4"
resolved "https://registry.yarnpkg.com/font-finder/-/font-finder-1.0.4.tgz#2ca944954dd8d0e1b5bdc4c596cc08607761d89b"
dependencies:
get-system-fonts "^2.0.0"
promise-stream-reader "^1.0.1"
font-ligatures@^1.3.2:
version "1.3.2"
resolved "https://registry.yarnpkg.com/font-ligatures/-/font-ligatures-1.3.2.tgz#227eb5fc38fef34b5373aa19b555320b82842a71"
dependencies:
font-finder "^1.0.3"
lru-cache "^4.1.3"
opentype.js "^0.8.0"
get-system-fonts@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/get-system-fonts/-/get-system-fonts-2.0.0.tgz#a43b9a33f05c0715a60176d2aad5ce6e98f0a3c6"
has-flag@^3.0.0:
version "3.0.0"
resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-3.0.0.tgz#b5d454dc2199ae225699f3467e5a07f3b955bafd"
is-buffer@^2.0.2:
version "2.0.3"
resolved "https://registry.yarnpkg.com/is-buffer/-/is-buffer-2.0.3.tgz#4ecf3fcf749cbd1e472689e109ac66261a25e725"
isarray@0.0.1:
version "0.0.1"
resolved "https://registry.yarnpkg.com/isarray/-/isarray-0.0.1.tgz#8a18acfca9a8f4177e09abfc6038939b05d1eedf"
just-extend@^1.1.27:
version "1.1.27"
resolved "https://registry.yarnpkg.com/just-extend/-/just-extend-1.1.27.tgz#ec6e79410ff914e472652abfa0e603c03d60e905"
lodash.get@^4.4.2:
version "4.4.2"
resolved "https://registry.yarnpkg.com/lodash.get/-/lodash.get-4.4.2.tgz#2d177f652fa31e939b4438d5341499dfa3825e99"
lolex@^2.3.2, lolex@^2.4.2:
version "2.7.1"
resolved "https://registry.yarnpkg.com/lolex/-/lolex-2.7.1.tgz#e40a8c4d1f14b536aa03e42a537c7adbaf0c20be"
lru-cache@^4.1.3:
version "4.1.3"
resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-4.1.3.tgz#a1175cf3496dfc8436c156c334b4955992bce69c"
dependencies:
pseudomap "^1.0.2"
yallist "^2.1.2"
minimist@0.0.8:
version "0.0.8"
resolved "https://registry.yarnpkg.com/minimist/-/minimist-0.0.8.tgz#857fcabfc3397d2625b8228262e86aa7a011b05d"
mkdirp@^0.5.1:
version "0.5.1"
resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-0.5.1.tgz#30057438eac6cf7f8c4767f38648d6697d75c903"
dependencies:
minimist "0.0.8"
ms@2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
nise@^1.3.3:
version "1.4.2"
resolved "https://registry.yarnpkg.com/nise/-/nise-1.4.2.tgz#a9a3800e3994994af9e452333d549d60f72b8e8c"
dependencies:
"@sinonjs/formatio" "^2.0.0"
just-extend "^1.1.27"
lolex "^2.3.2"
path-to-regexp "^1.7.0"
text-encoding "^0.6.4"
opentype.js@^0.8.0:
version "0.8.0"
resolved "https://registry.yarnpkg.com/opentype.js/-/opentype.js-0.8.0.tgz#acabcfa1642fbe894a3e4d759e43ba694e02bd35"
dependencies:
tiny-inflate "^1.0.2"
path-to-regexp@^1.7.0:
version "1.7.0"
resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-1.7.0.tgz#59fde0f435badacba103a84e9d3bc64e96b9937d"
dependencies:
isarray "0.0.1"
pend@~1.2.0:
version "1.2.0"
resolved "https://registry.yarnpkg.com/pend/-/pend-1.2.0.tgz#7a57eb550a6783f9115331fcf4663d5c8e007a50"
promise-stream-reader@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/promise-stream-reader/-/promise-stream-reader-1.0.1.tgz#4e793a79c9d49a73ccd947c6da9c127f12923649"
pseudomap@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/pseudomap/-/pseudomap-1.0.2.tgz#f052a28da70e618917ef0a8ac34c1ae5a68286b3"
samsam@1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/samsam/-/samsam-1.3.0.tgz#8d1d9350e25622da30de3e44ba692b5221ab7c50"
sinon@^6.1.3:
version "6.1.3"
resolved "https://registry.yarnpkg.com/sinon/-/sinon-6.1.3.tgz#98e7d716b7b11f7f1200e9c997e74f50ae094660"
dependencies:
"@sinonjs/formatio" "^2.0.0"
"@sinonjs/samsam" "^2.0.0"
diff "^3.5.0"
lodash.get "^4.4.2"
lolex "^2.4.2"
nise "^1.3.3"
supports-color "^5.4.0"
type-detect "^4.0.8"
supports-color@^5.4.0:
version "5.4.0"
resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-5.4.0.tgz#1c6b337402c2137605efe19f10fec390f6faab54"
dependencies:
has-flag "^3.0.0"
text-encoding@^0.6.4:
version "0.6.4"
resolved "https://registry.yarnpkg.com/text-encoding/-/text-encoding-0.6.4.tgz#e399a982257a276dae428bb92845cb71bdc26d19"
tiny-inflate@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/tiny-inflate/-/tiny-inflate-1.0.2.tgz#93d9decffc8805bd57eae4310f0b745e9b6fb3a7"
type-detect@^4.0.8:
version "4.0.8"
resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c"
yallist@^2.1.2:
version "2.1.2"
resolved "https://registry.yarnpkg.com/yallist/-/yallist-2.1.2.tgz#1c11f9218f076089a47dd512f93c6699a6a81d52"
yauzl@^2.10.0:
version "2.10.0"
resolved "https://registry.yarnpkg.com/yauzl/-/yauzl-2.10.0.tgz#c7eb17c93e112cb1086fa6d8e51fb0667b79a5f9"
dependencies:
buffer-crc32 "~0.2.3"
fd-slicer "~1.1.0"
+1
View File
@@ -28,6 +28,7 @@ if (changedFiles.some(e => e.search(/^addons\//) === -1)) {
const addonPackageDirs = [
path.resolve(__dirname, '../addons/xterm-addon-attach'),
path.resolve(__dirname, '../addons/xterm-addon-fit'),
path.resolve(__dirname, '../addons/xterm-addon-ligatures'),
path.resolve(__dirname, '../addons/xterm-addon-search'),
path.resolve(__dirname, '../addons/xterm-addon-serialize'),
path.resolve(__dirname, '../addons/xterm-addon-unicode11'),
+4 -3
View File
@@ -7,11 +7,12 @@
{ "path": "./test/benchmark" },
{ "path": "./addons/xterm-addon-attach/src" },
{ "path": "./addons/xterm-addon-fit/src" },
{ "path": "./addons/xterm-addon-ligatures/src" },
{ "path": "./addons/xterm-addon-search/src" },
{ "path": "./addons/xterm-addon-serialize/src" },
{ "path": "./addons/xterm-addon-serialize/benchmark" },
{ "path": "./addons/xterm-addon-unicode11/src" },
{ "path": "./addons/xterm-addon-web-links/src" },
{ "path": "./addons/xterm-addon-webgl/src" },
{ "path": "./addons/xterm-addon-serialize/src" },
{ "path": "./addons/xterm-addon-serialize/benchmark" }
{ "path": "./addons/xterm-addon-webgl/src" }
]
}