Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Ignore 0xHHH and 0xHHHH hex colors #143

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions src/strategies/hex.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Color from 'color';

const colorHex = /.?((?:\#|\b0x)([a-f0-9]{6}([a-f0-9]{2})?|[a-f0-9]{3}([a-f0-9]{1})?))\b/gi;
const colorHex = /.?((\#|\b0x)([a-f0-9]{6}([a-f0-9]{2})?|[a-f0-9]{3}([a-f0-9]{1})?))\b/gi;

/**
* @export
Expand All @@ -18,15 +18,24 @@ export async function findHex(text) {
while (match !== null) {
const firstChar = match[0][0];
const matchedColor = match[1];
const matchedHex = '#' + match[2];
const colorPrefix = match[2];
const hexChars = match[3];

const matchedHex = '#' + hexChars;
const start = match.index + (match[0].length - matchedColor.length);
const end = colorHex.lastIndex;


// Check the symbol before the color match, and try to avoid coloring in the
// contexts that are not relevant
// https://github.com/sergiirocks/vscode-ext-color-highlight/issues/25
if (firstChar.length && /\w/.test(firstChar)) {
// We skip the match in the following cases:
// 1. If the symbol before the `#` (exists and) is a letter, to try to avoid
// coloring in the contexts that are not relevant (such as inside a URL).
// https://github.com/sergiirocks/vscode-ext-color-highlight/issues/25
const notRelevant = firstChar.length && /\w/.test(firstChar);
// 2. If the color is a numeric hex color, and it is only 3 or 4 characters
// (e.g. `0xHHH` or `0xHHHH`), as these are *far* more likely to be
// normal hexadecimal number literals, which do not represent a color.
const isShortNumeric = /0x/i.test(colorPrefix) && hexChars.length <= 4;

if (notRelevant || isShortNumeric) {
match = colorHex.exec(text);
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion test/fixture/test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// #f00
// #ff0000
// 0xf00
// 0xff0000ff
// 0xff0000
// rgb(255, 0, 0)
// rgb(100%, 0%, 0%)
Expand Down