├── test ├── fixture │ ├── test.styl │ ├── test1.css │ ├── variables.scss │ ├── test.less │ ├── test.ts │ ├── test.scss │ ├── test.js │ └── test.css ├── extension.test.js └── index.js ├── .editorconfig ├── .gitignore ├── images └── preview.png ├── .vscodeignore ├── .babelrc ├── .vscode ├── settings.json ├── extensions.json ├── tasks.json └── launch.json ├── jsconfig.json ├── src ├── lib │ ├── sass-importer.js │ ├── decoration-map.js │ └── dynamic-contrast.js ├── strategies │ ├── hsla.js │ ├── hwb.js │ ├── rgbWithoutFunction.js │ ├── words.js │ ├── hslWithoutFunction.js │ ├── functions.js │ ├── css-vars.js │ ├── less-vars.js │ ├── styl-vars.js │ ├── scss-vars.js │ └── hex.js ├── main.js └── color-highlight.js ├── .eslintrc.json ├── README.md ├── webpack.config.js ├── CHANGELOG.md ├── package.json └── LICENSE /test/fixture/test.styl: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = space 5 | indent_size = 2 -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .DS_Store 3 | .vscode-test 4 | *.vsix 5 | /dist 6 | -------------------------------------------------------------------------------- /images/preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/enyancc/vscode-ext-color-highlight/HEAD/images/preview.png -------------------------------------------------------------------------------- /test/fixture/test1.css: -------------------------------------------------------------------------------- 1 | .red #fff .test { color: rgb(255, 255, 0); } 2 | .test2 { color: rgb(255, 179, 0); } 3 | -------------------------------------------------------------------------------- /test/fixture/variables.scss: -------------------------------------------------------------------------------- 1 | 2 | $gray: #aaaaaa; 3 | $gray1: #808080; 4 | $gray2: #4a4a4a; 5 | $gray3: #333333; 6 | -------------------------------------------------------------------------------- /test/fixture/test.less: -------------------------------------------------------------------------------- 1 | @base: #f938ab; 2 | 3 | .light-purple { /* I’m light-purple! */ 4 | color: #f938ab; 5 | } 6 | -------------------------------------------------------------------------------- /.vscodeignore: -------------------------------------------------------------------------------- 1 | .vscode/** 2 | .vscode-test/** 3 | test/** 4 | .gitignore 5 | jsconfig.json 6 | vsc-extension-quickstart.md 7 | .eslintrc 8 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "targets": "defaults" 7 | } 8 | ] 9 | ] 10 | } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "editor.tabSize": 2, 4 | "color-highlight.enable": true, 5 | "eslint.enable": true, 6 | } 7 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See https://go.microsoft.com/fwlink/?LinkId=733558 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "dbaeumer.vscode-eslint" 6 | ] 7 | } -------------------------------------------------------------------------------- /test/fixture/test.ts: -------------------------------------------------------------------------------- 1 | // #f00 2 | // #ff0000 3 | // 0xf00 4 | // 0xff0000 5 | // rgb(255, 0, 0) 6 | // rgb(100%, 0%, 0%) 7 | // rgba(255, 0, 0, 1) 8 | // rgba(100%, 0%, 0%, 1) 9 | // hwb(360, 0%, 0%) 10 | // hwb(360, 0%, 0%, 1) 11 | -------------------------------------------------------------------------------- /jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "es6", 5 | "lib": [ 6 | "es6" 7 | ] 8 | }, 9 | "exclude": [ 10 | "node_modules" 11 | ] 12 | } -------------------------------------------------------------------------------- /test/fixture/test.scss: -------------------------------------------------------------------------------- 1 | @import './variables.scss'; 2 | 3 | .gray { 4 | color: $gray; 5 | } 6 | 7 | .gray1 { 8 | color: $gray1; 9 | } 10 | 11 | .gray2 { 12 | color: $gray2; 13 | } 14 | 15 | .gray3 { 16 | color: $gray3; 17 | } 18 | -------------------------------------------------------------------------------- /test/fixture/test.js: -------------------------------------------------------------------------------- 1 | // #f00 2 | // #ff0000 3 | // 0xf00 4 | // 0xff0000 5 | // 0xffff0000 6 | // rgb(255, 0, 0) 7 | // rgb(100%, 0%, 0%) 8 | // rgba(255, 0, 0, 1) 9 | // rgba(100%, 0%, 0%, 1) 10 | // rgba(255 0 0 / 100%) 11 | // hwb(360, 0%, 0%) 12 | // hwb(360, 0%, 0%, 1) 13 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2.0.0", 3 | "tasks": [ 4 | { 5 | "type": "npm", 6 | "script": "build", 7 | "problemMatcher": [], 8 | "label": "npm: build", 9 | "detail": "webpack", 10 | "group": { 11 | "kind": "build", 12 | "isDefault": true 13 | } 14 | } 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /src/lib/sass-importer.js: -------------------------------------------------------------------------------- 1 | import fileImporter from 'file-importer'; 2 | 3 | export function parseImports(options) { 4 | return new Promise((resolve, reject) => { 5 | fileImporter.parse(options, (err, data) => { 6 | if (err) { 7 | return reject(err); 8 | } 9 | 10 | return resolve(data); 11 | }); 12 | }); 13 | } 14 | -------------------------------------------------------------------------------- /test/fixture/test.css: -------------------------------------------------------------------------------- 1 | @root { 2 | --test-color: #FFFF00; 3 | } 4 | 5 | .red { color: #d51f1faa; } 6 | .red { color: #7b1f1fb2; } 7 | .red { color: #9d2727e5; } 8 | .red { color: rgb(255, 0, 0); } 9 | .red { color: rgb(100%, 0%, 0%); } 10 | .red { color: rgba(255, 0, 0, 1); } 11 | .red { color: rgb(133, 52, 52); } 12 | .red { color: rgba(255 0 0 / 100%); } 13 | .red { color: hsla(0, 100%, 50%, 1); } 14 | .red { color: hwb(360, 0%, 0%); } 15 | .red { color: hwb(360, 0%, 0%, 1); } 16 | 17 | .test-color { 18 | color: var(--test-color); 19 | background-color: oklch(40.1% 0.123 21.57); 20 | border-color: lch(40.1% 0.123 21.57); 21 | } 22 | 23 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@babel/eslint-parser", 3 | "env": { 4 | "browser": false, 5 | "commonjs": true, 6 | "es6": true, 7 | "node": true 8 | }, 9 | "parserOptions": { 10 | "sourceType": "module", 11 | "allowImportExportEverywhere": false, 12 | "codeFrame": false 13 | }, 14 | "rules": { 15 | "no-const-assign": "warn", 16 | "no-this-before-super": "warn", 17 | "no-undef": "warn", 18 | "no-unreachable": "warn", 19 | "no-unused-vars": "warn", 20 | "constructor-super": "warn", 21 | "valid-typeof": "warn", 22 | "semi": "warn", 23 | "quotes": ["warn", "single"] 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /src/strategies/hsla.js: -------------------------------------------------------------------------------- 1 | const colorHsla = /(hsla?\([\d]{1,3},\s*[\d]{1,3}%,\s*[\d]{1,3}%(,\s*\d?\.?\d+)?\))/gi; 2 | 3 | /** 4 | * @export 5 | * @param {string} text 6 | * @returns {{ 7 | * start: number, 8 | * end: number, 9 | * color: string 10 | * }} 11 | */ 12 | export async function findHsla(text) { 13 | let match = colorHsla.exec(text); 14 | let result = []; 15 | 16 | while (match !== null) { 17 | const start = match.index; 18 | const end = colorHsla.lastIndex; 19 | const color = match[0]; 20 | 21 | result.push({ 22 | start, 23 | end, 24 | color 25 | }); 26 | 27 | match = colorHsla.exec(text); 28 | } 29 | 30 | return result; 31 | } -------------------------------------------------------------------------------- /test/extension.test.js: -------------------------------------------------------------------------------- 1 | /* global suite, test */ 2 | 3 | // 4 | // Note: This example test is leveraging the Mocha test framework. 5 | // Please refer to their documentation on https://mochajs.org/ for help. 6 | // 7 | 8 | // The module 'assert' provides assertion methods from node 9 | import { equal } from 'assert'; 10 | 11 | // You can import and use all API from the 'vscode' module 12 | // as well as import your extension to test it 13 | import vscode from 'vscode'; 14 | import myExtension from '../extension'; 15 | 16 | // Defines a Mocha test suite to group tests of similar kind together 17 | suite('Extension Tests', function () { 18 | 19 | // Defines a Mocha unit test 20 | test('Something 1', function () { 21 | equal(-1, [1, 2, 3].indexOf(5)); 22 | equal(-1, [1, 2, 3].indexOf(0)); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /src/strategies/hwb.js: -------------------------------------------------------------------------------- 1 | import Color from 'color'; 2 | 3 | const colorHwb = /((hwb)\(\d+,\s*(100|0*\d{1,2})%,\s*(100|0*\d{1,2})%(,\s*0?\.?\d+)?\))/gi; 4 | 5 | /** 6 | * @export 7 | * @param {string} text 8 | * @returns {{ 9 | * start: number, 10 | * end: number, 11 | * color: string 12 | * }} 13 | */ 14 | export async function findHwb(text) { 15 | let match = colorHwb.exec(text); 16 | let result = []; 17 | 18 | while (match !== null) { 19 | const start = match.index; 20 | const end = colorHwb.lastIndex; 21 | const matchedColor = match[0]; 22 | 23 | try { 24 | const color = Color(matchedColor) 25 | .rgb() 26 | .string(); 27 | 28 | result.push({ 29 | start, 30 | end, 31 | color 32 | }); 33 | } catch (e) { } 34 | 35 | match = colorHwb.exec(text); 36 | } 37 | 38 | return result; 39 | } 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [vscode-ext-color-highlight](https://github.com/naumovs/vscode-ext-color-highlight) 2 | 3 | This extension styles css/web colors found in your document. 4 | 5 | ## Install 6 | 7 | In VSC press Ctrl+Shift+P (Cmd+Shift+P on Mac) then type ">ext install", hit enter, search "Color Highlight". 8 | 9 | Still confused? Click "Get Started" above. 10 | 11 | ## Questionnaire 12 | 13 | Please answer the questions in this questionnaire. Your feedback is very valuable and will help me improve this extension. 14 | [https://goo.gl/forms/5emac4WyQv7CWZOK2](https://goo.gl/forms/5emac4WyQv7CWZOK2) 15 | 16 | ## Contributors 17 | 18 | - [chadgauth](https://github.com/chadgauth) - Support for LCH color format 19 | - [LucasMatuszewski](https://github.com/LucasMatuszewski) - Support for floating-point numbers in hsl and rgb 20 | - [lochstar](https://github.com/lochstar) - Styling modes for the marker 21 | 22 | Feel free to contribute! 23 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | // A launch configuration that launches the extension inside a new window 2 | { 3 | "version": "0.1.0", 4 | "configurations": [ 5 | { 6 | "name": "Launch Extension", 7 | "type": "extensionHost", 8 | "request": "launch", 9 | "runtimeExecutable": "${execPath}", 10 | "sourceMaps": true, 11 | "args": ["--extensionDevelopmentPath=${workspaceRoot}"], 12 | "stopOnEntry": false, 13 | "preLaunchTask": "npm: build", 14 | "env": { 15 | "COLOR_HIGHLIGHT_DEBUG": "true" 16 | } 17 | }, 18 | 19 | { 20 | "name": "Launch Tests", 21 | "type": "extensionHost", 22 | "request": "launch", 23 | "runtimeExecutable": "${execPath}", 24 | "args": [ 25 | "--extensionDevelopmentPath=${workspaceRoot}", 26 | "--extensionTestsPath=${workspaceRoot}/test" 27 | ], 28 | "stopOnEntry": false 29 | } 30 | ] 31 | } 32 | -------------------------------------------------------------------------------- /test/index.js: -------------------------------------------------------------------------------- 1 | // 2 | // PLEASE DO NOT MODIFY / DELETE UNLESS YOU KNOW WHAT YOU ARE DOING 3 | // 4 | // This file is providing the test runner to use when running extension tests. 5 | // By default the test runner in use is Mocha based. 6 | // 7 | // You can provide your own test runner if you want to override it by exporting 8 | // a function run(testRoot: string, clb: (error:Error) => void) that the extension 9 | // host can call to run the tests. The test runner is expected to use console.log 10 | // to report the results back to the caller. When the tests are finished, return 11 | // a possible error to the callback or null if none. 12 | 13 | import testRunner from 'vscode/lib/testrunner'; 14 | 15 | // You can directly control Mocha options by uncommenting the following lines 16 | // See https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically#set-options for more info 17 | testRunner.configure({ 18 | ui: 'tdd', // the TDD UI is being used in extension.test.js (suite, test, etc.) 19 | useColors: true // colored output from test results 20 | }); 21 | 22 | export default testRunner; 23 | -------------------------------------------------------------------------------- /src/strategies/rgbWithoutFunction.js: -------------------------------------------------------------------------------- 1 | import Color from 'color'; 2 | 3 | // Using [^\S\n] to avoid matching colors between lines. Using (?:;| |$) to avoid double matching with rgb() function 4 | const colorRgb = /([.\d]{1,5})[^\S\n]*(?[^\S\n]|,)[^\S\n]*([.\d]{1,5})[^\S\n]*\k[^\S\n]*([.\d]{1,5})(?:;| |$)/g; 5 | 6 | /** 7 | * @export 8 | * @param {string} text 9 | * @returns {{ 10 | * start: number, 11 | * end: number, 12 | * color: string 13 | * }} 14 | */ 15 | export async function findRgbNoFn(text) { 16 | let match = colorRgb.exec(text); 17 | let result = []; 18 | 19 | while (match !== null) { 20 | const [matchedColor, red, , green, blue] = match; 21 | const start = match.index + (match[0].length - matchedColor.length); 22 | const end = colorRgb.lastIndex; 23 | 24 | try { 25 | const color = Color.rgb( 26 | parseInt(red), 27 | parseInt(green), 28 | parseInt(blue) 29 | ).string(); 30 | 31 | result.push({ 32 | start, 33 | end, 34 | color 35 | }); 36 | } catch (e) { 37 | console.error(e); 38 | } 39 | 40 | match = colorRgb.exec(text); 41 | } 42 | 43 | return result; 44 | } 45 | -------------------------------------------------------------------------------- /src/strategies/words.js: -------------------------------------------------------------------------------- 1 | import Color from 'color'; 2 | import webColors from 'color-name'; 3 | 4 | const preparedRePart = Object.keys(webColors) 5 | .map(color => `\\b${color}\\b`) 6 | .join('|'); 7 | 8 | const colorWeb = new RegExp('.?(' + preparedRePart + ')(?!-)', 'g'); 9 | 10 | /** 11 | * @export 12 | * @param {string} text 13 | * @returns {{ 14 | * start: number, 15 | * end: number, 16 | * color: string 17 | * }} 18 | */ 19 | export async function findWords(text) { 20 | let match = colorWeb.exec(text); 21 | let result = []; 22 | 23 | while (match !== null) { 24 | const firstChar = match[0][0]; 25 | const matchedColor = match[1]; 26 | const start = match.index + (match[0].length - matchedColor.length); 27 | const end = colorWeb.lastIndex; 28 | 29 | if (firstChar.length && /[-\\$@#]/.test(firstChar)) { 30 | match = colorWeb.exec(text); 31 | continue; 32 | } 33 | 34 | try { 35 | const color = Color(matchedColor) 36 | .rgb() 37 | .string(); 38 | 39 | result.push({ 40 | start, 41 | end, 42 | color 43 | }); 44 | } catch (e) { } 45 | 46 | match = colorWeb.exec(text); 47 | } 48 | 49 | return result; 50 | } 51 | -------------------------------------------------------------------------------- /src/strategies/hslWithoutFunction.js: -------------------------------------------------------------------------------- 1 | import Color from 'color'; 2 | 3 | // Using [^\S\n] to avoid matching colors between lines. Using (?:;| |$) to avoid double matching with rgb() function 4 | const colorHsl = 5 | /([.\d]{1,5})[^\S\n]*(?[^\S\n]|,)[^\S\n]*([.\d]{1,5}%)[^\S\n]*\k[^\S\n]*([.\d]{1,5}%)(?:;| |$)/g; 6 | 7 | /** 8 | * @export 9 | * @param {string} text 10 | * @returns {{ 11 | * start: number, 12 | * end: number, 13 | * color: string 14 | * }} 15 | */ 16 | export async function findHslNoFn(text) { 17 | let match = colorHsl.exec(text); 18 | let result = []; 19 | 20 | while (match !== null) { 21 | const [matchedColor, hue, , saturation, lightness] = match; 22 | const start = match.index + (match[0].length - matchedColor.length); 23 | const end = colorHsl.lastIndex; 24 | 25 | try { 26 | const color = Color.hsl( 27 | parseInt(hue), 28 | parseInt(saturation), 29 | parseInt(lightness) 30 | ).string(); 31 | 32 | result.push({ 33 | start, 34 | end, 35 | color, 36 | }); 37 | } catch (e) { 38 | console.error(e); 39 | } 40 | 41 | match = colorHsl.exec(text); 42 | } 43 | 44 | return result; 45 | } 46 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const baseConfig = { 2 | entry: './src/main.js', 3 | externals: { 4 | 'vscode': 'vscode' 5 | }, 6 | module: { 7 | rules: [ 8 | { 9 | test: /\.js$/, 10 | exclude: /(node_modules|bower_components)/, 11 | use: { 12 | loader: 'babel-loader', 13 | options: { 14 | presets: [['@babel/preset-env', { targets: 'defaults' }]], 15 | plugins: ['@babel/transform-runtime'], 16 | } 17 | } 18 | } 19 | ] 20 | } 21 | }; 22 | 23 | const nodeConfig = { 24 | ...baseConfig, 25 | target: 'node', 26 | output: { 27 | libraryTarget: 'commonjs2', 28 | filename: 'extension-node.js', 29 | devtoolModuleFilenameTemplate: '[absolute-resource-path]' 30 | } 31 | }; 32 | 33 | const webConfig = { 34 | ...baseConfig, 35 | target: 'webworker', 36 | output: { 37 | libraryTarget: 'commonjs2', 38 | filename: 'extension-web.js', 39 | devtoolModuleFilenameTemplate: '[absolute-resource-path]' 40 | }, 41 | resolve: { 42 | fallback: { 43 | 'path': require.resolve('path-browserify'), 44 | 'fs': false 45 | } 46 | } 47 | }; 48 | 49 | module.exports = [nodeConfig, webConfig]; 50 | 51 | if (process.env.NODE_ENVIRONMENT !== 'production') { 52 | module.exports.devtool = 'source-map'; 53 | } 54 | -------------------------------------------------------------------------------- /src/strategies/functions.js: -------------------------------------------------------------------------------- 1 | const colorRegex = /((rgb|hsl|lch|oklch)a?\(\s*[\d]*\.?[\d]+%?\s*(?\s|,)\s*[\d]*\.?[\d]+%?\s*\k\s*[\d]*\.?[\d]+%?(\s*(\k|\/)\s*[\d]*\.?[\d]+%?)?\s*\))/gi; 2 | const cssVarRegex = /(--[\w-]+-(rgb|hsl|lch|oklch)):\s*([\d]*\.?[\d]+\s+[\d]*\.?[\d]+\s+[\d]*\.?[\d]+);/gi; 3 | const allowedColorFunctions = ['rgb', 'hsl', 'lch', 'oklch']; 4 | 5 | export async function findColorFunctionsInText(text) { 6 | const colorMatches = [...text.matchAll(colorRegex)]; 7 | const cssVarMatches = [...text.matchAll(cssVarRegex)]; 8 | 9 | return [...colorMatches, ...cssVarMatches].map(createColorFunctionObject); 10 | } 11 | 12 | function createColorFunctionObject(match) { 13 | const start = match.index; 14 | const end = start + match[0].length; 15 | let color = match[0]; 16 | 17 | const cssVarMatchArray = Array.from(color.matchAll(cssVarRegex)); 18 | 19 | if (cssVarMatchArray.length > 0) { 20 | const cssVarMatch = cssVarMatchArray[0]; 21 | const colorFunction = cssVarMatch[2]; 22 | const colorValues = cssVarMatch[3]; 23 | 24 | if (allowedColorFunctions.includes(colorFunction)) { 25 | color = `${colorFunction}(${colorValues})`; 26 | } 27 | } 28 | 29 | return { start, end, color }; 30 | } 31 | 32 | export function sortStringsInDescendingOrder(strings) { 33 | return strings.sort((a, b) => b.localeCompare(a)); 34 | } 35 | -------------------------------------------------------------------------------- /src/strategies/css-vars.js: -------------------------------------------------------------------------------- 1 | import { findHexRGBA } from './hex'; 2 | import { findWords } from './words'; 3 | import { findColorFunctionsInText, sortStringsInDescendingOrder } from './functions'; 4 | import { findHwb } from './hwb'; 5 | 6 | const setVariable = /^\s*(--[-\w]+)\s*:\s*(.*)$/gm; 7 | 8 | /** 9 | * @export 10 | * @param {string} text 11 | * @returns {{ 12 | * start: number, 13 | * end: number, 14 | * color: string 15 | * }} 16 | */ 17 | export async function findCssVars(text) { 18 | let match = setVariable.exec(text); 19 | let result = []; 20 | 21 | const varColor = {}; 22 | let varNames = []; 23 | 24 | while (match !== null) { 25 | const name = match[1]; 26 | const value = match[2]; 27 | const values = await Promise.race([ 28 | findHexRGBA(value), 29 | findWords(value), 30 | findColorFunctionsInText(value), 31 | findHwb(value) 32 | ]); 33 | 34 | if (values.length) { 35 | varNames.push(name); 36 | varColor[name] = values[0].color; 37 | } 38 | 39 | match = setVariable.exec(text); 40 | } 41 | 42 | if (!varNames.length) { 43 | return []; 44 | } 45 | 46 | varNames = sortStringsInDescendingOrder(varNames); 47 | 48 | const varNamesRegex = new RegExp(`var\\((${varNames.join('|')})\\)`, 'g'); 49 | 50 | match = varNamesRegex.exec(text); 51 | 52 | while (match !== null) { 53 | const start = match.index; 54 | const end = varNamesRegex.lastIndex; 55 | const varName = match[1]; 56 | 57 | result.push({ 58 | start, 59 | end, 60 | color: varColor[varName] 61 | }); 62 | 63 | match = varNamesRegex.exec(text); 64 | } 65 | 66 | 67 | return result; 68 | } 69 | -------------------------------------------------------------------------------- /src/strategies/less-vars.js: -------------------------------------------------------------------------------- 1 | import { findHexRGBA } from './hex'; 2 | import { findWords } from './words'; 3 | import { findColorFunctionsInText, sortStringsInDescendingOrder } from './functions'; 4 | import { findHwb } from './hwb'; 5 | 6 | const setVariable = /^\s*\@([-\w]+)\s*:\s*(.*)$/gm; 7 | 8 | /** 9 | * @export 10 | * @param {string} text 11 | * @returns {{ 12 | * start: number, 13 | * end: number, 14 | * color: string 15 | * }} 16 | */ 17 | export async function findLessVars(text) { 18 | let match = setVariable.exec(text); 19 | let result = []; 20 | 21 | const varColor = {}; 22 | let varNames = []; 23 | 24 | while (match !== null) { 25 | const name = match[1]; 26 | const value = match[2]; 27 | const values = await Promise.race([ 28 | findHexRGBA(value), 29 | findWords(value), 30 | findColorFunctionsInText(value), 31 | findHwb(value) 32 | ]); 33 | 34 | if (values.length) { 35 | varNames.push(name); 36 | varColor[name] = values[0].color; 37 | } 38 | 39 | match = setVariable.exec(text); 40 | } 41 | 42 | if (!varNames.length) { 43 | return []; 44 | } 45 | 46 | varNames = sortStringsInDescendingOrder(varNames); 47 | 48 | const varNamesRegex = new RegExp(`\\@(${varNames.join('|')})(?!-|\\s*:)`, 'g'); 49 | 50 | match = varNamesRegex.exec(text); 51 | 52 | while (match !== null) { 53 | const start = match.index; 54 | const end = varNamesRegex.lastIndex; 55 | const varName = match[1]; 56 | 57 | result.push({ 58 | start, 59 | end, 60 | color: varColor[varName] 61 | }); 62 | 63 | match = varNamesRegex.exec(text); 64 | } 65 | 66 | 67 | return result; 68 | } 69 | -------------------------------------------------------------------------------- /src/strategies/styl-vars.js: -------------------------------------------------------------------------------- 1 | import { findHexRGBA } from './hex'; 2 | import { findWords } from './words'; 3 | import { findColorFunctionsInText, sortStringsInDescendingOrder } from './functions'; 4 | import { findHwb } from './hwb'; 5 | 6 | const setVariable = /^\s*\$?([-\w]+)\s*=\s*(.*)$/gm; 7 | 8 | /** 9 | * @export 10 | * @param {string} text 11 | * @returns {{ 12 | * start: number, 13 | * end: number, 14 | * color: string 15 | * }} 16 | */ 17 | export async function findStylVars(text) { 18 | let match = setVariable.exec(text); 19 | let result = []; 20 | 21 | const varColor = {}; 22 | let varNames = []; 23 | 24 | while (match !== null) { 25 | const name = match[1]; 26 | const value = match[2]; 27 | const values = await Promise.race([ 28 | findHexRGBA(value), 29 | findWords(value), 30 | findColorFunctionsInText(value), 31 | findHwb(value) 32 | ]); 33 | 34 | if (values.length) { 35 | varNames.push(name); 36 | varColor[name] = values[0].color; 37 | } 38 | 39 | match = setVariable.exec(text); 40 | } 41 | 42 | if (!varNames.length) { 43 | return []; 44 | } 45 | 46 | varNames = sortStringsInDescendingOrder(varNames); 47 | 48 | const varNamesRegex = new RegExp(`\\$?(${varNames.join('|')})(?!-|\\s*=)`, 'g'); 49 | 50 | match = varNamesRegex.exec(text); 51 | 52 | while (match !== null) { 53 | const start = match.index; 54 | const end = varNamesRegex.lastIndex; 55 | const varName = match[1]; 56 | 57 | result.push({ 58 | start, 59 | end, 60 | color: varColor[varName] 61 | }); 62 | 63 | match = varNamesRegex.exec(text); 64 | } 65 | 66 | 67 | return result; 68 | } 69 | -------------------------------------------------------------------------------- /src/strategies/scss-vars.js: -------------------------------------------------------------------------------- 1 | import { findHexRGBA } from './hex'; 2 | import { findWords } from './words'; 3 | import { findColorFunctionsInText, sortStringsInDescendingOrder } from './functions'; 4 | import { findHwb } from './hwb'; 5 | import { parseImports } from '../lib/sass-importer'; 6 | 7 | const setVariable = /^\s*\$([-\w]+)\s*:\s*(.*)$/gm; 8 | 9 | /** 10 | * @export 11 | * @param {string} text 12 | * @returns {{ 13 | * start: number, 14 | * end: number, 15 | * color: string 16 | * }} 17 | */ 18 | export async function findScssVars(text, importerOptions) { 19 | let textWithImports = text; 20 | 21 | try { 22 | textWithImports = await parseImports(importerOptions); 23 | } catch(err) { 24 | console.log('Error during imports loading, falling back to local variables parsing'); 25 | } 26 | 27 | let match = setVariable.exec(textWithImports); 28 | let result = []; 29 | 30 | const varColor = {}; 31 | let varNames = []; 32 | 33 | while (match !== null) { 34 | const name = match[1]; 35 | const value = match[2]; 36 | const values = await Promise.race([ 37 | findHexRGBA(value), 38 | findWords(value), 39 | findColorFunctionsInText(value), 40 | findHwb(value) 41 | ]); 42 | 43 | if (values.length) { 44 | varNames.push(name); 45 | varColor[name] = values[0].color; 46 | } 47 | 48 | match = setVariable.exec(textWithImports); 49 | } 50 | 51 | if (!varNames.length) { 52 | return []; 53 | } 54 | 55 | varNames = sortStringsInDescendingOrder(varNames); 56 | 57 | const varNamesRegex = new RegExp(`\\$(${varNames.join('|')})(?!-|\\s*:)`, 'g'); 58 | 59 | match = varNamesRegex.exec(text); 60 | 61 | while (match !== null) { 62 | const start = match.index; 63 | const end = varNamesRegex.lastIndex; 64 | const varName = match[1]; 65 | 66 | result.push({ 67 | start, 68 | end, 69 | color: varColor[varName] 70 | }); 71 | 72 | match = varNamesRegex.exec(text); 73 | } 74 | 75 | 76 | return result; 77 | } 78 | -------------------------------------------------------------------------------- /src/strategies/hex.js: -------------------------------------------------------------------------------- 1 | import Color from 'color'; 2 | 3 | const colorHex = 4 | /.?((?:\#|\b0x)([a-f0-9]{6}([a-f0-9]{2})?|[a-f0-9]{3}([a-f0-9]{1})?))\b/gi; 5 | 6 | /** 7 | * @export 8 | * @param {string} text 9 | * @returns {{ 10 | * start: number, 11 | * end: number, 12 | * color: string 13 | * }} 14 | */ 15 | function findHex(text, useARGB) { 16 | let match = colorHex.exec(text); 17 | let result = []; 18 | 19 | while (match !== null) { 20 | const firstChar = match[0][0]; 21 | const matchedColor = match[1]; 22 | const start = match.index + (match[0].length - matchedColor.length); 23 | const end = colorHex.lastIndex; 24 | let matchedHex = '#' + match[2]; 25 | 26 | // Check the symbol before the color match, and try to avoid coloring in the 27 | // contexts that are not relevant 28 | // https://github.com/sergiirocks/vscode-ext-color-highlight/issues/25 29 | if (firstChar.length && /\w/.test(firstChar)) { 30 | match = colorHex.exec(text); 31 | continue; 32 | } 33 | 34 | try { 35 | let color; 36 | if (useARGB == true) { 37 | let alphaInt = 1; 38 | if (match[2].length == 8) { 39 | alphaInt = 40 | Math.round((parseInt(match[2].substring(0, 2), 16) * 100) / 255) / 41 | 100; // Get first 2 characters, convert to decimal 42 | matchedHex = '#' + match[2].substring(2); 43 | } 44 | 45 | color = Color(matchedHex).alpha(alphaInt).rgb().string(); 46 | } else { 47 | color = Color(matchedHex).rgb().string(); 48 | } 49 | 50 | result.push({ 51 | start, 52 | end, 53 | color, 54 | }); 55 | } catch (e) {} 56 | 57 | match = colorHex.exec(text); 58 | } 59 | 60 | return result; 61 | } 62 | 63 | /** 64 | * @export 65 | * @param {string} text 66 | * @returns {{ 67 | * start: number, 68 | * end: number, 69 | * color: string 70 | * }} 71 | */ 72 | export async function findHexARGB(text) { 73 | return findHex(text, true); 74 | } 75 | 76 | /** 77 | * @export 78 | * @param {string} text 79 | * @returns {{ 80 | * start: number, 81 | * end: number, 82 | * color: string 83 | * }} 84 | */ 85 | export async function findHexRGBA(text) { 86 | return findHex(text, false); 87 | } 88 | -------------------------------------------------------------------------------- /src/lib/decoration-map.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | import vscode from 'vscode'; 3 | import { getColorContrast } from './dynamic-contrast'; 4 | 5 | /** 6 | * 7 | * @export 8 | * @class DecorationMap 9 | * 10 | * @property {{ 11 | * markRuler: boolean, 12 | * markerType: string 13 | * }} options 14 | */ 15 | export class DecorationMap { 16 | /** 17 | * Creates an instance of DecorationMap. 18 | * @param {{ 19 | * markRuler: boolean, 20 | * markerType: string 21 | * }} options 22 | * 23 | * @memberOf DecorationMap 24 | */ 25 | constructor(options) { 26 | this.options = Object.assign({}, options); 27 | this._map = new Map(); 28 | this._keys = []; 29 | } 30 | 31 | /** 32 | * @param {string} color 33 | * @returns vscode.TextEditorDecorationType 34 | */ 35 | get(color) { 36 | if (!this._map.has(color)) { 37 | let rules = {}; 38 | if (this.options.markRuler) { 39 | rules = { 40 | overviewRulerColor: color 41 | }; 42 | } 43 | 44 | switch (this.options.markerType) { 45 | case 'outline': 46 | rules.border = `3px solid ${color}`; 47 | break; 48 | case 'foreground': 49 | rules.color = color; 50 | break; 51 | case 'underline': 52 | rules.color = 'invalid; border-bottom:solid 2px ' + color; 53 | break; 54 | case 'dot': 55 | case 'dotafter': 56 | case 'dot-after': 57 | case 'dot_after': 58 | rules.after = { 59 | contentText: ' ', 60 | margin: '0.1em 0.2em 0 0.2em', 61 | width: '0.7em', 62 | height: '0.7em', 63 | backgroundColor: color, 64 | borderRadius: '50%' 65 | }; 66 | break; 67 | case 'dotbefore': 68 | case 'dot-before': 69 | case 'dot_before': 70 | rules.before = { 71 | contentText: ' ', 72 | margin: '0.1em 0.2em 0 0.2em', 73 | width: '0.7em', 74 | height: '0.7em', 75 | backgroundColor: color, 76 | borderRadius: '50%' 77 | }; 78 | break; 79 | case 'background': 80 | default: 81 | rules.backgroundColor = color; 82 | rules.color = getColorContrast(color); 83 | rules.border = `3px solid ${color}`; 84 | rules.borderRadius = '3px'; 85 | } 86 | this._map.set(color, vscode.window.createTextEditorDecorationType(rules)); 87 | this._keys.push(color); 88 | } 89 | return this._map.get(color); 90 | } 91 | 92 | 93 | keys() { 94 | return this._keys.slice(); 95 | } 96 | 97 | dispose() { 98 | this._map.forEach((decoration) => { 99 | decoration.dispose(); 100 | }); 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /src/main.js: -------------------------------------------------------------------------------- 1 | import vscode from 'vscode'; 2 | import { DocumentHighlight } from './color-highlight'; 3 | 4 | const COMMAND_NAME = 'extension.colorHighlight'; 5 | let instanceMap = null; 6 | let config; 7 | 8 | // this method is called when your extension is activated 9 | // your extension is activated the very first time the command is executed 10 | export function activate(context) { 11 | instanceMap = []; 12 | config = vscode.workspace.getConfiguration('color-highlight'); 13 | 14 | context.subscriptions.push( 15 | 16 | // vscode.commands.registerCommand('_' + COMMAND_NAME, doHighlight), 17 | vscode.commands.registerTextEditorCommand(COMMAND_NAME, runHighlightEditorCommand) 18 | 19 | ); 20 | 21 | vscode.window.onDidChangeVisibleTextEditors(onOpenEditor, null, context.subscriptions); 22 | vscode.workspace 23 | .onDidChangeConfiguration(onConfigurationChange, null, context.subscriptions); 24 | 25 | onOpenEditor(vscode.window.visibleTextEditors); 26 | } 27 | 28 | // this method is called when your extension is deactivated 29 | export function deactivate() { 30 | instanceMap.forEach((instance) => instance.dispose()); 31 | instanceMap = null; 32 | } 33 | 34 | function reactivate() { 35 | deactivate(); 36 | 37 | instanceMap = []; 38 | onOpenEditor(vscode.window.visibleTextEditors); 39 | } 40 | 41 | /** 42 | * Checks if the document is applicable for autoHighlighighting 43 | * 44 | * @param {{languages: string[]}} config 45 | * @param {vscode.TextDocument} document 46 | * @returns 47 | */ 48 | function isValidDocument(config, { languageId }) { 49 | let isValid = false; 50 | 51 | if (!config.enable) { 52 | return isValid; 53 | } 54 | 55 | if (config.languages.indexOf('*') > -1) { 56 | isValid = true; 57 | } 58 | 59 | if (config.languages.indexOf(languageId) > -1) { 60 | isValid = true; 61 | } 62 | if (config.languages.indexOf(`!${languageId}`) > -1) { 63 | isValid = false; 64 | } 65 | 66 | return isValid; 67 | } 68 | 69 | /** 70 | * Finds relevant instance of the DocumentHighlighter or creates a new one 71 | * 72 | * @param {vscode.TextDocument} document 73 | * @returns {DocumentHighlight} 74 | */ 75 | async function findOrCreateInstance(document) { 76 | if (!document) { 77 | return; 78 | } 79 | 80 | const found = instanceMap.find(({ document: refDoc }) => refDoc === document); 81 | 82 | if (!found) { 83 | const instance = new DocumentHighlight(document, config); 84 | instanceMap.push(instance); 85 | } 86 | 87 | return found || instanceMap[instanceMap.length - 1]; 88 | } 89 | 90 | async function runHighlightEditorCommand(editor, edit, document) { 91 | if (!document) { 92 | document = editor && editor.document; 93 | } 94 | 95 | return doHighlight([document]); 96 | } 97 | 98 | async function doHighlight(documents = []) { 99 | if (documents.length) { 100 | const instances = await Promise.all(documents.map(findOrCreateInstance)); 101 | 102 | return instances.map(instance => instance.onUpdate()); 103 | } 104 | } 105 | 106 | function onConfigurationChange() { 107 | config = vscode.workspace.getConfiguration('color-highlight'); 108 | 109 | reactivate(); 110 | } 111 | 112 | /** 113 | * 114 | * @param {vscode.TextEditor[]} editors 115 | */ 116 | function onOpenEditor(editors) { 117 | // dispose all inactive editors 118 | const documents = editors.map(({ document }) => document); 119 | const forDisposal = instanceMap.filter(({ document }) => documents.indexOf(document) === -1); 120 | 121 | instanceMap = instanceMap.filter(({ document }) => documents.indexOf(document) > -1); 122 | forDisposal.forEach(instance => instance.dispose()); 123 | 124 | // enable highlight in active editors 125 | const validDocuments = documents.filter(doc => isValidDocument(config, doc)); 126 | 127 | doHighlight(validDocuments); 128 | } 129 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | # Change Log 3 | 4 | ## [Unreleased] 5 | 6 | ## [2.8.0] 7 | 8 | - Support for LCH color format 9 | - Variable syntax support when the variable defines the color (e.g., --variable-lch, rgb, oklch, etc.) 10 | 11 | ## [2.7.1] 12 | 13 | - Updated node dependencies. 14 | 15 | ## [2.7.0] 16 | 17 | ### Added 18 | 19 | - Support for HSL format without `hsl()` and configuration options for it (Disabled by default) 20 | - Support for floating-point numbers in hsl and rgb (like `343.2 15.4% 34.4%` or `rgb(100.4, 89.4%, 66.4%)`) - it's quite common in Tailwind 21 | 22 | ### Fixed 23 | - Fix double highlighting for function `rgb()` when `rgbWithNoFunction` is enabled 24 | 25 | ## [2.6.0] 26 | 27 | ### Added 28 | 29 | - Support for css color module level 4 30 | - "useARGB" option to toggle between RGBA and ARGB hex formats 31 | 32 | ## [2.5.0] - 2021-09-13 33 | 34 | ### Added 35 | 36 | - Build for the web 37 | 38 | ## [2.4.0] - 2021-07-15 39 | 40 | ### Added 41 | 42 | - Workspace Trust support (Supported completely in untrusted workspaces) 43 | - Support for whitespace format 44 | - Support for RGB format without rgb() and configuration options for it (Disabled by default) 45 | - License 46 | 47 | ### Changed 48 | 49 | - Configuration option for marker type is now a list of options 50 | 51 | ### Fixed 52 | 53 | - Fixed contrast ratio computation to follow WCAG 2.0 guidelines 54 | 55 | ## [2.3.0] - 2017-07-11 56 | 57 | ### Added 58 | 59 | - Highlight variables imported from the files (sass, scss) 60 | - Configuration option for the sass imports lookup folders 61 | 62 | ## [2.2.0] - 2017-05-15 63 | 64 | ### Added 65 | 66 | - "dot-before" marker type 67 | 68 | ## [2.1.3] - 2017-04-20 69 | 70 | ### Added 71 | 72 | - Google form to collect the user preffered setting defaults 73 | 74 | ### Fixed 75 | 76 | - Underline style: correct text color in comments 77 | 78 | ## [2.1.2] - 2017-04-18 79 | 80 | ### Fixed 81 | 82 | - Correct the highlighted offset if context is analyzed 83 | 84 | ## [2.1.1] - 2017-04-18 85 | 86 | ### Fixed 87 | 88 | - Partial variable matching in sass, less and stylus 89 | 90 | ## [2.1.0] - 2017-04-18 91 | 92 | ### Added 93 | 94 | - hsl() and hsla() support 95 | - Description for the configuration properties 96 | - Basic variables support within the file (for css, sass, less, stylus) 97 | 98 | ### Fixed 99 | 100 | - Matches in non-color contexts like link with hashes or other places 101 | - White in white-space is colored 102 | 103 | ### Changed 104 | 105 | - Color word matching is always "on" in the style languages (css, less, scss, sass, stylus) 106 | 107 | ## [2.0.1] - 2017-04-12 108 | 109 | ### Changed 110 | 111 | - Default value for matchWords to false 112 | 113 | ## [2.0.0] - 2017-04-12 114 | 115 | ### Added 116 | 117 | - Document type filters 118 | - Two new styles for color highlight: "dot" and "foreground" 119 | - Moved list of changes to the CHANGELOG.md file 120 | 121 | ### Changed 122 | 123 | - Extension enabled on all documents 124 | - Complete rewrite to gain maximum performance 125 | - Updated to the latest vscode library 126 | 127 | ## [1.3.2] - 0000-00-00 128 | 129 | - Feat: Add stylus 130 | 131 | ## [1.3.1] - 0000-00-00 132 | 133 | - Feat: Add typescript language to the list 134 | - Feat: Add option to disable the colors in ruler 135 | 136 | ## [1.3.0] - 0000-00-00 137 | 138 | - Feat: Support hex alpha 139 | - Fix: Accidental highlighting of strings like "#1234567890" 140 | - Fix: Highlights non-color array keys in Drupal PHP code 141 | 142 | ## [1.2.1] - 0000-00-00 143 | 144 | - Added new option to disable color words highlight 145 | 146 | ## [1.2] - 0000-00-00 147 | 148 | - New styling modes for the marker: background, underline. Default is "background" now 149 | 150 | ## [1.1] - 0000-00-00 151 | 152 | - Refactored code to prevent memory leaks 153 | - Added configuration for the extension 154 | - Added command highlight current file (if it's not configured to be highlighted automatically) 155 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "color-highlight", 3 | "displayName": "Color Highlight", 4 | "description": "Highlight web colors in your editor", 5 | "version": "2.8.0", 6 | "publisher": "naumovs", 7 | "license": "GPL-3.0", 8 | "engines": { 9 | "vscode": "^1.57.0" 10 | }, 11 | "categories": [ 12 | "Other" 13 | ], 14 | "activationEvents": [ 15 | "onStartupFinished" 16 | ], 17 | "capabilities": { 18 | "untrustedWorkspaces": { 19 | "supported": true 20 | } 21 | }, 22 | "scripts": { 23 | "build": "webpack --mode development", 24 | "vscode:prepublish": "webpack --mode production", 25 | "dev": "webpack --mode development -w", 26 | "postinstall": "node ./node_modules/vscode/bin/install", 27 | "force-resolutions": "npx npm-force-resolutions", 28 | "test": "node ./node_modules/vscode/bin/test" 29 | }, 30 | "bugs": { 31 | "url": "https://github.com/naumovs/vscode-ext-color-highlight/issues" 32 | }, 33 | "homepage": "https://github.com/naumovs/vscode-ext-color-highlight", 34 | "repository": { 35 | "type": "git", 36 | "url": "https://github.com/naumovs/vscode-ext-color-highlight.git" 37 | }, 38 | "browser": "./dist/extension-web.js", 39 | "main": "./dist/extension-node.js", 40 | "icon": "images/preview.png", 41 | "contributes": { 42 | "configuration": { 43 | "title": "Color Highlight", 44 | "properties": { 45 | "color-highlight.enable": { 46 | "default": true, 47 | "description": "Controls if plugin is enabled", 48 | "type": "boolean" 49 | }, 50 | "color-highlight.languages": { 51 | "default": [ 52 | "*" 53 | ], 54 | "description": "An array of language ids which should be highlighted by Color Highlight. \"*\" to trigger on any language; Prepend language id with \"!\" to exclude the language (i.e \"!typescript\", \"!javascript\")", 55 | "type": "array" 56 | }, 57 | "color-highlight.matchWords": { 58 | "default": false, 59 | "description": "Highlight color words in all files (grey, green, etc.)", 60 | "type": "boolean" 61 | }, 62 | "color-highlight.useARGB": { 63 | "default": false, 64 | "description": "Highlight HEX values using ARGB instead of RGBA (default)", 65 | "type": "boolean" 66 | }, 67 | "color-highlight.matchRgbWithNoFunction": { 68 | "default": false, 69 | "description": "Highlight rgb without functions like rgb() ('255, 255, 255', [255, 255, 255], '255 255 255', etc.)", 70 | "type": "boolean" 71 | }, 72 | "color-highlight.rgbWithNoFunctionLanguages": { 73 | "default": [ 74 | "*" 75 | ], 76 | "description": "An array of language ids which should be highlighted by Color Highlight with the rgbWithNoFunction pattern. \"*\" to trigger on any language; Prepend language id with \"!\" to exclude the language (i.e \"!typescript\", \"!javascript\")", 77 | "type": "array" 78 | }, 79 | "color-highlight.matchHslWithNoFunction": { 80 | "default": false, 81 | "description": "Highlight hsl without functions like hsl() ('255, 100%, 80%', [255, 100%, 80%], '255 100% 80%', etc.)", 82 | "type": "boolean" 83 | }, 84 | "color-highlight.hslWithNoFunctionLanguages": { 85 | "default": [ 86 | "*" 87 | ], 88 | "description": "An array of language ids which should be highlighted by Color Highlight with the rgbWithNoFunction pattern. \"*\" to trigger on any language; Prepend language id with \"!\" to exclude the language (i.e \"!typescript\", \"!javascript\")", 89 | "type": "array" 90 | }, 91 | "color-highlight.markerType": { 92 | "default": "background", 93 | "description": "Style of the highlight. Can be 'dot-before', 'dot-after', 'foreground', 'background', 'outline', 'underline'", 94 | "type": "string", 95 | "enum": [ 96 | "dot-before", 97 | "dot-after", 98 | "foreground", 99 | "background", 100 | "outline", 101 | "underline" 102 | ] 103 | }, 104 | "color-highlight.markRuler": { 105 | "default": true, 106 | "description": "Highlight colors on the ruler (scroll bar), true/false", 107 | "type": "boolean" 108 | }, 109 | "color-highlight.sass.includePaths": { 110 | "default": [], 111 | "description": "Array of absolute paths to search while perform file lookups.", 112 | "type": "array" 113 | } 114 | } 115 | }, 116 | "commands": [ 117 | { 118 | "command": "extension.colorHighlight", 119 | "title": "Highlight colors in current file" 120 | } 121 | ] 122 | }, 123 | "devDependencies": { 124 | "@babel/core": "^7.14.6", 125 | "@babel/eslint-parser": "^7.14.7", 126 | "@babel/plugin-transform-runtime": "^7.14.5", 127 | "@babel/preset-env": "^7.14.7", 128 | "@types/mocha": "^2.2.32", 129 | "@types/node": "^6.0.40", 130 | "@types/vscode": "^1.57.0", 131 | "babel-loader": "^8.2.2", 132 | "eslint": "^7.29.0", 133 | "mocha": "^9.0.0", 134 | "npm-force-resolutions": "0.0.10", 135 | "path-browserify": "^1.0.1", 136 | "vscode": "^0.9.9", 137 | "webpack": "^5.76.0", 138 | "webpack-cli": "^4.7.2" 139 | }, 140 | "dependencies": { 141 | "@babel/runtime": "^7.14.6", 142 | "color": "^1.0.3", 143 | "color-name": "^1.1.4", 144 | "file-importer": "^1.0.0" 145 | }, 146 | "resolutions": { 147 | "minimist": "^1.2.5" 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/color-highlight.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | import { 3 | workspace, 4 | window, 5 | Range, 6 | } from 'vscode'; 7 | import { findScssVars } from './strategies/scss-vars'; 8 | import { findLessVars } from './strategies/less-vars'; 9 | import { findStylVars } from './strategies/styl-vars'; 10 | import { findCssVars } from './strategies/css-vars'; 11 | import { findColorFunctionsInText } from './strategies/functions'; 12 | import { findRgbNoFn } from './strategies/rgbWithoutFunction'; 13 | import { findHslNoFn } from './strategies/hslWithoutFunction'; 14 | import { findHexARGB, findHexRGBA } from './strategies/hex'; 15 | import { findHwb } from './strategies/hwb'; 16 | import { findWords } from './strategies/words'; 17 | import { DecorationMap } from './lib/decoration-map'; 18 | import { dirname } from 'path'; 19 | 20 | const colorWordsLanguages = ['css', 'scss', 'sass', 'less', 'stylus']; 21 | 22 | export class DocumentHighlight { 23 | 24 | /** 25 | * Creates an instance of DocumentHighlight. 26 | * @param {TextDocument} document 27 | * @param {any} viewConfig 28 | * 29 | * @memberOf DocumentHighlight 30 | */ 31 | constructor(document, viewConfig) { 32 | this.disposed = false; 33 | 34 | this.document = document; 35 | this.strategies = [findColorFunctionsInText, findHwb]; 36 | 37 | if (viewConfig.useARGB == true) { 38 | this.strategies.push(findHexARGB); 39 | } else { 40 | this.strategies.push(findHexRGBA); 41 | } 42 | 43 | if (colorWordsLanguages.indexOf(document.languageId) > -1 || viewConfig.matchWords) { 44 | this.strategies.push(findWords); 45 | } 46 | 47 | if (viewConfig.matchRgbWithNoFunction) { 48 | let isValid = false; 49 | 50 | if (viewConfig.rgbWithNoFunctionLanguages.indexOf('*') > -1) { 51 | isValid = true; 52 | } 53 | 54 | if (viewConfig.rgbWithNoFunctionLanguages.indexOf(document.languageId) > -1) { 55 | isValid = true; 56 | } 57 | 58 | if (viewConfig.rgbWithNoFunctionLanguages.indexOf(`!${document.languageId}`) > -1) { 59 | isValid = false; 60 | } 61 | 62 | if (isValid) this.strategies.push(findRgbNoFn); 63 | } 64 | 65 | if (viewConfig.matchHslWithNoFunction) { 66 | let isValid = false; 67 | 68 | if (viewConfig.hslWithNoFunctionLanguages.indexOf('*') > -1) { 69 | isValid = true; 70 | } 71 | 72 | if (viewConfig.hslWithNoFunctionLanguages.indexOf(document.languageId) > -1) { 73 | isValid = true; 74 | } 75 | 76 | if (viewConfig.hslWithNoFunctionLanguages.indexOf(`!${document.languageId}`) > -1) { 77 | isValid = false; 78 | } 79 | 80 | if (isValid) this.strategies.push(findHslNoFn); 81 | } 82 | 83 | switch (document.languageId) { 84 | case 'css': 85 | this.strategies.push(findCssVars); 86 | break; 87 | case 'less': 88 | this.strategies.push(findLessVars); 89 | break; 90 | case 'stylus': 91 | this.strategies.push(findStylVars); 92 | break; 93 | case 'sass': 94 | case 'scss': 95 | this.strategies.push(text => findScssVars(text, { 96 | data: text, 97 | cwd: dirname(document.uri.fsPath), 98 | extensions: ['.scss', '.sass'], 99 | includePaths: viewConfig.sass.includePaths || [] 100 | })); 101 | break; 102 | } 103 | 104 | this.initialize(viewConfig); 105 | } 106 | 107 | initialize(viewConfig) { 108 | this.decorations = new DecorationMap(viewConfig); 109 | this.listner = workspace.onDidChangeTextDocument(({ document }) => this.onUpdate(document)); 110 | } 111 | 112 | /** 113 | * 114 | * @param {TextDocumentChangeEvent} e 115 | * 116 | * @memberOf DocumentHighlight 117 | */ 118 | onUpdate(document = this.document) { 119 | if (this.disposed || this.document.uri.toString() !== document.uri.toString()) { 120 | return; 121 | } 122 | 123 | const text = this.document.getText(); 124 | const version = this.document.version.toString(); 125 | 126 | return this.updateRange(text, version); 127 | } 128 | 129 | /** 130 | * @param {string} text 131 | * @param {string} version 132 | * 133 | * @memberOf DocumentHighlight 134 | */ 135 | async updateRange(text, version) { 136 | try { 137 | const result = await Promise.all(this.strategies.map(fn => fn(text))); 138 | 139 | const actualVersion = this.document.version.toString(); 140 | if (actualVersion !== version) { 141 | if (process.env.COLOR_HIGHLIGHT_DEBUG) throw new Error('Document version already has changed'); 142 | 143 | return; 144 | } 145 | 146 | const colorRanges = groupByColor(concatAll(result)); 147 | 148 | if (this.disposed) { 149 | return false; 150 | } 151 | 152 | const updateStack = this.decorations.keys() 153 | .reduce((state, color) => { 154 | state[color] = []; 155 | return state; 156 | }, {}); 157 | 158 | for (const color in colorRanges) { 159 | updateStack[color] = colorRanges[color].map(item => { 160 | return new Range( 161 | this.document.positionAt(item.start), 162 | this.document.positionAt(item.end) 163 | ); 164 | }); 165 | } 166 | 167 | for (const color in updateStack) { 168 | const decoration = this.decorations.get(color); 169 | 170 | window.visibleTextEditors 171 | .filter(({ document }) => document.uri === this.document.uri) 172 | .forEach(editor => editor.setDecorations(decoration, updateStack[color])); 173 | } 174 | } catch (error) { 175 | console.error(error); 176 | } 177 | } 178 | 179 | dispose() { 180 | this.disposed = true; 181 | this.decorations.dispose(); 182 | this.listner.dispose(); 183 | 184 | this.decorations = null; 185 | this.document = null; 186 | this.colors = null; 187 | this.listner = null; 188 | } 189 | } 190 | 191 | function groupByColor(results) { 192 | return results 193 | .reduce((collection, item) => { 194 | if (!collection[item.color]) { 195 | collection[item.color] = []; 196 | } 197 | 198 | collection[item.color].push(item); 199 | 200 | return collection; 201 | }, {}); 202 | } 203 | 204 | function concatAll(arr) { 205 | return arr.reduce((result, item) => result.concat(item), []); 206 | } 207 | -------------------------------------------------------------------------------- /src/lib/dynamic-contrast.js: -------------------------------------------------------------------------------- 1 | // getColorContrast 2 | // Return suggested contrast grey scale color for the color (hex/rgba) given. 3 | // Uses the definitions of relative luminance and contrast ratio from 4 | // WCAG 2.0: https://www.w3.org/TR/WCAG20 5 | // 6 | // @param color string A valid hex or rgb value, examples: 7 | // #000, #000000, 000, 000000 8 | // rgb(255, 255, 255), rgba(255, 255, 255), 9 | // rgba(255, 255, 255, 1) 10 | // blue, green, red 11 | // @return string of the form #RRGGBB 12 | import webColors from 'color-name'; 13 | 14 | export function getColorContrast(color) { 15 | const rgbExp = /^rgba?[\s+]?\(\s*([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\s*,\s*([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\s*(?:,\s*([\d.]+)\s*)?\)/im, 16 | hexExp = /^(?:#)|([a-fA-F0-9]{3}|[a-fA-F0-9]{6})$/igm; 17 | let rgb = color.match(rgbExp), 18 | hex = color.match(hexExp), 19 | r, g, b; 20 | if (rgb) { 21 | r = parseInt(rgb[1], 10); 22 | g = parseInt(rgb[2], 10); 23 | b = parseInt(rgb[3], 10); 24 | } else if (hex) { 25 | if (hex.length > 1) { 26 | hex = hex[1]; 27 | } else { 28 | hex = hex[0]; 29 | } 30 | if (hex.length == 3) { 31 | hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; 32 | } 33 | r = parseInt(hex.substr(0, 2), 16); 34 | g = parseInt(hex.substr(2, 2), 16); 35 | b = parseInt(hex.substr(4, 2), 16); 36 | } else { 37 | rgb = webColors[color.toLowerCase()]; 38 | if (rgb) { 39 | r = rgb[0]; 40 | g = rgb[1]; 41 | b = rgb[2]; 42 | } else { 43 | return '#000000'; 44 | } 45 | } 46 | // The color with the maximum contrast ratio to our input color is guaranteed 47 | // to either be white or black, so we just check both and pick whichever has 48 | // a higher contrast ratio. 49 | 50 | let luminance = relativeLuminance(r, g, b); 51 | 52 | // This is equivalent to `relativeLuminance(255, 255, 255)` (by definition). 53 | let luminanceWhite = 1.0; 54 | // This is equivalent to `relativeLuminance(0, 0, 0)` (by definition). 55 | let luminanceBlack = 0.0; 56 | 57 | let contrastWhite = contrastRatio(luminance, luminanceWhite); 58 | let contrastBlack = contrastRatio(luminance, luminanceBlack); 59 | if (contrastWhite > contrastBlack) { 60 | return '#FFFFFF'; 61 | } else { 62 | return '#000000'; 63 | } 64 | } 65 | 66 | // Note: the rest of this module contains unexported helper functions. 67 | 68 | /** 69 | * Compute the contrast ratio between two relative luminances, using the 70 | * algorithm from WCAG 2.0: 71 | * 72 | * Note that the order of the arguments does not matter. In other words, if `a` 73 | * and `b` are valid inputs, then `contrastRatio(a, b) === contrastRatio(b, a)`. 74 | * 75 | * @param l1 number The relative luminance of the first color -- a number 76 | * between 0.0 and 1.0 (inclusive), which should be produced 77 | * by the `relativeLuminance` function. 78 | * @param l2 number The relative luminance of the second color -- a number 79 | * between 0.0 and 1.0 (inclusive), which is expected to have 80 | * been produced by the `relativeLuminance` function. 81 | * 82 | * @returns number The contrast ratio between the input colors. Assuming the 83 | * inputs were in the correct range, this will be a number 84 | * between 1.0 and 21.0 (inclusive). 85 | */ 86 | function contrastRatio(l1, l2) { 87 | // Note: the denominator of the contrast ratio must be the darker (e.g. lower 88 | // relative luminance) color. 89 | if (l2 < l1) { 90 | return (0.05 + l1) / (0.05 + l2); 91 | } else { 92 | return (0.05 + l2) / (0.05 + l1); 93 | } 94 | } 95 | 96 | /** 97 | * Compute the relative luminance of a color, using the algorithm from WCAG 2.0 98 | * . 99 | * 100 | * All three color components used as input should be integers between 0 and 255 101 | * inclusive, and are assumed to be in the sRGB color space -- typical for 102 | * source code constants, especially ones using CSS syntax, as sRGB is the 103 | * default color space on the web. 104 | * 105 | * (Note: it's overwhelmingly likely that even if the true color space of the 106 | * color is *not* sRGB, that it still has an sRGB-style gamma curve, if not a 107 | * fully sRGB-compatible one, in which case the result of this function will 108 | * still be reasonable) 109 | * 110 | * @param r8 number The red component, as an 8-bit integer 111 | * @param g8 number The green component, as an 8-bit integer 112 | * @param b8 number The blue component, as an 8-bit integer 113 | * 114 | * @returns number The relative luminance of the color, a number between 0.0 115 | * and 1.0 (inclusive). 116 | */ 117 | function relativeLuminance(r8, g8, b8) { 118 | const bigR = srgb8ToLinear(r8); 119 | const bigG = srgb8ToLinear(g8); 120 | const bigB = srgb8ToLinear(b8); 121 | return 0.2126 * bigR + 0.7152 * bigG + 0.0722 * bigB; 122 | } 123 | 124 | /** 125 | * Convert an 8-bit color component from sRGB space (the default web color 126 | * space) into the linear RGB color space. 127 | * 128 | * This is a helper function for `relativeLuminance`, and at the moment isn't 129 | * needed except as part of calling that function. 130 | * 131 | * @param c8 number An 8-bit integer color channel in the sRGB color space. In 132 | * other words, a number between 0 and 255 (inclusive). 133 | * Anything outside this range will be clamped and truncated. 134 | * 135 | * @returns number The value of the channel in a linear RGB color space -- a 136 | * number between 0.0 and 1.0, inclusive. 137 | */ 138 | const srgb8ToLinear = (function() { 139 | // There are only 256 possible different input values (0 <= input <= 255), 140 | // so we just use a lookup table, which to avoid repeating the (somewhat 141 | // costly) computation 3 times for each input. 142 | const srgbLookupTable = new Float64Array(256); 143 | for (let i = 0; i < 256; ++i) { 144 | const c = i / 255.0; 145 | srgbLookupTable[i] = (c <= 0.04045) 146 | ? c / 12.92 147 | : Math.pow((c + 0.055) / 1.055, 2.4); 148 | } 149 | 150 | return function srgb8ToLinear(c8) { 151 | // Input should be an integer between 0 and 255 already, but clamp if 152 | // for some reason it is not. 153 | const index = Math.min(Math.max(c8, 0), 255) & 0xff; 154 | return srgbLookupTable[index]; 155 | }; 156 | }()); 157 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------