ESLint: Added quotes rule (#2835)

This commit is contained in:
Michael Schmidt 2021-04-17 22:26:40 +02:00 committed by GitHub
parent bb1eca949c
commit 9cae446161
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
45 changed files with 211 additions and 200 deletions

View File

@ -3,6 +3,9 @@ module.exports = {
root: true,
extends: 'eslint:recommended',
rules: {
// stylistic rules
'quotes': ['warn', 'single', { avoidEscape: true, allowTemplateLiterals: true }],
// I turned this rule off because we use `hasOwnProperty` in a lot of places
// TODO: Think about re-enabling this rule
'no-prototype-builtins': 'off',

View File

@ -186,7 +186,7 @@ for (var id in themes) {
$u.element.create('input', {
properties: {
type: 'radio',
name: "theme",
name: 'theme',
id: 'theme=' + id,
checked: current === id,
value: id,
@ -261,7 +261,7 @@ Prism && Prism.hooks.add('complete', function (env) {
// transfer margin of pre to wrapper
wrapper.style.margin = window.getComputedStyle(pre).margin;
pre.style.margin = "0";
pre.style.margin = '0';
});
});

View File

@ -194,7 +194,7 @@ for (var category in components) {
for (var alias in lang.aliasTitles)
if (lang.aliasTitles.hasOwnProperty(alias))
titles.push(lang.aliasTitles[alias]);
return titles.join(" + ");
return titles.join(' + ');
}
var label = $u.element.create('label', {
@ -506,18 +506,18 @@ function generateCode(){
$u.element.contents(error, errors);
}
var redownloadUrl = window.location.href.split("#")[0] + "#";
var redownloadUrl = window.location.href.split('#')[0] + '#';
for (var category in redownload) {
redownloadUrl += category + "=" + redownload[category].join('+') + "&";
redownloadUrl += category + '=' + redownload[category].join('+') + '&';
}
redownloadUrl = redownloadUrl.replace(/&$/,"");
redownloadUrl = redownloadUrl.replace(/&$/,'');
window.location.replace(redownloadUrl);
var versionComment = "/* PrismJS " + version + "\n" + redownloadUrl + " */";
var versionComment = '/* PrismJS ' + version + '\n' + redownloadUrl + ' */';
for (var type in code) {
(function (type) {
var text = versionComment + "\n" + code[type];
var text = versionComment + '\n' + code[type];
var fileName = 'prism.' + type;
var codeElement = $('#download-' + type + ' code');
@ -533,7 +533,7 @@ function generateCode(){
$('#download-' + type + ' .download-button').onclick = function () {
saveAs(new Blob([text], { type: "application/octet-stream;charset=utf-8" }), fileName);
saveAs(new Blob([text], { type: 'application/octet-stream;charset=utf-8' }), fileName);
};
})(type);
}
@ -562,7 +562,7 @@ function buildCode(promises) {
var toSortMap = {};
promises.forEach(function (p) {
if (p.category == "core" || p.category == "themes") {
if (p.category == 'core' || p.category == 'themes') {
finalPromises.push(p);
} else {
var infos = toSortMap[p.id];
@ -576,7 +576,7 @@ function buildCode(promises) {
// this assumes that the ids in `toSortMap` are complete under transitive requirements
getLoader(components, Object.keys(toSortMap)).getIds().forEach(function (id) {
if (!toSortMap[id]) {
console.error(id + " not found.");
console.error(id + ' not found.');
}
finalPromises.push.apply(finalPromises, toSortMap[id]);
});

View File

@ -232,7 +232,7 @@ function getDependenciesOfLanguage(lang) {
return [];
}
return ($u.type(components.languages[lang].require) === "array")
return ($u.type(components.languages[lang].require) === 'array')
? components.languages[lang].require
: [components.languages[lang].require];
}

View File

@ -32,17 +32,17 @@ Prism.languages.abap = {
pattern: /(\s)&&?(?=\s)/,
lookbehind: true,
/* The official editor highlights */
alias: "keyword"
alias: 'keyword'
},
'token-operator' : [{
/* Special operators used to access structure components, class methods/attributes, etc. */
pattern: /(\w)(?:->?|=>|[~|{}])(?=\w)/,
lookbehind: true,
alias: "punctuation"
alias: 'punctuation'
}, {
/* Special tokens used do delimit string templates */
pattern: /[|{}]/,
alias: "punctuation"
alias: 'punctuation'
}],
'punctuation' : /[,.:()]/
};

View File

@ -28,7 +28,7 @@ Prism.languages.aspnet.tag.pattern = /<(?!%)\/?[^\s>\/]+(?:\s+[^\s>\/=]+(?:=(?:(
// match directives of attribute value foo="<% Bar %>"
Prism.languages.insertBefore('inside', 'punctuation', {
'directive': Prism.languages.aspnet['directive']
}, Prism.languages.aspnet.tag.inside["attr-value"]);
}, Prism.languages.aspnet.tag.inside['attr-value']);
Prism.languages.insertBefore('aspnet', 'comment', {
'asp-comment': {

View File

@ -1,5 +1,5 @@
Prism.languages.autoit = {
"comment": [
'comment': [
/;.*/,
{
// The multi-line comments delimiters can actually be commented out with ";"
@ -7,28 +7,28 @@ Prism.languages.autoit = {
lookbehind: true
}
],
"url": {
'url': {
pattern: /(^\s*#include\s+)(?:<[^\r\n>]+>|"[^\r\n"]+")/m,
lookbehind: true
},
"string": {
'string': {
pattern: /(["'])(?:\1\1|(?!\1)[^\r\n])*\1/,
greedy: true,
inside: {
"variable": /([%$@])\w+\1/
'variable': /([%$@])\w+\1/
}
},
"directive": {
'directive': {
pattern: /(^\s*)#\w+/m,
lookbehind: true,
alias: 'keyword'
},
"function": /\b\w+(?=\()/,
'function': /\b\w+(?=\()/,
// Variables and macros
"variable": /[$@]\w+/,
"keyword": /\b(?:Case|Const|Continue(?:Case|Loop)|Default|Dim|Do|Else(?:If)?|End(?:Func|If|Select|Switch|With)|Enum|Exit(?:Loop)?|For|Func|Global|If|In|Local|Next|Null|ReDim|Select|Static|Step|Switch|Then|To|Until|Volatile|WEnd|While|With)\b/i,
"number": /\b(?:0x[\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b/i,
"boolean": /\b(?:True|False)\b/i,
"operator": /<[=>]?|[-+*\/=&>]=?|[?^]|\b(?:And|Or|Not)\b/i,
"punctuation": /[\[\]().,:]/
'variable': /[$@]\w+/,
'keyword': /\b(?:Case|Const|Continue(?:Case|Loop)|Default|Dim|Do|Else(?:If)?|End(?:Func|If|Select|Switch|With)|Enum|Exit(?:Loop)?|For|Func|Global|If|In|Local|Next|Null|ReDim|Select|Static|Step|Switch|Then|To|Until|Volatile|WEnd|While|With)\b/i,
'number': /\b(?:0x[\da-f]+|\d+(?:\.\d+)?(?:e[+-]?\d+)?)\b/i,
'boolean': /\b(?:True|False)\b/i,
'operator': /<[=>]?|[-+*\/=&>]=?|[?^]|\b(?:And|Or|Not)\b/i,
'punctuation': /[\[\]().,:]/
};

View File

@ -15,7 +15,7 @@
var insideString = {
'bash': commandAfterHeredoc,
'environment': {
pattern: RegExp("\\$" + envVars),
pattern: RegExp('\\$' + envVars),
alias: 'constant'
},
'variable': [
@ -55,7 +55,7 @@
'operator': /:[-=?+]?|[!\/]|##?|%%?|\^\^?|,,?/,
'punctuation': /[\[\]]/,
'environment': {
pattern: RegExp("(\\{)" + envVars),
pattern: RegExp('(\\{)' + envVars),
lookbehind: true,
alias: 'constant'
}
@ -105,7 +105,7 @@
pattern: /(^|[\s;|&]|[<>]\()\w+(?=\+?=)/,
inside: {
'environment': {
pattern: RegExp("(^|[\\s;|&]|[<>]\\()" + envVars),
pattern: RegExp('(^|[\\s;|&]|[<>]\\()' + envVars),
lookbehind: true,
alias: 'constant'
}
@ -155,7 +155,7 @@
}
],
'environment': {
pattern: RegExp("\\$?" + envVars),
pattern: RegExp('\\$?' + envVars),
alias: 'constant'
},
'variable': insideString.variable,

View File

@ -35,8 +35,8 @@
if (!/^\w+$/.test(name)) { // "deleted-sign" -> "deleted"
alias.push(/\w+/.exec(name)[0]);
}
if (name === "diff") {
alias.push("bold");
if (name === 'diff') {
alias.push('bold');
}
Prism.languages.diff[name] = {

View File

@ -2,7 +2,7 @@ Prism.languages.jexl = {
'string': /(["'])(?:\\[\s\S]|(?!\1)[^\\])*\1/,
'transform': {
pattern: /(\|\s*)[a-zA-Zа-яА-Я_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF$][a-zA-Zа-яА-Я0-9_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF$]*/,
alias: "function",
alias: 'function',
lookbehind: true
},
'function': /[a-zA-Zа-яА-Я_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF$][a-zA-Zа-яА-Я0-9_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF$]*\s*(?=\()/,

View File

@ -20,7 +20,7 @@
'operator': /\+[+=]?|-[-=>]?|==?=?|!(?:!|==?)?|[\/*%<>]=?|[?:]:?|\.\.|&&|\|\||\b(?:and|inv|or|shl|shr|ushr|xor)\b/
});
delete Prism.languages.kotlin["class-name"];
delete Prism.languages.kotlin['class-name'];
Prism.languages.insertBefore('kotlin', 'string', {
'raw-string': {

View File

@ -39,7 +39,7 @@ Prism.languages.insertBefore('less', 'property', {
{
pattern: /@[\w-]+\s*:/,
inside: {
"punctuation": /:/
'punctuation': /:/
}
},

View File

@ -122,7 +122,7 @@
/** @type {(Token | string)[]} */
var tokens = env.tokens;
tokens.forEach(function (token) {
if (typeof token !== "string" && token.type === 'generic-text') {
if (typeof token !== 'string' && token.type === 'generic-text') {
var content = getTextContent(token);
if (!isBracketsBalanced(content)) {
token.type = 'bad-line';
@ -137,7 +137,7 @@
* @returns {boolean}
*/
function isBracketsBalanced(input) {
var brackets = "[]{}";
var brackets = '[]{}';
var stack = [];
for (var i = 0; i < input.length; i++) {
var bracket = input[i];

View File

@ -55,7 +55,7 @@
return accum;
}, {});
pascaligo["class-name"].forEach(function (p) {
pascaligo['class-name'].forEach(function (p) {
p.inside = classNameInside;
});

View File

@ -8,7 +8,7 @@ Prism.languages.peoplecode = {
/<\*(?:[^<*]|\*(?!>)|<(?!\*)|<\*(?:(?!\*>)[\s\S])*\*>)*\*>/.source,
// /+ +/ comments
/\/\+[\s\S]*?\+\//.source,
].join("|")),
].join('|')),
'string': {
pattern: /'(?:''|[^'\r\n])*'(?!')|"(?:""|[^"\r\n])*"(?!")/,
greedy: true

View File

@ -37,11 +37,11 @@
// Value is made optional because it may have already been tokenized
pattern: /\w+\s*=\s*(?:(?!\d)\w+)?/,
inside: {
"variable": {
'variable': {
pattern: /(=\s*)(?!\d)\w+/,
lookbehind: true
},
"operator": /=/
'operator': /=/
}
},
'punctuation': [

View File

@ -1,4 +1,4 @@
Prism.languages.vbnet = Prism.languages.extend("basic", {
Prism.languages.vbnet = Prism.languages.extend('basic', {
'comment': [
{
pattern: /(?:!|REM\b).+/i,

View File

@ -107,7 +107,7 @@
Prism.languages.insertBefore('inside', 'punctuation', {
'variable': Prism.languages.xeora['function-inline'].inside['variable']
}, Prism.languages.xeora["function-block"]);
}, Prism.languages.xeora['function-block']);
Prism.languages.xeoracube = Prism.languages.xeora;

View File

@ -4,7 +4,7 @@
'xquery-comment': {
pattern: /\(:[\s\S]*?:\)/,
greedy: true,
alias: "comment"
alias: 'comment'
},
'string': {
pattern: /(["'])(?:\1\1|(?!\1)[\s\S])*\1/,

View File

@ -56,7 +56,7 @@ const formatBytes = (bytes, decimals = 2) => {
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
const maybePlus = (from, to) => from < to ? "+" : "";
const maybePlus = (from, to) => from < to ? '+' : '';
const absDiff = (from, to) => {
if (from === to) {

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
/**
* @typedef {Object<string, ComponentCategory>} Components

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
const { src, dest } = require('gulp');
@ -230,7 +230,7 @@ async function changes() {
if (change.mode === 'A' && change.file.startsWith('components/prism-')) {
const lang = change.file.match(/prism-([\w-]+)\.js$/)[1];
const entry = languages[lang] || {
title: "REMOVED LANGUAGE " + lang,
title: 'REMOVED LANGUAGE ' + lang,
};
const titles = [entry.title];
if (entry.aliasTitles) {

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
const { src, dest, series } = require('gulp');
const replace = require('gulp-replace');

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
const { src, dest, series, parallel, watch } = require('gulp');
@ -45,7 +45,7 @@ function inlineRegexSource() {
}
return '\\\\' + g1;
} else {
return "[^]";
return '[^]';
}
});
// escape single quotes

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
module.exports = {
componentsFile: 'components.json',

View File

@ -4,6 +4,8 @@
return;
}
/* eslint-disable */
/**
* The dependencies map is built automatically with gulp.
*
@ -240,6 +242,8 @@
"yml": "yaml"
}/*]*/;
/* eslint-enable */
/**
* @typedef LangDataItem
* @property {{ success?: () => void, error?: () => void }[]} callbacks

View File

@ -8,7 +8,7 @@
var PROMPT_CLASS = 'command-line-prompt';
/** @type {(str: string, prefix: string) => boolean} */
var startsWith = "".startsWith
var startsWith = ''.startsWith
? function (s, p) { return s.startsWith(p); }
: function (s, p) { return s.indexOf(p) === 0; };
@ -22,7 +22,7 @@
* @returns {string}
*/
function repeat(str, times) {
var s = "";
var s = '';
for (var i = 0; i < times; i++) {
s += str;
}

View File

@ -31,13 +31,13 @@
/** @param {CopyInfo} copyInfo */
function fallbackCopyTextToClipboard(copyInfo) {
var textArea = document.createElement("textarea");
var textArea = document.createElement('textarea');
textArea.value = copyInfo.getText();
// Avoid scrolling to bottom
textArea.style.top = "0";
textArea.style.left = "0";
textArea.style.position = "fixed";
textArea.style.top = '0';
textArea.style.left = '0';
textArea.style.position = 'fixed';
document.body.appendChild(textArea);
textArea.focus();

View File

@ -5,7 +5,7 @@ if (typeof Prism === 'undefined') {
}
Prism.hooks.add('wrap', function(env) {
if (env.type !== "keyword") {
if (env.type !== 'keyword') {
return;
}
env.classes.push('keyword-' + env.content);

View File

@ -29,7 +29,7 @@
*/
function registerAdapter(adapter, name) {
name = name || adapter.name;
if (typeof adapter === "function" && !getAdapter(adapter) && !getAdapter(name)) {
if (typeof adapter === 'function' && !getAdapter(adapter) && !getAdapter(name)) {
adapters.push({ adapter: adapter, name: name });
}
}
@ -42,14 +42,14 @@
* @returns {Adapter} A registered adapter or `null`.
*/
function getAdapter(adapter) {
if (typeof adapter === "function") {
if (typeof adapter === 'function') {
for (var i = 0, item; item = adapters[i++];) {
if (item.adapter.valueOf() === adapter.valueOf()) {
return item.adapter;
}
}
}
else if (typeof adapter === "string") {
else if (typeof adapter === 'string') {
// eslint-disable-next-line no-redeclare
for (var i = 0, item; item = adapters[i++];) {
if (item.name === adapter) {
@ -66,10 +66,10 @@
* @param {string|Function} adapter The adapter itself or the name of an adapter.
*/
function removeAdapter(adapter) {
if (typeof adapter === "string") {
if (typeof adapter === 'string') {
adapter = getAdapter(adapter);
}
if (typeof adapter === "function") {
if (typeof adapter === 'function') {
var index = adapters.findIndex(function (item) {
return item.adapter === adapter;
});
@ -82,12 +82,12 @@
registerAdapter(function github(rsp) {
if (rsp && rsp.meta && rsp.data) {
if (rsp.meta.status && rsp.meta.status >= 400) {
return "Error: " + (rsp.data.message || rsp.meta.status);
return 'Error: ' + (rsp.data.message || rsp.meta.status);
}
else if (typeof (rsp.data.content) === "string") {
return typeof (atob) === "function"
? atob(rsp.data.content.replace(/\s/g, ""))
: "Your browser cannot decode base64";
else if (typeof (rsp.data.content) === 'string') {
return typeof (atob) === 'function'
? atob(rsp.data.content.replace(/\s/g, ''))
: 'Your browser cannot decode base64';
}
}
return null;
@ -95,11 +95,11 @@
registerAdapter(function gist(rsp, el) {
if (rsp && rsp.meta && rsp.data && rsp.data.files) {
if (rsp.meta.status && rsp.meta.status >= 400) {
return "Error: " + (rsp.data.message || rsp.meta.status);
return 'Error: ' + (rsp.data.message || rsp.meta.status);
}
var files = rsp.data.files;
var filename = el.getAttribute("data-filename");
var filename = el.getAttribute('data-filename');
if (filename == null) {
// Maybe in the future we can somehow render all files
// But the standard <script> include for gists does that nicely already,
@ -115,12 +115,12 @@
if (files[filename] !== undefined) {
return files[filename].content;
}
return "Error: unknown or missing gist file " + filename;
return 'Error: unknown or missing gist file ' + filename;
}
return null;
}, 'gist');
registerAdapter(function bitbucket(rsp) {
if (rsp && rsp.node && typeof (rsp.data) === "string") {
if (rsp && rsp.node && typeof (rsp.data) === 'string') {
return rsp.data;
}
return null;

View File

@ -40,7 +40,7 @@ NormalizeWhitespace.prototype = {
for (var name in settings) {
var methodName = toCamelCase(name);
if (name !== "normalize" && methodName !== 'setDefaults' &&
if (name !== 'normalize' && methodName !== 'setDefaults' &&
settings[name] && this[methodName]) {
input = this[methodName].call(this, input, settings[name]);
}
@ -172,7 +172,7 @@ Prism.hooks.add('before-sanity-check', function (env) {
if (node == env.element) {
codeFound = true;
} else if (node.nodeName === "#text") {
} else if (node.nodeName === '#text') {
if (codeFound) {
after += node.nodeValue;
} else {

View File

@ -10,6 +10,8 @@
return;
}
/* eslint-disable */
// The languages map is built automatically with gulp
var Languages = /*languages_placeholder[*/{
"none": "Plain text",
@ -236,6 +238,8 @@
"yang": "YANG"
}/*]*/;
/* eslint-enable */
Prism.plugins.toolbar.registerButton('show-language', function (env) {
var pre = env.element.parentNode;
if (!pre || !/pre/i.test(pre.nodeName)) {

View File

@ -1,6 +1,6 @@
"use strict";
'use strict';
const { assert } = require("chai");
const { assert } = require('chai');
const PrismLoader = require('./helper/prism-loader');
const { languages } = require('./../components.json');

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
const { assert } = require('chai');
const PrismLoader = require('../helper/prism-loader');
@ -30,8 +30,8 @@ describe('Greedy matching', function () {
},
code: '// /*\n/* comment */',
expected: [
["comment", "// /*"],
["comment", "/* comment */"]
['comment', '// /*'],
['comment', '/* comment */']
]
});
});
@ -49,9 +49,9 @@ describe('Greedy matching', function () {
},
code: 'foo "bar" \'baz\'',
expected: [
["b", "foo"],
["b", "\"bar\""],
["a", "'baz'"]
['b', 'foo'],
['b', '"bar"'],
['a', "'baz'"]
]
});
});
@ -73,14 +73,14 @@ describe('Greedy matching', function () {
},
code: `<'> '' ''\n<"> "" ""`,
expected: [
["c", "<'>"],
['c', "<'>"],
" '",
["a", "' '"],
['a', "' '"],
"'\n",
["c", "<\">"],
["b", "\"\""],
["b", "\"\""],
['c', '<">'],
['b', '""'],
['b', '""'],
]
});
});
@ -98,9 +98,9 @@ describe('Greedy matching', function () {
},
code: 'bab',
expected: [
["b", "b"],
["a", "a"],
"b"
['b', 'b'],
['a', 'a'],
'b'
]
});
});

View File

@ -283,18 +283,18 @@ describe('components.json', function () {
}
const entryProperties = [
"title",
"description",
"alias",
"aliasTitles",
"owner",
'title',
'description',
'alias',
'aliasTitles',
'owner',
"require",
"optional",
"modify",
'require',
'optional',
'modify',
"noCSS",
"option"
'noCSS',
'option'
];
it('- should be valid', function () {
@ -363,7 +363,7 @@ describe('components.json', function () {
it('- should not have single-element or empty arrays', function () {
/** @type {keyof import("../dependencies").ComponentEntry} */
const properties = ["alias", "optional", "require", "modify"];
const properties = ['alias', 'optional', 'require', 'modify'];
forEachEntry((entry, id) => {
for (const prop of properties) {

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
function testFunction(name, object, tester) {
const func = object[name];
@ -87,7 +87,7 @@ module.exports = (Prism) => {
const oldClone = Prism.util.clone;
Prism.util.clone = obj => {
const clone = oldClone(obj);
if (clone && typeof clone === "object") {
if (clone && typeof clone === 'object') {
Object.defineProperty(clone, '__cloned', { value: true });
}
return clone;
@ -97,7 +97,7 @@ module.exports = (Prism) => {
function extendTest(id, redef) {
let redefStr;
if (Prism.util.type(redef) === 'Object') {
redefStr = "{\n";
redefStr = '{\n';
for (const key in redef) {
const element = redef[key];
let elementStr;
@ -134,7 +134,7 @@ module.exports = (Prism) => {
}
// rest property check
if ("rest" in redef) {
if ('rest' in redef) {
throw new Error(`The redef object is not allowed to contain a "rest" property.` + details);
}

View File

@ -1,8 +1,8 @@
"use strict";
'use strict';
const fs = require("fs");
const components = require("../../components.json");
const getLoader = require("../../dependencies");
const fs = require('fs');
const components = require('../../components.json');
const getLoader = require('../../dependencies');
const languagesCatalog = components.languages;
const coreChecks = require('./checks');
@ -82,7 +82,7 @@ module.exports = {
*/
createEmptyPrism() {
if (!coreSupplierFunction) {
const source = this.loadComponentSource("core");
const source = this.loadComponentSource('core');
// Core exports itself in 2 ways:
// 1) it uses `module.exports = Prism` which what we'll use
// 2) it uses `global.Prism = Prism` which we want to sabotage to prevent leaking
@ -109,7 +109,7 @@ module.exports = {
* @returns {string}
*/
loadComponentSource(name) {
return this.loadFileSource(__dirname + "/../../components/prism-" + name + ".js");
return this.loadFileSource(__dirname + '/../../components/prism-' + name + '.js');
},
/**
@ -122,7 +122,7 @@ module.exports = {
loadFileSource(src) {
let content = fileSourceCache.get(src);
if (content === undefined) {
fileSourceCache.set(src, content = fs.readFileSync(src, "utf8"));
fileSourceCache.set(src, content = fs.readFileSync(src, 'utf8'));
}
return content;
}

View File

@ -1,9 +1,9 @@
"use strict";
'use strict';
const fs = require("fs");
const { assert } = require("chai");
const PrismLoader = require("./prism-loader");
const TokenStreamTransformer = require("./token-stream-transformer");
const fs = require('fs');
const { assert } = require('chai');
const PrismLoader = require('./prism-loader');
const TokenStreamTransformer = require('./token-stream-transformer');
/**
* @typedef {import("./token-stream-transformer").TokenStream} TokenStream
@ -163,19 +163,19 @@ module.exports = {
* @returns {{languages: string[], mainLanguage: string}}
*/
parseLanguageNames(languageIdentifier) {
let languages = languageIdentifier.split("+");
let languages = languageIdentifier.split('+');
let mainLanguage = null;
languages = languages.map(
function (language) {
const pos = language.indexOf("!");
const pos = language.indexOf('!');
if (-1 < pos) {
if (mainLanguage) {
throw "There are multiple main languages defined.";
throw 'There are multiple main languages defined.';
}
mainLanguage = language.replace("!", "");
mainLanguage = language.replace('!', '');
return mainLanguage;
}
@ -209,11 +209,11 @@ module.exports = {
* @property {string} comment
*/
parseTestCaseFile(filePath) {
const testCaseSource = fs.readFileSync(filePath, "utf8");
const testCaseSource = fs.readFileSync(filePath, 'utf8');
const testCaseParts = testCaseSource.split(/^-{10,}[ \t]*$/m);
if (testCaseParts.length > 3) {
throw new Error("Invalid test case format: Too many sections.");
throw new Error('Invalid test case format: Too many sections.');
}
const code = testCaseParts[0].trim();

View File

@ -1,7 +1,7 @@
"use strict";
'use strict';
const fs = require("fs");
const path = require("path");
const fs = require('fs');
const path = require('path');
module.exports = {

View File

@ -185,16 +185,16 @@ function prettyFormat(prettyStream, indentationWidth) {
return g
.map(item => {
if (isToken(item)) {
if (typeof item === "string") {
return ", ".length + JSON.stringify(item).length;
if (typeof item === 'string') {
return ', '.length + JSON.stringify(item).length;
} else {
return ", ".length + JSON.stringify(item).length + " ".length;
return ', '.length + JSON.stringify(item).length + ' '.length;
}
} else {
return 0;
}
})
.reduce((a, b) => a + b, 0) - ", ".length;
.reduce((a, b) => a + b, 0) - ', '.length;
} else {
// we don't really care about the print width of a single-token line
return 1;
@ -433,7 +433,7 @@ function prettyCountTokens(prettyStream, recursive) {
*/
function prettyGlueTogether(prettyStream, prev, next) {
// strings may appear more than once in the stream, so we have to search for tokens.
if (typeof prev !== "string") {
if (typeof prev !== 'string') {
let index = prettyStream.indexOf(prev);
if (index === -1 || prettyStream[index + 1] !== next) {
throw new Error('Cannot glue: At least one of the tokens is not part of the given token stream.');

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
const { assert } = require('chai');
const PrismLoader = require('./helper/prism-loader');
@ -157,7 +157,7 @@ function getOptions(lang) {
* @property {string | Token | (string | Token)[]} content
*/
function isNotBroken(token) {
if (typeof token === "string") {
if (typeof token === 'string') {
return true;
} else if (Array.isArray(token)) {
return token.length === 1 && isNotBroken(token[0]);

View File

@ -1,4 +1,4 @@
"use strict";
'use strict';
const { assert } = require('chai');
const PrismLoader = require('./helper/prism-loader');
@ -231,7 +231,7 @@ function testPatterns(Prism) {
* @returns {boolean}
*/
function underAStar(node) {
if (node.type === "Quantifier" && node.max > 10) {
if (node.type === 'Quantifier' && node.max > 10) {
return true;
} else if (node.parent) {
return underAStar(node.parent);
@ -417,13 +417,13 @@ function testPatterns(Prism) {
function toNFA(element) {
let { expression, maxCharacter } = parser.parseElement(element, {
maxBackreferenceWords: 1000,
backreferences: "disable"
backreferences: 'disable'
});
// try to remove assertions
expression = transform(transformer, expression);
return NFA.fromRegex(expression, { maxCharacter }, { assertions: "disable" });
return NFA.fromRegex(expression, { maxCharacter }, { assertions: 'disable' });
}
/**
@ -470,7 +470,7 @@ function testPatterns(Prism) {
onCapturingGroupLeave: checkDisjointAlternatives,
onGroupLeave: checkDisjointAlternatives,
onAssertionLeave(node) {
if (node.kind === "lookahead" || node.kind === "lookbehind") {
if (node.kind === 'lookahead' || node.kind === 'lookbehind') {
checkDisjointAlternatives(node);
}
},
@ -479,7 +479,7 @@ function testPatterns(Prism) {
if (node.max < 10) {
return; // not a star
}
if (node.element.type !== "CapturingGroup" && node.element.type !== "Group") {
if (node.element.type !== 'CapturingGroup' && node.element.type !== 'Group') {
return; // not a group
}
@ -589,7 +589,7 @@ function testPatterns(Prism) {
+ `\n`
+ `\nFull pattern:`
+ `\n${patternStr}`
+ `\n${indent(rangeHighlight, " ".repeat(rangeOffset))}`
+ `\n${indent(rangeHighlight, ' '.repeat(rangeOffset))}`
+ `\n`
+ `\n` + (fixed ? `Fixed:\n/${fixed.source}/${fixed.flags}` : `Fix not available.`)
);

View File

@ -42,7 +42,7 @@ describe('Prism Keep Markup Plugin', function () {
const afterHighlight = Prism.hooks.all['after-highlight'][0]
const env = {
element: new JSDOM(code).window.document.getElementsByTagName('code')[0],
language: "javascript"
language: 'javascript'
}
beforeHighlight(env)
afterHighlight(env)

View File

@ -1,16 +1,16 @@
// @ts-check
"use strict";
'use strict';
const TestDiscovery = require("./helper/test-discovery");
const TestCase = require("./helper/test-case");
const path = require("path");
const { argv } = require("yargs");
const TestDiscovery = require('./helper/test-discovery');
const TestCase = require('./helper/test-case');
const path = require('path');
const { argv } = require('yargs');
const testSuite =
(argv.language)
? TestDiscovery.loadSomeTests(__dirname + "/languages", argv.language)
? TestDiscovery.loadSomeTests(__dirname + '/languages', argv.language)
// load complete test suite
: TestDiscovery.loadAllTests(__dirname + "/languages");
: TestDiscovery.loadAllTests(__dirname + '/languages');
const insert = !!argv.accept || !!argv.insert;
const update = !!argv.update;
@ -30,7 +30,7 @@ for (const language in testSuite) {
it(" should pass test case '" + fileName + "'", function () {
if (path.extname(filePath) === '.test') {
TestCase.runTestCase(language, filePath, update ? "update" : insert ? "insert" : "none");
TestCase.runTestCase(language, filePath, update ? 'update' : insert ? 'insert' : 'none');
} else {
TestCase.runTestsWithHooks(language, require(filePath));
}

View File

@ -1,36 +1,36 @@
"use strict";
'use strict';
const { assert } = require("chai");
const TokenStreamTransformer = require("./helper/token-stream-transformer");
const TestCase = require("./helper/test-case");
const { assert } = require('chai');
const TokenStreamTransformer = require('./helper/token-stream-transformer');
const TestCase = require('./helper/test-case');
describe("The token stream transformer", function () {
describe('The token stream transformer', function () {
it("should handle all kinds of simple transformations", function () {
it('should handle all kinds of simple transformations', function () {
const tokens = [
{ type: "type", content: "content" },
"string"
{ type: 'type', content: 'content' },
'string'
];
const expected = [
["type", "content"],
"string"
['type', 'content'],
'string'
];
assert.deepEqual(TokenStreamTransformer.simplify(tokens), expected);
});
it("should handle nested structures", function () {
it('should handle nested structures', function () {
const tokens = [
{
type: "type",
type: 'type',
content: [
{
type: "insideType",
type: 'insideType',
content: [
{ type: "insideInsideType", content: "content" }
{ type: 'insideInsideType', content: 'content' }
]
}
]
@ -38,9 +38,9 @@ describe("The token stream transformer", function () {
];
const expected = [
["type", [
["insideType", [
["insideInsideType", "content"]
['type', [
['insideType', [
['insideInsideType', 'content']
]]
]]
];
@ -49,12 +49,12 @@ describe("The token stream transformer", function () {
});
it("should strip empty tokens", function () {
it('should strip empty tokens', function () {
const tokenStream = [
"",
"\r\n",
"\t",
" "
'',
'\r\n',
'\t',
' '
];
const expectedSimplified = [];
@ -63,22 +63,22 @@ describe("The token stream transformer", function () {
});
it("should strip empty token tree branches", function () {
it('should strip empty token tree branches', function () {
const tokenStream = [
{
type: "type",
type: 'type',
content: [
"",
{ type: "nested", content: [""] },
""
'',
{ type: 'nested', content: [''] },
''
]
},
""
''
];
const expectedSimplified = [
["type", [
["nested", []]
['type', [
['nested', []]
]]
];
@ -86,58 +86,58 @@ describe("The token stream transformer", function () {
});
it("should ignore all properties in tokens except value and content", function () {
it('should ignore all properties in tokens except value and content', function () {
const tokenStream = [
{ type: "type", content: "content", alias: "alias" }
{ type: 'type', content: 'content', alias: 'alias' }
];
const expectedSimplified = [
["type", "content"]
['type', 'content']
];
assert.deepEqual(TokenStreamTransformer.simplify(tokenStream), expectedSimplified);
});
});
describe("The language name parsing", function () {
describe('The language name parsing', function () {
it("should use the last language as the main language if no language is specified", function () {
it('should use the last language as the main language if no language is specified', function () {
assert.deepEqual(
TestCase.parseLanguageNames("a"),
TestCase.parseLanguageNames('a'),
{
languages: ["a"],
mainLanguage: "a"
languages: ['a'],
mainLanguage: 'a'
}
);
assert.deepEqual(
TestCase.parseLanguageNames("a+b+c"),
TestCase.parseLanguageNames('a+b+c'),
{
languages: ["a", "b", "c"],
mainLanguage: "c"
languages: ['a', 'b', 'c'],
mainLanguage: 'c'
}
);
});
it("should use the specified language as main language", function () {
it('should use the specified language as main language', function () {
assert.deepEqual(
TestCase.parseLanguageNames("a+b!+c"),
TestCase.parseLanguageNames('a+b!+c'),
{
languages: ["a", "b", "c"],
mainLanguage: "b"
languages: ['a', 'b', 'c'],
mainLanguage: 'b'
}
);
});
it("should throw an error if there are multiple main languages", function () {
it('should throw an error if there are multiple main languages', function () {
assert.throw(
() => {
TestCase.parseLanguageNames("a+b!+c!");
TestCase.parseLanguageNames('a+b!+c!');
},
"There are multiple main languages defined."
'There are multiple main languages defined.'
);
});
});