Reference

ack

OtherEvergreenPublic

ack is a grep-like source code search tool.

Ack for CSS Developers

https://csswizardry.com/2017/01/ack-for-css-developers/

ack --html "foo"
ack --html --js --css "bar"
ack --help-types
ack --css "\d*\.\d*px"

Find Decimal Pixel Values

ack --css "\d*\.\d*px"

We don’t want to have any decimal places in any of our pixel values (e.g. 7.5px), so let’s search for those:

  • \d* will match zero or more (*) \digits. The reason I’m looking for zero or more is because I want to find both .5px or 11.2px.
  • \. will match a literal full-stop/period character.
  • \d* is the same as before. This means I will find both 97.856px, or 52.px (which is actually just an error).
  • px will match the literal string px: I don’t want to look for ems or rems or percentages because they accept float values.

See the demo.

Find IDs

We definitely shouldn’t be using IDs in CSS, so let’s look for them:

ack --css -i "#[-_a-z][-_a-z0-9]*(?=[^}]*\{)"

Firstly, notice the -i flag. This tells Ack to run our regexes case insensitively.

This pretty complex regex does a few things:

  • #finds a literal hash (#) symbol.
  • [-_a-z] finds a single hyphen (-), underscore (_), or case insensitive a-z, denoting a valid start to an ID.
  • [-_a-z0-9]* does almost exactly the same as above, except this time we’re looking for zero or more (*) characters, and for digits as well (0-9). We’re doing this separately from the previous lookup because IDs can’t start with numbers.
  • (?=[^}]*\{) is running a positive lookahead, just checking that we encounter an opening curly brace (\{) next, and not a closing one ([^}]).

This means we will find IDs, but not hex values.

N.B. Because of Sass’ nesting abilities, nested code containing hex values becomes a false positive. As such, only run this regex over your compiled CSS. Please refer to the demo.

Background Shorthand

ack --css -i "background:\s*#[a-f0-9]*;"
  • background: finds the literal string background followed by a colon (:).
  • \s* matches zero or more units of whitespace between the colon and the beginning of a hex value.
  • # is the literal hash symbol (#), the beginning of a hex value.
  • [a-f0-9]* is a valid hex value (e.g. #f00, #BADA55). Setting the -i flag means that our regex is now case insensitive.
  • ; matches the literal semi-colon character (;) which denotes the termination of the declaration.

See the .

Find Unitted Zeroes

ack --css "\b0(px|r?em)"

This is a little pedantic of me, but putting a unit (e.g. px) on a zero (0) is redundant: zero pixels is the same distance as zero lightyears. Let’s look for them.

  • \b looks for a word boundary. This means we’re looking for zeroes at the start of a string (i.e. 0px) and not midway through one (e.g. 210px).
  • 0 is looking for the literal zero character (0).
  • (px|r?em) looks for the literal strings px or rem or em.
  • r?em makes the r optional, so we can match either rem or em at the same time.