* lisp/textmodes/css-mode.el (css--hex-color): Trivial simplification
[emacs.git] / lisp / textmodes / css-mode.el
blobb0e66d397f07a246151deb028b0580f9c972a6e2
1 ;;; css-mode.el --- Major mode to edit CSS files -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2017 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Maintainer: Simen Heggestøyl <simenheg@gmail.com>
7 ;; Keywords: hypermedia
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; Yet another CSS mode.
28 ;;; Todo:
30 ;; - filling code with auto-fill-mode
31 ;; - fix font-lock errors with multi-line selectors
33 ;;; Code:
35 (require 'eww)
36 (require 'cl-lib)
37 (require 'color)
38 (require 'seq)
39 (require 'sgml-mode)
40 (require 'smie)
41 (eval-when-compile (require 'subr-x))
43 (defgroup css nil
44 "Cascading Style Sheets (CSS) editing mode."
45 :group 'languages)
47 (defconst css-pseudo-class-ids
48 '("active" "checked" "default" "disabled" "empty" "enabled" "first"
49 "first-child" "first-of-type" "focus" "focus-within" "hover"
50 "in-range" "indeterminate" "invalid" "lang" "last-child"
51 "last-of-type" "left" "link" "not" "nth-child" "nth-last-child"
52 "nth-last-of-type" "nth-of-type" "only-child" "only-of-type"
53 "optional" "out-of-range" "read-only" "read-write" "required"
54 "right" "root" "scope" "target" "valid" "visited")
55 "Identifiers for pseudo-classes.")
57 (defconst css-pseudo-element-ids
58 '("after" "before" "first-letter" "first-line")
59 "Identifiers for pseudo-elements.")
61 (defconst css-at-ids
62 '("charset" "font-face" "import" "keyframes" "media" "namespace"
63 "page" "supports")
64 "Identifiers that appear in the form @foo.")
66 (defconst scss-at-ids
67 '("at-root" "content" "debug" "each" "else" "else if" "error" "extend"
68 "for" "function" "if" "import" "include" "mixin" "return" "warn"
69 "while")
70 "Additional identifiers that appear in the form @foo in SCSS.")
72 (defvar css--at-ids css-at-ids
73 "List of at-rules for the current mode.")
74 (make-variable-buffer-local 'css--at-ids)
76 (defconst css-bang-ids
77 '("important")
78 "Identifiers that appear in the form !foo.")
80 (defconst scss-bang-ids
81 '("default" "global" "optional")
82 "Additional identifiers that appear in the form !foo in SCSS.")
84 (defvar css--bang-ids css-bang-ids
85 "List of bang-rules for the current mode.")
86 (make-variable-buffer-local 'css--bang-ids)
88 (defconst css-descriptor-ids
89 '("ascent" "baseline" "bbox" "cap-height" "centerline" "definition-src"
90 "descent" "font-family" "font-size" "font-stretch" "font-style"
91 "font-variant" "font-weight" "mathline" "panose-1" "slope" "src" "stemh"
92 "stemv" "topline" "unicode-range" "units-per-em" "widths" "x-height")
93 "Identifiers for font descriptors.")
95 (defconst css-media-ids
96 '("all" "aural" "bitmap" "continuous" "grid" "paged" "static" "tactile"
97 "visual")
98 "Identifiers for types of media.")
100 (defconst css-property-alist
101 ;; CSS 2.1 properties (http://www.w3.org/TR/CSS21/propidx.html).
103 ;; Properties duplicated by any of the CSS3 modules below have been
104 ;; removed.
105 '(("azimuth" angle "left-side" "far-left" "left" "center-left"
106 "center" "center-right" "right" "far-right" "right-side" "behind"
107 "leftwards" "rightwards")
108 ("border-collapse" "collapse" "separate")
109 ("border-spacing" length)
110 ("bottom" length percentage "auto")
111 ("caption-side" "top" "bottom")
112 ("clear" "none" "left" "right" "both")
113 ("clip" shape "auto")
114 ("content" "normal" "none" string uri counter "attr()"
115 "open-quote" "close-quote" "no-open-quote" "no-close-quote")
116 ("counter-increment" identifier integer "none")
117 ("counter-reset" identifier integer "none")
118 ("cue" cue-before cue-after)
119 ("cue-after" uri "none")
120 ("cue-before" uri "none")
121 ("direction" "ltr" "rtl")
122 ("display" "inline" "block" "list-item" "inline-block" "table"
123 "inline-table" "table-row-group" "table-header-group"
124 "table-footer-group" "table-row" "table-column-group"
125 "table-column" "table-cell" "table-caption" "none"
126 ;; CSS Flexible Box Layout Module Level 1
127 ;; (https://www.w3.org/TR/css3-flexbox/#valdef-display-flex)
128 "flex" "inline-flex"
129 ;; CSS Grid Layout Module Level 1
130 ;; (https://www.w3.org/TR/css-grid-1/#grid-containers)
131 "grid" "inline-grid" "subgrid")
132 ("elevation" angle "below" "level" "above" "higher" "lower")
133 ("empty-cells" "show" "hide")
134 ("float" "left" "right" "none")
135 ("height" length percentage "auto")
136 ("left" length percentage "auto")
137 ("line-height" "normal" number length percentage)
138 ("list-style" list-style-type list-style-position
139 list-style-image)
140 ("list-style-image" uri "none")
141 ("list-style-position" "inside" "outside")
142 ("list-style-type" "disc" "circle" "square" "decimal"
143 "decimal-leading-zero" "lower-roman" "upper-roman" "lower-greek"
144 "lower-latin" "upper-latin" "armenian" "georgian" "lower-alpha"
145 "upper-alpha" "none")
146 ("margin" margin-width)
147 ("margin-bottom" margin-width)
148 ("margin-left" margin-width)
149 ("margin-right" margin-width)
150 ("margin-top" margin-width)
151 ("max-height" length percentage "none")
152 ("max-width" length percentage "none")
153 ("min-height" length percentage)
154 ("min-width" length percentage)
155 ("padding" padding-width)
156 ("padding-bottom" padding-width)
157 ("padding-left" padding-width)
158 ("padding-right" padding-width)
159 ("padding-top" padding-width)
160 ("page-break-after" "auto" "always" "avoid" "left" "right")
161 ("page-break-before" "auto" "always" "avoid" "left" "right")
162 ("page-break-inside" "avoid" "auto")
163 ("pause" time percentage)
164 ("pause-after" time percentage)
165 ("pause-before" time percentage)
166 ("pitch" frequency "x-low" "low" "medium" "high" "x-high")
167 ("pitch-range" number)
168 ("play-during" uri "mix" "repeat" "auto" "none")
169 ("position" "static" "relative" "absolute" "fixed")
170 ("quotes" string "none")
171 ("richness" number)
172 ("right" length percentage "auto")
173 ("speak" "normal" "none" "spell-out")
174 ("speak-header" "once" "always")
175 ("speak-numeral" "digits" "continuous")
176 ("speak-punctuation" "code" "none")
177 ("speech-rate" number "x-slow" "slow" "medium" "fast" "x-fast"
178 "faster" "slower")
179 ("stress" number)
180 ("table-layout" "auto" "fixed")
181 ("top" length percentage "auto")
182 ("unicode-bidi" "normal" "embed" "bidi-override")
183 ("vertical-align" "baseline" "sub" "super" "top" "text-top"
184 "middle" "bottom" "text-bottom" percentage length)
185 ("visibility" "visible" "hidden" "collapse")
186 ("voice-family" specific-voice generic-voice specific-voice
187 generic-voice)
188 ("volume" number percentage "silent" "x-soft" "soft" "medium"
189 "loud" "x-loud")
190 ("width" length percentage "auto")
191 ("z-index" "auto" integer)
193 ;; CSS Animations
194 ;; (http://www.w3.org/TR/css3-animations/#property-index)
195 ("animation" single-animation-name time single-timing-function
196 single-animation-iteration-count single-animation-direction
197 single-animation-fill-mode single-animation-play-state)
198 ("animation-delay" time)
199 ("animation-direction" single-animation-direction)
200 ("animation-duration" time)
201 ("animation-fill-mode" single-animation-fill-mode)
202 ("animation-iteration-count" single-animation-iteration-count)
203 ("animation-name" single-animation-name)
204 ("animation-play-state" single-animation-play-state)
205 ("animation-timing-function" single-timing-function)
207 ;; CSS Backgrounds and Borders Module Level 3
208 ;; (http://www.w3.org/TR/css3-background/#property-index)
209 ("background" bg-layer final-bg-layer)
210 ("background-attachment" attachment)
211 ("background-clip" box)
212 ("background-color" color)
213 ("background-image" bg-image)
214 ("background-origin" box)
215 ("background-position" position)
216 ("background-repeat" repeat-style)
217 ("background-size" bg-size)
218 ("border" line-width line-style color)
219 ("border-bottom" line-width line-style color)
220 ("border-bottom-color" color)
221 ("border-bottom-left-radius" length percentage)
222 ("border-bottom-right-radius" length percentage)
223 ("border-bottom-style" line-style)
224 ("border-bottom-width" line-width)
225 ("border-color" color)
226 ("border-image" border-image-source border-image-slice
227 border-image-width border-image-outset border-image-repeat)
228 ("border-image-outset" length number)
229 ("border-image-repeat" "stretch" "repeat" "round" "space")
230 ("border-image-slice" number percentage "fill")
231 ("border-image-source" "none" image)
232 ("border-image-width" length percentage number "auto")
233 ("border-left" line-width line-style color)
234 ("border-left-color" color)
235 ("border-left-style" line-style)
236 ("border-left-width" line-width)
237 ("border-radius" length percentage)
238 ("border-right" line-width line-style color)
239 ("border-right-color" color)
240 ("border-right-style" line-style)
241 ("border-right-width" line-width)
242 ("border-style" line-style)
243 ("border-top" line-width line-style color)
244 ("border-top-color" color)
245 ("border-top-left-radius" length percentage)
246 ("border-top-right-radius" length percentage)
247 ("border-top-style" line-style)
248 ("border-top-width" line-width)
249 ("border-width" line-width)
250 ("box-shadow" "none" shadow)
252 ;; CSS Basic User Interface Module Level 3 (CSS3 UI)
253 ;; (http://www.w3.org/TR/css3-ui/#property-index)
254 ("box-sizing" "content-box" "border-box")
255 ("caret-color" "auto" color)
256 ("cursor" uri x y "auto" "default" "none" "context-menu" "help"
257 "pointer" "progress" "wait" "cell" "crosshair" "text"
258 "vertical-text" "alias" "copy" "move" "no-drop" "not-allowed"
259 "grab" "grabbing" "e-resize" "n-resize" "ne-resize" "nw-resize"
260 "s-resize" "se-resize" "sw-resize" "w-resize" "ew-resize"
261 "ns-resize" "nesw-resize" "nwse-resize" "col-resize" "row-resize"
262 "all-scroll" "zoom-in" "zoom-out")
263 ("nav-down" "auto" id "current" "root" target-name)
264 ("nav-left" "auto" id "current" "root" target-name)
265 ("nav-right" "auto" id "current" "root" target-name)
266 ("nav-up" "auto" id "current" "root" target-name)
267 ("outline" outline-color outline-style outline-width)
268 ("outline-color" color "invert")
269 ("outline-offset" length)
270 ("outline-style" "auto" border-style)
271 ("outline-width" border-width)
272 ("resize" "none" "both" "horizontal" "vertical")
273 ("text-overflow" "clip" "ellipsis" string)
275 ;; CSS Color Module Level 3
276 ;; (http://www.w3.org/TR/css3-color/#property)
277 ("color" color)
278 ("opacity" alphavalue)
280 ;; CSS Grid Layout Module Level 1
281 ;; (https://www.w3.org/TR/css-grid-1/#property-index)
282 ("grid" grid-template grid-template-rows "auto-flow" "dense"
283 grid-auto-columns grid-auto-rows grid-template-columns)
284 ("grid-area" grid-line)
285 ("grid-auto-columns" track-size)
286 ("grid-auto-flow" "row" "column" "dense")
287 ("grid-auto-rows" track-size)
288 ("grid-column" grid-line)
289 ("grid-column-end" grid-line)
290 ("grid-column-gap" length-percentage)
291 ("grid-column-start" grid-line)
292 ("grid-gap" grid-row-gap grid-column-gap)
293 ("grid-row" grid-line)
294 ("grid-row-end" grid-line)
295 ("grid-row-gap" length-percentage)
296 ("grid-row-start" grid-line)
297 ("grid-template" "none" grid-template-rows grid-template-columns
298 line-names string track-size line-names explicit-track-list)
299 ("grid-template-areas" "none" string)
300 ("grid-template-columns" "none" track-list auto-track-list)
301 ("grid-template-rows" "none" track-list auto-track-list)
303 ;; CSS Flexible Box Layout Module Level 1
304 ;; (http://www.w3.org/TR/css-flexbox-1/#property-index)
305 ("align-content" "flex-start" "flex-end" "center" "space-between"
306 "space-around" "stretch")
307 ("align-items" "flex-start" "flex-end" "center" "baseline"
308 "stretch")
309 ("align-self" "auto" "flex-start" "flex-end" "center" "baseline"
310 "stretch")
311 ("flex" "none" flex-grow flex-shrink flex-basis)
312 ("flex-basis" "auto" "content" width)
313 ("flex-direction" "row" "row-reverse" "column" "column-reverse")
314 ("flex-flow" flex-direction flex-wrap)
315 ("flex-grow" number)
316 ("flex-shrink" number)
317 ("flex-wrap" "nowrap" "wrap" "wrap-reverse")
318 ("justify-content" "flex-start" "flex-end" "center"
319 "space-between" "space-around")
320 ("order" integer)
322 ;; CSS Fonts Module Level 3
323 ;; (http://www.w3.org/TR/css3-fonts/#property-index)
324 ("font" font-style font-variant-css21 font-weight font-stretch
325 font-size line-height font-family "caption" "icon" "menu"
326 "message-box" "small-caption" "status-bar")
327 ("font-family" family-name generic-family)
328 ("font-feature-settings" "normal" feature-tag-value)
329 ("font-kerning" "auto" "normal" "none")
330 ("font-language-override" "normal" string)
331 ("font-size" absolute-size relative-size length percentage)
332 ("font-size-adjust" "none" number)
333 ("font-stretch" "normal" "ultra-condensed" "extra-condensed"
334 "condensed" "semi-condensed" "semi-expanded" "expanded"
335 "extra-expanded" "ultra-expanded")
336 ("font-style" "normal" "italic" "oblique")
337 ("font-synthesis" "none" "weight" "style")
338 ("font-variant" "normal" "none" common-lig-values
339 discretionary-lig-values historical-lig-values
340 contextual-alt-values "stylistic()" "historical-forms"
341 "styleset()" "character-variant()" "swash()" "ornaments()"
342 "annotation()" "small-caps" "all-small-caps" "petite-caps"
343 "all-petite-caps" "unicase" "titling-caps" numeric-figure-values
344 numeric-spacing-values numeric-fraction-values "ordinal"
345 "slashed-zero" east-asian-variant-values east-asian-width-values
346 "ruby")
347 ("font-variant-alternates" "normal" "stylistic()"
348 "historical-forms" "styleset()" "character-variant()" "swash()"
349 "ornaments()" "annotation()")
350 ("font-variant-caps" "normal" "small-caps" "all-small-caps"
351 "petite-caps" "all-petite-caps" "unicase" "titling-caps")
352 ("font-variant-east-asian" "normal" east-asian-variant-values
353 east-asian-width-values "ruby")
354 ("font-variant-ligatures" "normal" "none" common-lig-values
355 discretionary-lig-values historical-lig-values
356 contextual-alt-values)
357 ("font-variant-numeric" "normal" numeric-figure-values
358 numeric-spacing-values numeric-fraction-values "ordinal"
359 "slashed-zero")
360 ("font-variant-position" "normal" "sub" "super")
361 ("font-weight" "normal" "bold" "bolder" "lighter" "100" "200"
362 "300" "400" "500" "600" "700" "800" "900")
364 ;; CSS Fragmentation Module Level 3
365 ;; (https://www.w3.org/TR/css-break-3/#property-index)
366 ("box-decoration-break" "slice" "clone")
367 ("break-after" "auto" "avoid" "avoid-page" "page" "left" "right"
368 "recto" "verso" "avoid-column" "column" "avoid-region" "region")
369 ("break-before" "auto" "avoid" "avoid-page" "page" "left" "right"
370 "recto" "verso" "avoid-column" "column" "avoid-region" "region")
371 ("break-inside" "auto" "avoid" "avoid-page" "avoid-column"
372 "avoid-region")
373 ("orphans" integer)
374 ("widows" integer)
376 ;; CSS Multi-column Layout Module
377 ;; (https://www.w3.org/TR/css3-multicol/#property-index)
378 ;; "break-after", "break-before", and "break-inside" are left out
379 ;; below, because they're already included in CSS Fragmentation
380 ;; Module Level 3.
381 ("column-count" integer "auto")
382 ("column-fill" "auto" "balance")
383 ("column-gap" length "normal")
384 ("column-rule" column-rule-width column-rule-style
385 column-rule-color "transparent")
386 ("column-rule-color" color)
387 ("column-rule-style" border-style)
388 ("column-rule-width" border-width)
389 ("column-span" "none" "all")
390 ("column-width" length "auto")
391 ("columns" column-width column-count)
393 ;; CSS Overflow Module Level 3
394 ;; (http://www.w3.org/TR/css-overflow-3/#property-index)
395 ("max-lines" "none" integer)
396 ("overflow" "visible" "hidden" "scroll" "auto" "paged-x" "paged-y"
397 "paged-x-controls" "paged-y-controls" "fragments")
398 ("overflow-x" "visible" "hidden" "scroll" "auto" "paged-x"
399 "paged-y" "paged-x-controls" "paged-y-controls" "fragments")
400 ("overflow-y" "visible" "hidden" "scroll" "auto" "paged-x"
401 "paged-y" "paged-x-controls" "paged-y-controls" "fragments")
403 ;; CSS Text Decoration Module Level 3
404 ;; (http://dev.w3.org/csswg/css-text-decor-3/#property-index)
405 ("text-decoration" text-decoration-line text-decoration-style
406 text-decoration-color)
407 ("text-decoration-color" color)
408 ("text-decoration-line" "none" "underline" "overline"
409 "line-through" "blink")
410 ("text-decoration-skip" "none" "objects" "spaces" "ink" "edges"
411 "box-decoration")
412 ("text-decoration-style" "solid" "double" "dotted" "dashed"
413 "wavy")
414 ("text-emphasis" text-emphasis-style text-emphasis-color)
415 ("text-emphasis-color" color)
416 ("text-emphasis-position" "over" "under" "right" "left")
417 ("text-emphasis-style" "none" "filled" "open" "dot" "circle"
418 "double-circle" "triangle" "sesame" string)
419 ("text-shadow" "none" length color)
420 ("text-underline-position" "auto" "under" "left" "right")
422 ;; CSS Text Module Level 3
423 ;; (http://www.w3.org/TR/css3-text/#property-index)
424 ("hanging-punctuation" "none" "first" "force-end" "allow-end"
425 "last")
426 ("hyphens" "none" "manual" "auto")
427 ("letter-spacing" "normal" length)
428 ("line-break" "auto" "loose" "normal" "strict")
429 ("overflow-wrap" "normal" "break-word")
430 ("tab-size" integer length)
431 ("text-align" "start" "end" "left" "right" "center" "justify"
432 "match-parent")
433 ("text-align-last" "auto" "start" "end" "left" "right" "center"
434 "justify")
435 ("text-indent" length percentage)
436 ("text-justify" "auto" "none" "inter-word" "distribute")
437 ("text-transform" "none" "capitalize" "uppercase" "lowercase"
438 "full-width")
439 ("white-space" "normal" "pre" "nowrap" "pre-wrap" "pre-line")
440 ("word-break" "normal" "keep-all" "break-all")
441 ("word-spacing" "normal" length percentage)
442 ("word-wrap" "normal" "break-word")
444 ;; CSS Transforms Module Level 1
445 ;; (http://www.w3.org/TR/css3-2d-transforms/#property-index)
446 ("backface-visibility" "visible" "hidden")
447 ("perspective" "none" length)
448 ("perspective-origin" "left" "center" "right" "top" "bottom"
449 percentage length)
450 ("transform" "none" transform-list)
451 ("transform-origin" "left" "center" "right" "top" "bottom"
452 percentage length)
453 ("transform-style" "flat" "preserve-3d")
455 ;; CSS Transitions
456 ;; (http://www.w3.org/TR/css3-transitions/#property-index)
457 ("transition" single-transition)
458 ("transition-delay" time)
459 ("transition-duration" time)
460 ("transition-property" "none" single-transition-property "all")
461 ("transition-timing-function" single-transition-timing-function)
463 ;; CSS Will Change Module Level 1
464 ;; (https://www.w3.org/TR/css-will-change-1/#property-index)
465 ("will-change" "auto" animateable-feature)
467 ;; Filter Effects Module Level 1
468 ;; (http://www.w3.org/TR/filter-effects/#property-index)
469 ("color-interpolation-filters" "auto" "sRGB" "linearRGB")
470 ("filter" "none" filter-function-list)
471 ("flood-color" color)
472 ("flood-opacity" number percentage)
473 ("lighting-color" color)
475 ;; Pointer Events
476 ;; (https://www.w3.org/TR/pointerevents/#the-touch-action-css-property)
477 ("touch-action" "auto" "none" "pan-x" "pan-y" "manipulation"))
478 "Identifiers for properties and their possible values.
479 The CAR of each entry is the name of a property, while the CDR is
480 a list of possible values for that property. String values in
481 the CDRs represent literal values, while symbols represent one of
482 the value classes found in `css-value-class-alist'. If a symbol
483 is not found in `css-value-class-alist', it's interpreted as a
484 reference back to one of the properties in this list. Some
485 symbols, such as `number' or `identifier', don't produce any
486 further value candidates, since that list would be infinite.")
488 (defconst css-property-ids
489 (mapcar #'car css-property-alist)
490 "Identifiers for properties.")
492 (defconst css--color-map
493 '(("black" . "#000000")
494 ("silver" . "#c0c0c0")
495 ("gray" . "#808080")
496 ("white" . "#ffffff")
497 ("maroon" . "#800000")
498 ("red" . "#ff0000")
499 ("purple" . "#800080")
500 ("fuchsia" . "#ff00ff")
501 ("green" . "#008000")
502 ("lime" . "#00ff00")
503 ("olive" . "#808000")
504 ("yellow" . "#ffff00")
505 ("navy" . "#000080")
506 ("blue" . "#0000ff")
507 ("teal" . "#008080")
508 ("aqua" . "#00ffff")
509 ("orange" . "#ffa500")
510 ("aliceblue" . "#f0f8ff")
511 ("antiquewhite" . "#faebd7")
512 ("aquamarine" . "#7fffd4")
513 ("azure" . "#f0ffff")
514 ("beige" . "#f5f5dc")
515 ("bisque" . "#ffe4c4")
516 ("blanchedalmond" . "#ffebcd")
517 ("blueviolet" . "#8a2be2")
518 ("brown" . "#a52a2a")
519 ("burlywood" . "#deb887")
520 ("cadetblue" . "#5f9ea0")
521 ("chartreuse" . "#7fff00")
522 ("chocolate" . "#d2691e")
523 ("coral" . "#ff7f50")
524 ("cornflowerblue" . "#6495ed")
525 ("cornsilk" . "#fff8dc")
526 ("crimson" . "#dc143c")
527 ("darkblue" . "#00008b")
528 ("darkcyan" . "#008b8b")
529 ("darkgoldenrod" . "#b8860b")
530 ("darkgray" . "#a9a9a9")
531 ("darkgreen" . "#006400")
532 ("darkgrey" . "#a9a9a9")
533 ("darkkhaki" . "#bdb76b")
534 ("darkmagenta" . "#8b008b")
535 ("darkolivegreen" . "#556b2f")
536 ("darkorange" . "#ff8c00")
537 ("darkorchid" . "#9932cc")
538 ("darkred" . "#8b0000")
539 ("darksalmon" . "#e9967a")
540 ("darkseagreen" . "#8fbc8f")
541 ("darkslateblue" . "#483d8b")
542 ("darkslategray" . "#2f4f4f")
543 ("darkslategrey" . "#2f4f4f")
544 ("darkturquoise" . "#00ced1")
545 ("darkviolet" . "#9400d3")
546 ("deeppink" . "#ff1493")
547 ("deepskyblue" . "#00bfff")
548 ("dimgray" . "#696969")
549 ("dimgrey" . "#696969")
550 ("dodgerblue" . "#1e90ff")
551 ("firebrick" . "#b22222")
552 ("floralwhite" . "#fffaf0")
553 ("forestgreen" . "#228b22")
554 ("gainsboro" . "#dcdcdc")
555 ("ghostwhite" . "#f8f8ff")
556 ("gold" . "#ffd700")
557 ("goldenrod" . "#daa520")
558 ("greenyellow" . "#adff2f")
559 ("grey" . "#808080")
560 ("honeydew" . "#f0fff0")
561 ("hotpink" . "#ff69b4")
562 ("indianred" . "#cd5c5c")
563 ("indigo" . "#4b0082")
564 ("ivory" . "#fffff0")
565 ("khaki" . "#f0e68c")
566 ("lavender" . "#e6e6fa")
567 ("lavenderblush" . "#fff0f5")
568 ("lawngreen" . "#7cfc00")
569 ("lemonchiffon" . "#fffacd")
570 ("lightblue" . "#add8e6")
571 ("lightcoral" . "#f08080")
572 ("lightcyan" . "#e0ffff")
573 ("lightgoldenrodyellow" . "#fafad2")
574 ("lightgray" . "#d3d3d3")
575 ("lightgreen" . "#90ee90")
576 ("lightgrey" . "#d3d3d3")
577 ("lightpink" . "#ffb6c1")
578 ("lightsalmon" . "#ffa07a")
579 ("lightseagreen" . "#20b2aa")
580 ("lightskyblue" . "#87cefa")
581 ("lightslategray" . "#778899")
582 ("lightslategrey" . "#778899")
583 ("lightsteelblue" . "#b0c4de")
584 ("lightyellow" . "#ffffe0")
585 ("limegreen" . "#32cd32")
586 ("linen" . "#faf0e6")
587 ("mediumaquamarine" . "#66cdaa")
588 ("mediumblue" . "#0000cd")
589 ("mediumorchid" . "#ba55d3")
590 ("mediumpurple" . "#9370db")
591 ("mediumseagreen" . "#3cb371")
592 ("mediumslateblue" . "#7b68ee")
593 ("mediumspringgreen" . "#00fa9a")
594 ("mediumturquoise" . "#48d1cc")
595 ("mediumvioletred" . "#c71585")
596 ("midnightblue" . "#191970")
597 ("mintcream" . "#f5fffa")
598 ("mistyrose" . "#ffe4e1")
599 ("moccasin" . "#ffe4b5")
600 ("navajowhite" . "#ffdead")
601 ("oldlace" . "#fdf5e6")
602 ("olivedrab" . "#6b8e23")
603 ("orangered" . "#ff4500")
604 ("orchid" . "#da70d6")
605 ("palegoldenrod" . "#eee8aa")
606 ("palegreen" . "#98fb98")
607 ("paleturquoise" . "#afeeee")
608 ("palevioletred" . "#db7093")
609 ("papayawhip" . "#ffefd5")
610 ("peachpuff" . "#ffdab9")
611 ("peru" . "#cd853f")
612 ("pink" . "#ffc0cb")
613 ("plum" . "#dda0dd")
614 ("powderblue" . "#b0e0e6")
615 ("rosybrown" . "#bc8f8f")
616 ("royalblue" . "#4169e1")
617 ("saddlebrown" . "#8b4513")
618 ("salmon" . "#fa8072")
619 ("sandybrown" . "#f4a460")
620 ("seagreen" . "#2e8b57")
621 ("seashell" . "#fff5ee")
622 ("sienna" . "#a0522d")
623 ("skyblue" . "#87ceeb")
624 ("slateblue" . "#6a5acd")
625 ("slategray" . "#708090")
626 ("slategrey" . "#708090")
627 ("snow" . "#fffafa")
628 ("springgreen" . "#00ff7f")
629 ("steelblue" . "#4682b4")
630 ("tan" . "#d2b48c")
631 ("thistle" . "#d8bfd8")
632 ("tomato" . "#ff6347")
633 ("turquoise" . "#40e0d0")
634 ("violet" . "#ee82ee")
635 ("wheat" . "#f5deb3")
636 ("whitesmoke" . "#f5f5f5")
637 ("yellowgreen" . "#9acd32")
638 ("rebeccapurple" . "#663399"))
639 "Map CSS named colors to their hex RGB value.")
641 (defconst css-value-class-alist
642 `((absolute-size
643 "xx-small" "x-small" "small" "medium" "large" "x-large"
644 "xx-large")
645 (alphavalue number)
646 (angle "calc()")
647 (animateable-feature "scroll-position" "contents" custom-ident)
648 (attachment "scroll" "fixed" "local")
649 (auto-repeat "repeat()")
650 (auto-track-list line-names fixed-size fixed-repeat auto-repeat)
651 (bg-image image "none")
652 (bg-layer bg-image position repeat-style attachment box)
653 (bg-size length percentage "auto" "cover" "contain")
654 (box "border-box" "padding-box" "content-box")
655 (color
656 "rgb()" "rgba()" "hsl()" "hsla()" named-color "transparent"
657 "currentColor")
658 (common-lig-values "common-ligatures" "no-common-ligatures")
659 (contextual-alt-values "contextual" "no-contextual")
660 (counter "counter()" "counters()")
661 (discretionary-lig-values
662 "discretionary-ligatures" "no-discretionary-ligatures")
663 (east-asian-variant-values
664 "jis78" "jis83" "jis90" "jis04" "simplified" "traditional")
665 (east-asian-width-values "full-width" "proportional-width")
666 (explicit-track-list line-names track-size)
667 (family-name "Courier" "Helvetica" "Times")
668 (feature-tag-value string integer "on" "off")
669 (filter-function
670 "blur()" "brightness()" "contrast()" "drop-shadow()"
671 "grayscale()" "hue-rotate()" "invert()" "opacity()" "sepia()"
672 "saturate()")
673 (filter-function-list filter-function uri)
674 (final-bg-layer
675 bg-image position repeat-style attachment box color)
676 (fixed-breadth length-percentage)
677 (fixed-repeat "repeat()")
678 (fixed-size fixed-breadth "minmax()")
679 (font-variant-css21 "normal" "small-caps")
680 (frequency "calc()")
681 (generic-family
682 "serif" "sans-serif" "cursive" "fantasy" "monospace")
683 (generic-voice "male" "female" "child")
684 (gradient
685 linear-gradient radial-gradient repeating-linear-gradient
686 repeating-radial-gradient)
687 (grid-line "auto" custom-ident integer "span")
688 (historical-lig-values
689 "historical-ligatures" "no-historical-ligatures")
690 (image uri image-list element-reference gradient)
691 (image-list "image()")
692 (inflexible-breadth length-percentage "min-content" "max-content"
693 "auto")
694 (integer "calc()")
695 (length "calc()" number)
696 (line-height "normal" number length percentage)
697 (line-names custom-ident)
698 (line-style
699 "none" "hidden" "dotted" "dashed" "solid" "double" "groove"
700 "ridge" "inset" "outset")
701 (line-width length "thin" "medium" "thick")
702 (linear-gradient "linear-gradient()")
703 (margin-width "auto" length percentage)
704 (named-color . ,(mapcar #'car css--color-map))
705 (number "calc()")
706 (numeric-figure-values "lining-nums" "oldstyle-nums")
707 (numeric-fraction-values "diagonal-fractions" "stacked-fractions")
708 (numeric-spacing-values "proportional-nums" "tabular-nums")
709 (padding-width length percentage)
710 (position
711 "left" "center" "right" "top" "bottom" percentage length)
712 (radial-gradient "radial-gradient()")
713 (relative-size "larger" "smaller")
714 (repeat-style
715 "repeat-x" "repeat-y" "repeat" "space" "round" "no-repeat")
716 (repeating-linear-gradient "repeating-linear-gradient()")
717 (repeating-radial-gradient "repeating-radial-gradient()")
718 (shadow "inset" length color)
719 (shape "rect()")
720 (single-animation-direction
721 "normal" "reverse" "alternate" "alternate-reverse")
722 (single-animation-fill-mode "none" "forwards" "backwards" "both")
723 (single-animation-iteration-count "infinite" number)
724 (single-animation-name "none" identifier)
725 (single-animation-play-state "running" "paused")
726 (single-timing-function single-transition-timing-function)
727 (single-transition
728 "none" single-transition-property time
729 single-transition-timing-function)
730 (single-transition-property "all" identifier)
731 (single-transition-timing-function
732 "ease" "linear" "ease-in" "ease-out" "ease-in-out" "step-start"
733 "step-end" "steps()" "cubic-bezier()")
734 (specific-voice identifier)
735 (target-name string)
736 (time "calc()")
737 (track-breadth length-percentage flex "min-content" "max-content"
738 "auto")
739 (track-list line-names track-size track-repeat)
740 (track-repeat "repeat()")
741 (track-size track-breadth "minmax()" "fit-content()")
742 (transform-list
743 "matrix()" "translate()" "translateX()" "translateY()" "scale()"
744 "scaleX()" "scaleY()" "rotate()" "skew()" "skewX()" "skewY()"
745 "matrix3d()" "translate3d()" "translateZ()" "scale3d()"
746 "scaleZ()" "rotate3d()" "rotateX()" "rotateY()" "rotateZ()"
747 "perspective()")
748 (uri "url()")
749 (width length percentage "auto")
750 (x number)
751 (y number))
752 "Property value classes and their values.
753 The format is similar to that of `css-property-alist', except
754 that the CARs aren't actual CSS properties, but rather a name for
755 a class of values, and that symbols in the CDRs always refer to
756 other entries in this list, not to properties.
758 The following classes have been left out above because they
759 cannot be completed sensibly: `custom-ident',
760 `element-reference', `flex', `id', `identifier',
761 `length-percentage', `percentage', and `string'.")
763 (defcustom css-electric-keys '(?\} ?\;) ;; '()
764 "Self inserting keys which should trigger re-indentation."
765 :version "22.2"
766 :type '(repeat character)
767 :group 'css)
769 (defvar css-mode-syntax-table
770 (let ((st (make-syntax-table)))
771 ;; C-style comments.
772 (modify-syntax-entry ?/ ". 14" st)
773 (modify-syntax-entry ?* ". 23b" st)
774 ;; Strings.
775 (modify-syntax-entry ?\" "\"" st)
776 (modify-syntax-entry ?\' "\"" st)
777 ;; Blocks.
778 (modify-syntax-entry ?\{ "(}" st)
779 (modify-syntax-entry ?\} "){" st)
780 ;; Args in url(...) thingies and other "function calls".
781 (modify-syntax-entry ?\( "()" st)
782 (modify-syntax-entry ?\) ")(" st)
783 ;; To match attributes in selectors.
784 (modify-syntax-entry ?\[ "(]" st)
785 (modify-syntax-entry ?\] ")[" st)
786 ;; Special chars that sometimes come at the beginning of words.
787 ;; We'll treat them as symbol constituents.
788 (modify-syntax-entry ?@ "_" st)
789 (modify-syntax-entry ?# "_" st)
790 (modify-syntax-entry ?. "_" st)
791 ;; Distinction between words and symbols.
792 (modify-syntax-entry ?- "_" st)
794 (modify-syntax-entry ?! "." st)
795 (modify-syntax-entry ?$ "." st)
796 (modify-syntax-entry ?% "." st)
797 (modify-syntax-entry ?& "." st)
798 (modify-syntax-entry ?+ "." st)
799 (modify-syntax-entry ?, "." st)
800 (modify-syntax-entry ?< "." st)
801 (modify-syntax-entry ?> "." st)
802 (modify-syntax-entry ?= "." st)
803 (modify-syntax-entry ?? "." st)
804 st))
806 (defvar css-mode-map
807 (let ((map (make-sparse-keymap)))
808 (define-key map [remap info-lookup-symbol] 'css-lookup-symbol)
809 map)
810 "Keymap used in `css-mode'.")
812 (eval-and-compile
813 (defconst css--uri-re
814 (concat
815 "url\\((\\)[[:space:]]*\\(?:\\\\.\\|[^()[:space:]\n'\"]\\)+"
816 "[[:space:]]*\\()\\)")))
818 (defconst css-syntax-propertize-function
819 (syntax-propertize-rules
820 (css--uri-re (1 "|") (2 "|"))))
822 (defconst css-escapes-re
823 "\\\\\\(?:[^\000-\037\177]\\|[0-9a-fA-F]+[ \n\t\r\f]?\\)")
824 (defconst css-nmchar-re (concat "\\(?:[-[:alnum:]]\\|" css-escapes-re "\\)"))
825 (defconst css-nmstart-re (concat "\\(?:[[:alpha:]]\\|" css-escapes-re "\\)"))
826 (defconst css-ident-re ;; (concat css-nmstart-re css-nmchar-re "*")
827 ;; Apparently, "at rules" names can start with a dash, e.g. @-moz-keyframes.
828 (concat css-nmchar-re "+"))
829 (defconst css-proprietary-nmstart-re ;; Vendor-specific properties.
830 (concat "[-_]" (regexp-opt '("ms" "moz" "o" "khtml" "webkit")) "-"))
831 (defconst css-name-re (concat css-nmchar-re "+"))
833 (defconst scss--hash-re "#\\(?:{[$-_[:alnum:]]+}\\|[[:alnum:]]+\\)")
835 (defface css-selector '((t :inherit font-lock-function-name-face))
836 "Face to use for selectors."
837 :group 'css)
838 (defface css-property '((t :inherit font-lock-keyword-face))
839 "Face to use for properties."
840 :group 'css)
841 (defface css-proprietary-property '((t :inherit (css-property italic)))
842 "Face to use for vendor-specific properties.")
844 (defun css--font-lock-keywords (&optional sassy)
845 `((,(concat "!\\s-*" (regexp-opt css--bang-ids))
846 (0 font-lock-builtin-face))
847 ;; Atrules keywords. IDs not in css-at-ids are valid (ignored).
848 ;; In fact the regexp should probably be
849 ;; (,(concat "\\(@" css-ident-re "\\)\\([ \t\n][^;{]*\\)[;{]")
850 ;; (1 font-lock-builtin-face))
851 ;; Since "An at-rule consists of everything up to and including the next
852 ;; semicolon (;) or the next block, whichever comes first."
853 (,(concat "@" css-ident-re) (0 font-lock-builtin-face))
854 ;; Selectors.
855 ;; Allow plain ":root" as a selector.
856 ("^[ \t]*\\(:root\\)\\(?:[\n \t]*\\)*{" (1 'css-selector keep))
857 ;; FIXME: attribute selectors don't work well because they may contain
858 ;; strings which have already been highlighted as f-l-string-face and
859 ;; thus prevent this highlighting from being applied (actually now that
860 ;; I use `keep' this should work better). But really the part of the
861 ;; selector between [...] should simply not be highlighted.
862 (,(concat
863 "^[ \t]*\\("
864 (if (not sassy)
865 ;; We don't allow / as first char, so as not to
866 ;; take a comment as the beginning of a selector.
867 "[^@/:{}() \t\n][^:{}()]*"
868 ;; Same as for non-sassy except we do want to allow { and }
869 ;; chars in selectors in the case of #{$foo}
870 ;; variable interpolation!
871 (concat "\\(?:" scss--hash-re
872 "\\|[^@/:{}() \t\n#]\\)"
873 "[^:{}()#]*\\(?:" scss--hash-re "[^:{}()#]*\\)*"))
874 ;; Even though pseudo-elements should be prefixed by ::, a
875 ;; single colon is accepted for backward compatibility.
876 "\\(?:\\(:" (regexp-opt (append css-pseudo-class-ids
877 css-pseudo-element-ids)
879 "\\|\\::" (regexp-opt css-pseudo-element-ids t) "\\)"
880 "\\(?:([^)]+)\\)?"
881 (if (not sassy)
882 "[^:{}()\n]*"
883 (concat "[^:{}()\n#]*\\(?:" scss--hash-re "[^:{}()\n#]*\\)*"))
884 "\\)*"
885 "\\)\\(?:\n[ \t]*\\)*{")
886 (1 'css-selector keep))
887 ;; In the above rule, we allow the open-brace to be on some subsequent
888 ;; line. This will only work if we properly mark the intervening text
889 ;; as being part of a multiline element (and even then, this only
890 ;; ensures proper refontification, but not proper discovery).
891 ("^[ \t]*{" (0 (save-excursion
892 (goto-char (match-beginning 0))
893 (skip-chars-backward " \n\t")
894 (put-text-property (point) (match-end 0)
895 'font-lock-multiline t)
896 ;; No face.
897 nil)))
898 ;; Variables.
899 (,(concat (rx symbol-start) "--" css-ident-re) (0 font-lock-variable-name-face))
900 ;; Properties. Again, we don't limit ourselves to css-property-ids.
901 (,(concat "\\(?:[{;]\\|^\\)[ \t]*\\("
902 "\\(?:\\(" css-proprietary-nmstart-re "\\)\\|"
903 css-nmstart-re "\\)" css-nmchar-re "*"
904 "\\)\\s-*:")
905 (1 (if (match-end 2) 'css-proprietary-property 'css-property)))
906 ;; Make sure the parens in a url(...) expression receive the
907 ;; default face. This is done because the parens may sometimes
908 ;; receive generic string delimiter syntax (see
909 ;; `css-syntax-propertize-function').
910 (,css--uri-re
911 (1 'default t) (2 'default t))))
913 (defvar css-font-lock-keywords (css--font-lock-keywords))
915 (defvar css-font-lock-defaults
916 '(css-font-lock-keywords nil t))
918 (defconst css--number-regexp
919 "\\(\\(?:[0-9]*\\.[0-9]+\\(?:[eE][0-9]+\\)?\\)\\|[0-9]+\\)"
920 "A regular expression matching a CSS number.")
922 (defconst css--percent-regexp "\\([0-9]+\\)%"
923 "A regular expression matching a CSS percentage.")
925 (defconst css--number-or-percent-regexp
926 (concat "\\(?:" css--percent-regexp "\\)\\|\\(?:" css--number-regexp "\\)")
927 "A regular expression matching a CSS number or a CSS percentage.")
929 (defconst css--angle-regexp
930 (concat css--number-regexp
931 (regexp-opt '("deg" "grad" "rad" "turn") t)
932 "?")
933 "A regular expression matching a CSS angle.")
935 (defun css--color-skip-blanks ()
936 "Skip blanks and comments."
937 (while (forward-comment 1)))
939 (cl-defun css--rgb-color ()
940 "Parse a CSS rgb() or rgba() color.
941 Point should be just after the open paren.
942 Returns a hex RGB color, or nil if the color could not be recognized.
943 This recognizes CSS-color-4 extensions."
944 (let ((result '())
945 (iter 0))
946 (while (< iter 4)
947 (css--color-skip-blanks)
948 (unless (looking-at css--number-or-percent-regexp)
949 (cl-return-from css--rgb-color nil))
950 (let* ((is-percent (match-beginning 1))
951 (str (match-string (if is-percent 1 2)))
952 (number (string-to-number str)))
953 (when is-percent
954 (setq number (* 255 (/ number 100.0))))
955 ;; Don't push the alpha.
956 (when (< iter 3)
957 (push (min (max 0 (truncate number)) 255) result))
958 (goto-char (match-end 0))
959 (css--color-skip-blanks)
960 (cl-incf iter)
961 ;; Accept a superset of the CSS syntax since I'm feeling lazy.
962 (when (and (= (skip-chars-forward ",/") 0)
963 (= iter 3))
964 ;; The alpha is optional.
965 (cl-incf iter))
966 (css--color-skip-blanks)))
967 (when (looking-at ")")
968 (forward-char)
969 (apply #'format "#%02x%02x%02x" (nreverse result)))))
971 (cl-defun css--hsl-color ()
972 "Parse a CSS hsl() or hsla() color.
973 Point should be just after the open paren.
974 Returns a hex RGB color, or nil if the color could not be recognized.
975 This recognizes CSS-color-4 extensions."
976 (let ((result '()))
977 ;; First parse the hue.
978 (css--color-skip-blanks)
979 (unless (looking-at css--angle-regexp)
980 (cl-return-from css--hsl-color nil))
981 (let ((hue (string-to-number (match-string 1)))
982 (unit (match-string 2)))
983 (goto-char (match-end 0))
984 ;; Note that here "turn" is just passed through.
985 (cond
986 ((or (not unit) (equal unit "deg"))
987 ;; Degrees.
988 (setq hue (/ hue 360.0)))
989 ((equal unit "grad")
990 (setq hue (/ hue 400.0)))
991 ((equal unit "rad")
992 (setq hue (/ hue (* 2 float-pi)))))
993 (push (mod hue 1.0) result))
994 (dotimes (_ 2)
995 (skip-chars-forward ",")
996 (css--color-skip-blanks)
997 (unless (looking-at css--percent-regexp)
998 (cl-return-from css--hsl-color nil))
999 (let ((number (string-to-number (match-string 1))))
1000 (setq number (/ number 100.0))
1001 (push (min (max number 0.0) 1.0) result)
1002 (goto-char (match-end 0))
1003 (css--color-skip-blanks)))
1004 (css--color-skip-blanks)
1005 ;; Accept a superset of the CSS syntax since I'm feeling lazy.
1006 (when (> (skip-chars-forward ",/") 0)
1007 (css--color-skip-blanks)
1008 (unless (looking-at css--number-or-percent-regexp)
1009 (cl-return-from css--hsl-color nil))
1010 (goto-char (match-end 0))
1011 (css--color-skip-blanks))
1012 (when (looking-at ")")
1013 (forward-char)
1014 (apply #'color-rgb-to-hex
1015 (nconc (apply #'color-hsl-to-rgb (nreverse result)) '(2))))))
1017 (defconst css--colors-regexp
1018 (concat
1019 ;; Named colors.
1020 (regexp-opt (mapcar #'car css--color-map) 'symbols)
1021 "\\|"
1022 ;; Short hex. css-color-4 adds alpha.
1023 "\\(#[0-9a-fA-F]\\{3,4\\}\\b\\)"
1024 "\\|"
1025 ;; Long hex. css-color-4 adds alpha.
1026 "\\(#\\(?:[0-9a-fA-F][0-9a-fA-F]\\)\\{3,4\\}\\b\\)"
1027 "\\|"
1028 ;; RGB.
1029 "\\(\\_<rgba?(\\)"
1030 "\\|"
1031 ;; HSL.
1032 "\\(\\_<hsla?(\\)")
1033 "A regular expression that matches the start of a CSS color.")
1035 (defun css--hex-color (str)
1036 "Convert a CSS hex color to an Emacs hex color.
1037 STR is the incoming CSS hex color.
1038 This function simply drops any transparency."
1039 ;; Either #RGB or #RRGGBB, drop the "A" or "AA".
1040 (substring str 0 (if (> (length str) 5) 7 4)))
1042 (defun css--named-color (start-point str)
1043 "Check whether STR, seen at point, is CSS named color.
1044 Returns STR if it is a valid color. Special care is taken
1045 to exclude some SCSS constructs."
1046 (when-let* ((color (assoc str css--color-map)))
1047 (save-excursion
1048 (goto-char start-point)
1049 (forward-comment (- (point)))
1050 (skip-chars-backward "@[:alpha:]")
1051 (unless (looking-at-p "@\\(mixin\\|include\\)")
1052 (cdr color)))))
1054 (defun css--compute-color (start-point match)
1055 "Return the CSS color at point.
1056 Point should be just after the start of a CSS color, as recognized
1057 by `css--colors-regexp'. START-POINT is the start of the color,
1058 and MATCH is the string matched by the regexp.
1060 This function will either return the color, as a hex RGB string;
1061 or `nil' if no color could be recognized. When this function
1062 returns, point will be at the end of the recognized color."
1063 (cond
1064 ((eq (aref match 0) ?#)
1065 (css--hex-color match))
1066 ((member match '("rgb(" "rgba("))
1067 (css--rgb-color))
1068 ((member match '("hsl(" "hsla("))
1069 (css--hsl-color))
1070 ;; Evaluate to the color if the name is found.
1071 ((css--named-color start-point match))))
1073 (defun css--contrasty-color (name)
1074 "Return a color that contrasts with NAME.
1075 NAME is of any form accepted by `color-distance'.
1076 The returned color will be usable by Emacs and will contrast
1077 with NAME; in particular so that if NAME is used as a background
1078 color, the returned color can be used as the foreground and still
1079 be readable."
1080 ;; See bug#25525 for a discussion of this.
1081 (if (> (color-distance name "black") 292485)
1082 "black" "white"))
1084 (defcustom css-fontify-colors t
1085 "Whether CSS colors should be fontified using the color as the background.
1086 When non-`nil', a text representing CSS color will be fontified
1087 such that its background is the color itself. E.g., #ff0000 will
1088 be fontified with a red background."
1089 :version "26.1"
1090 :group 'css
1091 :type 'boolean
1092 :safe 'booleanp)
1094 (defun css--fontify-region (start end &optional loudly)
1095 "Fontify a CSS buffer between START and END.
1096 START and END are buffer positions."
1097 (let ((extended-region (font-lock-default-fontify-region start end loudly)))
1098 (when css-fontify-colors
1099 (when (and (consp extended-region)
1100 (eq (car extended-region) 'jit-lock-bounds))
1101 (setq start (cadr extended-region))
1102 (setq end (cddr extended-region)))
1103 (save-excursion
1104 (let ((case-fold-search t))
1105 (goto-char start)
1106 (while (re-search-forward css--colors-regexp end t)
1107 ;; Skip comments and strings.
1108 (unless (nth 8 (syntax-ppss))
1109 (let* ((start (match-beginning 0))
1110 (color (css--compute-color start (match-string 0))))
1111 (when color
1112 (with-silent-modifications
1113 ;; Use the color as the background, to make it more
1114 ;; clear. Use a contrasting color as the foreground,
1115 ;; to make it readable. Finally, have a small box
1116 ;; using the existing foreground color, to make sure
1117 ;; it stands out a bit from any other text; in
1118 ;; particular this is nice when the color matches the
1119 ;; buffer's background color.
1120 (add-text-properties
1121 start (point)
1122 (list 'face (list :background color
1123 :foreground (css--contrasty-color color)
1124 :box '(:line-width -1))))))))))))
1125 extended-region))
1127 (defcustom css-indent-offset 4
1128 "Basic size of one indentation step."
1129 :version "22.2"
1130 :type 'integer
1131 :safe 'integerp)
1133 (defconst css-smie-grammar
1134 (smie-prec2->grammar
1135 (smie-precs->prec2
1136 '((assoc ";")
1137 ;; Colons that belong to a CSS property. These get a higher
1138 ;; precedence than other colons, such as colons in selectors,
1139 ;; which are represented by a plain ":" token.
1140 (left ":-property")
1141 (assoc ",")
1142 (assoc ":")))))
1144 (defun css--colon-inside-selector-p ()
1145 "Return t if point looks to be inside a CSS selector.
1146 This function is intended to be good enough to help SMIE during
1147 tokenization, but should not be regarded as a reliable function
1148 for determining whether point is within a selector."
1149 (save-excursion
1150 (re-search-forward "[{};]" nil t)
1151 (eq (char-before) ?\{)))
1153 (defun css--colon-inside-funcall ()
1154 "Return t if point is inside a function call."
1155 (when-let* ((opening-paren-pos (nth 1 (syntax-ppss))))
1156 (save-excursion
1157 (goto-char opening-paren-pos)
1158 (eq (char-after) ?\())))
1160 (defun css-smie--forward-token ()
1161 (cond
1162 ((and (eq (char-before) ?\})
1163 (scss-smie--not-interpolation-p)
1164 ;; FIXME: If the next char is not whitespace, what should we do?
1165 (or (memq (char-after) '(?\s ?\t ?\n))
1166 (looking-at comment-start-skip)))
1167 (if (memq (char-after) '(?\s ?\t ?\n))
1168 (forward-char 1) (forward-comment 1))
1169 ";")
1170 ((progn (forward-comment (point-max))
1171 (looking-at "[;,:]"))
1172 (forward-char 1)
1173 (if (equal (match-string 0) ":")
1174 (if (or (css--colon-inside-selector-p)
1175 (css--colon-inside-funcall))
1177 ":-property")
1178 (match-string 0)))
1179 (t (smie-default-forward-token))))
1181 (defun css-smie--backward-token ()
1182 (let ((pos (point)))
1183 (forward-comment (- (point)))
1184 (cond
1185 ;; FIXME: If the next char is not whitespace, what should we do?
1186 ((and (eq (char-before) ?\}) (scss-smie--not-interpolation-p)
1187 (> pos (point))) ";")
1188 ((memq (char-before) '(?\; ?\, ?\:))
1189 (forward-char -1)
1190 (if (eq (char-after) ?\:)
1191 (if (or (css--colon-inside-selector-p)
1192 (css--colon-inside-funcall))
1194 ":-property")
1195 (string (char-after))))
1196 (t (smie-default-backward-token)))))
1198 (defun css-smie-rules (kind token)
1199 (pcase (cons kind token)
1200 (`(:elem . basic) css-indent-offset)
1201 (`(:elem . arg) 0)
1202 (`(:list-intro . ,(or `";" `"")) t) ;"" stands for BOB (bug#15467).
1203 (`(:before . "{")
1204 (when (or (smie-rule-hanging-p) (smie-rule-bolp))
1205 (smie-backward-sexp ";")
1206 (unless (eq (char-after) ?\{)
1207 (smie-indent-virtual))))
1208 (`(:before . "(")
1209 (cond
1210 ((smie-rule-hanging-p) (smie-rule-parent 0))
1211 ((not (smie-rule-bolp)) 0)))
1212 (`(:after . ":-property")
1213 (when (smie-rule-hanging-p)
1214 css-indent-offset))))
1216 ;;; Completion
1218 (defun css--complete-property ()
1219 "Complete property at point."
1220 (save-excursion
1221 (let ((pos (point)))
1222 (skip-chars-backward "-[:alnum:]")
1223 (let ((start (point)))
1224 (skip-chars-backward " \t\r\n")
1225 (when (memq (char-before) '(?\{ ?\;))
1226 (list start pos css-property-ids))))))
1228 (defun css--complete-bang-rule ()
1229 "Complete bang-rule at point."
1230 (save-excursion
1231 (let ((pos (point)))
1232 (skip-chars-backward "-[:alnum:]")
1233 (when (eq (char-before) ?\!)
1234 (list (point) pos css--bang-ids)))))
1236 (defun css--complete-pseudo-element-or-class ()
1237 "Complete pseudo-element or pseudo-class at point."
1238 (save-excursion
1239 (let ((pos (point)))
1240 (skip-chars-backward "-[:alnum:]")
1241 (when (eq (char-before) ?\:)
1242 (list (point) pos
1243 (if (eq (char-before (- (point) 1)) ?\:)
1244 css-pseudo-element-ids
1245 css-pseudo-class-ids))))))
1247 (defun css--complete-at-rule ()
1248 "Complete at-rule (statement beginning with `@') at point."
1249 (save-excursion
1250 (let ((pos (point)))
1251 (skip-chars-backward "-[:alnum:]")
1252 (when (eq (char-before) ?\@)
1253 (list (point) pos css--at-ids)))))
1255 (defvar css--property-value-cache
1256 (make-hash-table :test 'equal :size (length css-property-alist))
1257 "Cache of previously completed property values.")
1259 (defun css--value-class-lookup (value-class)
1260 "Return a list of value completion candidates for VALUE-CLASS.
1261 Completion candidates are looked up in `css-value-class-alist' by
1262 the symbol VALUE-CLASS."
1263 (seq-uniq
1264 (seq-mapcat
1265 (lambda (value)
1266 (if (stringp value)
1267 (list value)
1268 (css--value-class-lookup value)))
1269 (cdr (assq value-class css-value-class-alist)))))
1271 (defun css--property-values (property)
1272 "Return a list of value completion candidates for PROPERTY.
1273 Completion candidates are looked up in `css-property-alist' by
1274 the string PROPERTY."
1275 (or (gethash property css--property-value-cache)
1276 (let ((values
1277 (seq-uniq
1278 (seq-mapcat
1279 (lambda (value)
1280 (if (stringp value)
1281 (list value)
1282 (or (css--value-class-lookup value)
1283 (css--property-values (symbol-name value)))))
1284 (cdr (assoc property css-property-alist))))))
1285 (puthash property values css--property-value-cache))))
1287 (defun css--complete-property-value ()
1288 "Complete property value at point."
1289 (let ((property
1290 (save-excursion
1291 (re-search-backward ":[^/]" (line-beginning-position) t)
1292 (when (eq (char-after) ?:)
1293 (let ((property-end (point)))
1294 (skip-chars-backward "-[:alnum:]")
1295 (let ((prop (buffer-substring (point) property-end)))
1296 (car (member prop css-property-ids))))))))
1297 (when property
1298 (let ((end (point)))
1299 (save-excursion
1300 (skip-chars-backward "[:graph:]")
1301 (list (point) end
1302 (append '("inherit" "initial" "unset")
1303 (css--property-values property))))))))
1305 (defvar css--html-tags (mapcar #'car html-tag-alist)
1306 "List of HTML tags.
1307 Used to provide completion of HTML tags in selectors.")
1309 (defvar css--nested-selectors-allowed nil
1310 "Non-nil if nested selectors are allowed in the current mode.")
1311 (make-variable-buffer-local 'css--nested-selectors-allowed)
1313 (defvar css-class-list-function #'ignore
1314 "Called to provide completions of class names.
1315 This can be bound by buffers that are able to suggest class name
1316 completions, such as HTML mode buffers.")
1318 (defvar css-id-list-function #'ignore
1319 "Called to provide completions of IDs.
1320 This can be bound by buffers that are able to suggest ID
1321 completions, such as HTML mode buffers.")
1323 (defun css--foreign-completions (extractor)
1324 "Return a list of completions provided by other buffers.
1325 EXTRACTOR should be the name of a function that may be defined in
1326 one or more buffers. In each of the buffers where EXTRACTOR is
1327 defined, EXTRACTOR is called and the results are accumulated into
1328 a list of completions."
1329 (delete-dups
1330 (seq-mapcat
1331 (lambda (buf)
1332 (with-current-buffer buf
1333 (funcall (symbol-value extractor))))
1334 (buffer-list))))
1336 (defun css--complete-selector ()
1337 "Complete part of a CSS selector at point."
1338 (when (or (= (nth 0 (syntax-ppss)) 0) css--nested-selectors-allowed)
1339 (let ((end (point)))
1340 (save-excursion
1341 (skip-chars-backward "-[:alnum:]")
1342 (let ((start-char (char-before)))
1343 (list
1344 (point) end
1345 (completion-table-dynamic
1346 (lambda (_)
1347 (cond
1348 ((eq start-char ?.)
1349 (css--foreign-completions 'css-class-list-function))
1350 ((eq start-char ?#)
1351 (css--foreign-completions 'css-id-list-function))
1352 (t css--html-tags))))))))))
1354 (defun css-completion-at-point ()
1355 "Complete current symbol at point.
1356 Currently supports completion of CSS properties, property values,
1357 pseudo-elements, pseudo-classes, at-rules, bang-rules, and HTML
1358 tags, classes and IDs."
1359 (or (css--complete-bang-rule)
1360 (css--complete-property-value)
1361 (css--complete-pseudo-element-or-class)
1362 (css--complete-at-rule)
1363 (seq-let (prop-beg prop-end prop-table) (css--complete-property)
1364 (seq-let (sel-beg sel-end sel-table) (css--complete-selector)
1365 (when (or prop-table sel-table)
1366 ;; FIXME: If both prop-table and sel-table are set but
1367 ;; prop-beg/prop-end is different from sel-beg/sel-end
1368 ;; we have a problem!
1369 `(,@(if prop-table
1370 (list prop-beg prop-end)
1371 (list sel-beg sel-end))
1372 ,(completion-table-merge prop-table sel-table)
1373 :exit-function
1374 ,(lambda (string status)
1375 (and (eq status 'finished)
1376 (eolp)
1377 prop-table
1378 (test-completion string prop-table)
1379 (not (and sel-table
1380 (test-completion string sel-table)))
1381 (progn (insert ": ;")
1382 (forward-char -1))))))))))
1384 ;;;###autoload
1385 (define-derived-mode css-mode prog-mode "CSS"
1386 "Major mode to edit Cascading Style Sheets (CSS).
1387 \\<css-mode-map>
1388 This mode provides syntax highlighting, indentation, completion,
1389 and documentation lookup for CSS.
1391 Use `\\[complete-symbol]' to complete CSS properties, property values,
1392 pseudo-elements, pseudo-classes, at-rules, bang-rules, and HTML
1393 tags, classes and IDs. Completion candidates for HTML class
1394 names and IDs are found by looking through open HTML mode
1395 buffers.
1397 Use `\\[info-lookup-symbol]' to look up documentation of CSS properties, at-rules,
1398 pseudo-classes, and pseudo-elements on the Mozilla Developer
1399 Network (MDN).
1401 \\{css-mode-map}"
1402 (setq-local font-lock-defaults css-font-lock-defaults)
1403 (setq-local comment-start "/*")
1404 (setq-local comment-start-skip "/\\*+[ \t]*")
1405 (setq-local comment-end "*/")
1406 (setq-local comment-end-skip "[ \t]*\\*+/")
1407 (setq-local syntax-propertize-function
1408 css-syntax-propertize-function)
1409 (setq-local fill-paragraph-function #'css-fill-paragraph)
1410 (setq-local adaptive-fill-function #'css-adaptive-fill)
1411 (setq-local add-log-current-defun-function #'css-current-defun-name)
1412 (smie-setup css-smie-grammar #'css-smie-rules
1413 :forward-token #'css-smie--forward-token
1414 :backward-token #'css-smie--backward-token)
1415 (setq-local electric-indent-chars
1416 (append css-electric-keys electric-indent-chars))
1417 (setq-local font-lock-fontify-region-function #'css--fontify-region)
1418 (add-hook 'completion-at-point-functions
1419 #'css-completion-at-point nil 'local))
1421 (defvar comment-continue)
1423 (defun css-fill-paragraph (&optional justify)
1424 (save-excursion
1425 ;; Fill succeeding comment when invoked right before a multi-line
1426 ;; comment.
1427 (when (save-excursion
1428 (beginning-of-line)
1429 (comment-search-forward (point-at-eol) t))
1430 (goto-char (match-end 0)))
1431 (let ((ppss (syntax-ppss))
1432 (eol (line-end-position)))
1433 (cond
1434 ((and (nth 4 ppss)
1435 (save-excursion
1436 (goto-char (nth 8 ppss))
1437 (forward-comment 1)
1438 (prog1 (not (bolp))
1439 (setq eol (point)))))
1440 ;; Filling inside a comment whose comment-end marker is not \n.
1441 ;; This code is meant to be generic, so that it works not only for
1442 ;; css-mode but for all modes.
1443 (save-restriction
1444 (narrow-to-region (nth 8 ppss) eol)
1445 (comment-normalize-vars) ;Will define comment-continue.
1446 (let ((fill-paragraph-function nil)
1447 (paragraph-separate
1448 (if (and comment-continue
1449 (string-match "[^ \t]" comment-continue))
1450 (concat "\\(?:[ \t]*\\(?:"
1451 (regexp-quote comment-continue) "\\|"
1452 comment-start-skip "\\|"
1453 comment-end-skip "\\)\\)?"
1454 "\\(?:" paragraph-separate "\\)")
1455 paragraph-separate))
1456 (paragraph-start
1457 (if (and comment-continue
1458 (string-match "[^ \t]" comment-continue))
1459 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
1460 "\\)?\\(?:" paragraph-start "\\)")
1461 paragraph-start)))
1462 (fill-paragraph justify)
1463 ;; Don't try filling again.
1464 t)))
1466 ((and (null (nth 8 ppss))
1467 (or (nth 1 ppss)
1468 (and (ignore-errors
1469 (down-list 1)
1470 (when (<= (point) eol)
1471 (setq ppss (syntax-ppss)))))))
1472 (goto-char (nth 1 ppss))
1473 (let ((end (save-excursion
1474 (ignore-errors (forward-sexp 1) (copy-marker (point) t)))))
1475 (when end
1476 (while (re-search-forward "[{;}]" end t)
1477 (cond
1478 ;; This is a false positive inside a string or comment.
1479 ((nth 8 (syntax-ppss)) nil)
1480 ;; This is a false positive when encountering an
1481 ;; interpolated variable (bug#19751).
1482 ((eq (char-before (- (point) 1)) ?#) nil)
1483 ((eq (char-before) ?\})
1484 (save-excursion
1485 (forward-char -1)
1486 (skip-chars-backward " \t")
1487 (when (and (not (bolp))
1488 (scss-smie--not-interpolation-p))
1489 (newline))))
1491 (while
1492 (progn
1493 (setq eol (line-end-position))
1494 (and (forward-comment 1)
1495 (> (point) eol)
1496 ;; A multi-line comment should be on its own line.
1497 (save-excursion (forward-comment -1)
1498 (when (< (point) eol)
1499 (newline)
1500 t)))))
1501 (if (< (point) eol) (newline)))))
1502 (goto-char (nth 1 ppss))
1503 (indent-region (line-beginning-position 2) end)
1504 ;; Don't use the default filling code.
1505 t)))))))
1507 (defun css-adaptive-fill ()
1508 (when (looking-at "[ \t]*/\\*[ \t]*")
1509 (let ((str (match-string 0)))
1510 (and (string-match "/\\*" str)
1511 (replace-match " *" t t str)))))
1513 (defun css-current-defun-name ()
1514 "Return the name of the CSS section at point, or nil."
1515 (save-excursion
1516 (let ((max (max (point-min) (- (point) 1600)))) ; approx 20 lines back
1517 (when (search-backward "{" max t)
1518 (skip-chars-backward " \t\r\n")
1519 (beginning-of-line)
1520 (if (looking-at "^[ \t]*\\([^{\r\n]*[^ {\t\r\n]\\)")
1521 (match-string-no-properties 1))))))
1523 ;;; SCSS mode
1525 (defvar scss-mode-syntax-table
1526 (let ((st (make-syntax-table css-mode-syntax-table)))
1527 (modify-syntax-entry ?/ ". 124" st)
1528 (modify-syntax-entry ?\n ">" st)
1529 ;; Variable names are prefixed by $.
1530 (modify-syntax-entry ?$ "_" st)
1531 (modify-syntax-entry ?% "_" st)
1532 st))
1534 (defun scss-font-lock-keywords ()
1535 (append `((,(concat "$" css-ident-re) (0 font-lock-variable-name-face)))
1536 (css--font-lock-keywords 'sassy)
1537 `((,(concat "@mixin[ \t]+\\(" css-ident-re "\\)[ \t]*(")
1538 (1 font-lock-function-name-face)))))
1540 (defun scss-smie--not-interpolation-p ()
1541 (save-excursion
1542 (forward-char -1)
1543 (or (zerop (skip-chars-backward "-[:alnum:]"))
1544 (not (looking-back "#{\\$" (- (point) 3))))))
1546 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.scss\\'" . scss-mode))
1547 ;;;###autoload
1548 (define-derived-mode scss-mode css-mode "SCSS"
1549 "Major mode to edit \"Sassy CSS\" files."
1550 (setq-local comment-start "// ")
1551 (setq-local comment-end "")
1552 (setq-local comment-continue " *")
1553 (setq-local comment-start-skip "/[*/]+[ \t]*")
1554 (setq-local comment-end-skip "[ \t]*\\(?:\n\\|\\*+/\\)")
1555 (setq-local css--at-ids (append css-at-ids scss-at-ids))
1556 (setq-local css--bang-ids (append css-bang-ids scss-bang-ids))
1557 (setq-local css--nested-selectors-allowed t)
1558 (setq-local font-lock-defaults
1559 (list (scss-font-lock-keywords) nil t)))
1563 (defvar css--mdn-lookup-history nil)
1565 (defcustom css-lookup-url-format
1566 "https://developer.mozilla.org/en-US/docs/Web/CSS/%s?raw&macros"
1567 "Format for a URL where CSS documentation can be found.
1568 The format should include a single \"%s\" substitution.
1569 The name of the CSS property, @-id, pseudo-class, or pseudo-element
1570 to look up will be substituted there."
1571 :version "26.1"
1572 :type 'string
1573 :group 'css)
1575 (defun css--mdn-after-render ()
1576 (setf header-line-format nil)
1577 (goto-char (point-min))
1578 (let ((window (get-buffer-window (current-buffer) 'visible)))
1579 (when window
1580 (when (re-search-forward "^\\(Summary\\|Syntax\\)" nil 'move)
1581 (beginning-of-line)
1582 (set-window-start window (point))))))
1584 (defconst css--mdn-symbol-regexp
1585 (concat "\\("
1586 ;; @-ids.
1587 "\\(@" (regexp-opt css-at-ids) "\\)"
1588 "\\|"
1589 ;; ;; Known properties.
1590 (regexp-opt css-property-ids t)
1591 "\\|"
1592 ;; Pseudo-classes.
1593 "\\(:" (regexp-opt css-pseudo-class-ids) "\\)"
1594 "\\|"
1595 ;; Pseudo-elements with either one or two ":"s.
1596 "\\(::?" (regexp-opt css-pseudo-element-ids) "\\)"
1597 "\\)")
1598 "Regular expression to match the CSS symbol at point.")
1600 (defconst css--mdn-property-regexp
1601 (concat "\\_<" (regexp-opt css-property-ids t) "\\s-*\\(?:\\=\\|:\\)")
1602 "Regular expression to match a CSS property.")
1604 (defconst css--mdn-completion-list
1605 (nconc
1606 ;; @-ids.
1607 (mapcar (lambda (atrule) (concat "@" atrule)) css-at-ids)
1608 ;; Pseudo-classes.
1609 (mapcar (lambda (class) (concat ":" class)) css-pseudo-class-ids)
1610 ;; Pseudo-elements with either one or two ":"s.
1611 (mapcar (lambda (elt) (concat ":" elt)) css-pseudo-element-ids)
1612 (mapcar (lambda (elt) (concat "::" elt)) css-pseudo-element-ids)
1613 ;; Properties.
1614 css-property-ids)
1615 "List of all symbols available for lookup via MDN.")
1617 (defun css--mdn-find-symbol ()
1618 "A helper for `css-lookup-symbol' that finds the symbol at point.
1619 Returns the symbol, a string, or nil if none found."
1620 (save-excursion
1621 ;; Skip any whitespace between the word and point.
1622 (skip-chars-backward "- \t")
1623 ;; Skip backward over a word.
1624 (skip-chars-backward "-[:alnum:]")
1625 ;; Now skip ":" or "@" to see if it's a pseudo-element or at-id.
1626 (skip-chars-backward "@:")
1627 (if (looking-at css--mdn-symbol-regexp)
1628 (match-string-no-properties 0)
1629 (let ((bound (save-excursion
1630 (beginning-of-line)
1631 (point))))
1632 (when (re-search-backward css--mdn-property-regexp bound t)
1633 (match-string-no-properties 1))))))
1635 ;;;###autoload
1636 (defun css-lookup-symbol (symbol)
1637 "Display the CSS documentation for SYMBOL, as found on MDN.
1638 When this command is used interactively, it picks a default
1639 symbol based on the CSS text before point -- either an @-keyword,
1640 a property name, a pseudo-class, or a pseudo-element, depending
1641 on what is seen near point."
1642 (interactive
1643 (list
1644 (let* ((sym (css--mdn-find-symbol))
1645 (enable-recursive-minibuffers t)
1646 (value (completing-read
1647 (if sym
1648 (format "Describe CSS symbol (default %s): " sym)
1649 "Describe CSS symbol: ")
1650 css--mdn-completion-list nil nil nil
1651 'css--mdn-lookup-history sym)))
1652 (if (equal value "") sym value))))
1653 (when symbol
1654 ;; If we see a single-colon pseudo-element like ":after", turn it
1655 ;; into "::after".
1656 (when (and (eq (aref symbol 0) ?:)
1657 (member (substring symbol 1) css-pseudo-element-ids))
1658 (setq symbol (concat ":" symbol)))
1659 (let ((url (format css-lookup-url-format symbol))
1660 (buffer (get-buffer-create "*MDN CSS*")))
1661 ;; Make sure to display the buffer before calling `eww', as that
1662 ;; calls `pop-to-buffer-same-window'.
1663 (switch-to-buffer-other-window buffer)
1664 (with-current-buffer buffer
1665 (eww-mode)
1666 (add-hook 'eww-after-render-hook #'css--mdn-after-render nil t)
1667 (eww url)))))
1669 (provide 'css-mode)
1670 ;;; css-mode.el ends here