Avoid segfaults when some display vector is an empty string
[emacs.git] / lisp / textmodes / css-mode.el
blobb37e6dce1af5da9e045401a2540242f40279793e
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 <http://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-variable-name-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 "--" 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 (if (> (length str) 4)
1041 (substring str 0 7)
1042 (substring str 0 4)))
1044 (defun css--named-color (start-point str)
1045 "Check whether STR, seen at point, is CSS named color.
1046 Returns STR if it is a valid color. Special care is taken
1047 to exclude some SCSS constructs."
1048 (when-let ((color (assoc str css--color-map)))
1049 (save-excursion
1050 (goto-char start-point)
1051 (forward-comment (- (point)))
1052 (skip-chars-backward "@[:alpha:]")
1053 (unless (looking-at-p "@\\(mixin\\|include\\)")
1054 (cdr color)))))
1056 (defun css--compute-color (start-point match)
1057 "Return the CSS color at point.
1058 Point should be just after the start of a CSS color, as recognized
1059 by `css--colors-regexp'. START-POINT is the start of the color,
1060 and MATCH is the string matched by the regexp.
1062 This function will either return the color, as a hex RGB string;
1063 or `nil' if no color could be recognized. When this function
1064 returns, point will be at the end of the recognized color."
1065 (cond
1066 ((eq (aref match 0) ?#)
1067 (css--hex-color match))
1068 ((member match '("rgb(" "rgba("))
1069 (css--rgb-color))
1070 ((member match '("hsl(" "hsla("))
1071 (css--hsl-color))
1072 ;; Evaluate to the color if the name is found.
1073 ((css--named-color start-point match))))
1075 (defun css--contrasty-color (name)
1076 "Return a color that contrasts with NAME.
1077 NAME is of any form accepted by `color-distance'.
1078 The returned color will be usable by Emacs and will contrast
1079 with NAME; in particular so that if NAME is used as a background
1080 color, the returned color can be used as the foreground and still
1081 be readable."
1082 ;; See bug#25525 for a discussion of this.
1083 (if (> (color-distance name "black") 292485)
1084 "black" "white"))
1086 (defcustom css-fontify-colors t
1087 "Whether CSS colors should be fontified using the color as the background.
1088 When non-`nil', a text representing CSS color will be fontified
1089 such that its background is the color itself. E.g., #ff0000 will
1090 be fontified with a red background."
1091 :version "26.1"
1092 :group 'css
1093 :type 'boolean
1094 :safe 'booleanp)
1096 (defun css--fontify-region (start end &optional loudly)
1097 "Fontify a CSS buffer between START and END.
1098 START and END are buffer positions."
1099 (let ((extended-region (font-lock-default-fontify-region start end loudly)))
1100 (when css-fontify-colors
1101 (when (and (consp extended-region)
1102 (eq (car extended-region) 'jit-lock-bounds))
1103 (setq start (cadr extended-region))
1104 (setq end (cddr extended-region)))
1105 (save-excursion
1106 (let ((case-fold-search t))
1107 (goto-char start)
1108 (while (re-search-forward css--colors-regexp end t)
1109 ;; Skip comments and strings.
1110 (unless (nth 8 (syntax-ppss))
1111 (let* ((start (match-beginning 0))
1112 (color (css--compute-color start (match-string 0))))
1113 (when color
1114 (with-silent-modifications
1115 ;; Use the color as the background, to make it more
1116 ;; clear. Use a contrasting color as the foreground,
1117 ;; to make it readable. Finally, have a small box
1118 ;; using the existing foreground color, to make sure
1119 ;; it stands out a bit from any other text; in
1120 ;; particular this is nice when the color matches the
1121 ;; buffer's background color.
1122 (add-text-properties
1123 start (point)
1124 (list 'face (list :background color
1125 :foreground (css--contrasty-color color)
1126 :box '(:line-width -1))))))))))))
1127 extended-region))
1129 (defcustom css-indent-offset 4
1130 "Basic size of one indentation step."
1131 :version "22.2"
1132 :type 'integer
1133 :safe 'integerp)
1135 (defconst css-smie-grammar
1136 (smie-prec2->grammar
1137 (smie-precs->prec2
1138 '((assoc ";")
1139 ;; Colons that belong to a CSS property. These get a higher
1140 ;; precedence than other colons, such as colons in selectors,
1141 ;; which are represented by a plain ":" token.
1142 (left ":-property")
1143 (assoc ",")
1144 (assoc ":")))))
1146 (defun css--colon-inside-selector-p ()
1147 "Return t if point looks to be inside a CSS selector.
1148 This function is intended to be good enough to help SMIE during
1149 tokenization, but should not be regarded as a reliable function
1150 for determining whether point is within a selector."
1151 (save-excursion
1152 (re-search-forward "[{};)]" nil t)
1153 (eq (char-before) ?\{)))
1155 (defun css--colon-inside-funcall ()
1156 "Return t if point is inside a function call."
1157 (when-let (opening-paren-pos (nth 1 (syntax-ppss)))
1158 (save-excursion
1159 (goto-char opening-paren-pos)
1160 (eq (char-after) ?\())))
1162 (defun css-smie--forward-token ()
1163 (cond
1164 ((and (eq (char-before) ?\})
1165 (scss-smie--not-interpolation-p)
1166 ;; FIXME: If the next char is not whitespace, what should we do?
1167 (or (memq (char-after) '(?\s ?\t ?\n))
1168 (looking-at comment-start-skip)))
1169 (if (memq (char-after) '(?\s ?\t ?\n))
1170 (forward-char 1) (forward-comment 1))
1171 ";")
1172 ((progn (forward-comment (point-max))
1173 (looking-at "[;,:]"))
1174 (forward-char 1)
1175 (if (equal (match-string 0) ":")
1176 (if (or (css--colon-inside-selector-p)
1177 (css--colon-inside-funcall))
1179 ":-property")
1180 (match-string 0)))
1181 (t (smie-default-forward-token))))
1183 (defun css-smie--backward-token ()
1184 (let ((pos (point)))
1185 (forward-comment (- (point)))
1186 (cond
1187 ;; FIXME: If the next char is not whitespace, what should we do?
1188 ((and (eq (char-before) ?\}) (scss-smie--not-interpolation-p)
1189 (> pos (point))) ";")
1190 ((memq (char-before) '(?\; ?\, ?\:))
1191 (forward-char -1)
1192 (if (eq (char-after) ?\:)
1193 (if (or (css--colon-inside-selector-p)
1194 (css--colon-inside-funcall))
1196 ":-property")
1197 (string (char-after))))
1198 (t (smie-default-backward-token)))))
1200 (defun css-smie-rules (kind token)
1201 (pcase (cons kind token)
1202 (`(:elem . basic) css-indent-offset)
1203 (`(:elem . arg) 0)
1204 (`(:list-intro . ,(or `";" `"")) t) ;"" stands for BOB (bug#15467).
1205 (`(:before . "{")
1206 (when (or (smie-rule-hanging-p) (smie-rule-bolp))
1207 (smie-backward-sexp ";")
1208 (smie-indent-virtual)))
1209 (`(:before . ,(or "{" "("))
1210 (if (smie-rule-hanging-p) (smie-rule-parent 0)))
1211 (`(:after . ":-property")
1212 (when (smie-rule-hanging-p)
1213 css-indent-offset))))
1215 ;;; Completion
1217 (defun css--complete-property ()
1218 "Complete property at point."
1219 (save-excursion
1220 (let ((pos (point)))
1221 (skip-chars-backward "-[:alnum:]")
1222 (let ((start (point)))
1223 (skip-chars-backward " \t\r\n")
1224 (when (memq (char-before) '(?\{ ?\;))
1225 (list start pos css-property-ids))))))
1227 (defun css--complete-bang-rule ()
1228 "Complete bang-rule at point."
1229 (save-excursion
1230 (let ((pos (point)))
1231 (skip-chars-backward "-[:alnum:]")
1232 (when (eq (char-before) ?\!)
1233 (list (point) pos css--bang-ids)))))
1235 (defun css--complete-pseudo-element-or-class ()
1236 "Complete pseudo-element or pseudo-class at point."
1237 (save-excursion
1238 (let ((pos (point)))
1239 (skip-chars-backward "-[:alnum:]")
1240 (when (eq (char-before) ?\:)
1241 (list (point) pos
1242 (if (eq (char-before (- (point) 1)) ?\:)
1243 css-pseudo-element-ids
1244 css-pseudo-class-ids))))))
1246 (defun css--complete-at-rule ()
1247 "Complete at-rule (statement beginning with `@') at point."
1248 (save-excursion
1249 (let ((pos (point)))
1250 (skip-chars-backward "-[:alnum:]")
1251 (when (eq (char-before) ?\@)
1252 (list (point) pos css--at-ids)))))
1254 (defvar css--property-value-cache
1255 (make-hash-table :test 'equal :size (length css-property-alist))
1256 "Cache of previously completed property values.")
1258 (defun css--value-class-lookup (value-class)
1259 "Return a list of value completion candidates for VALUE-CLASS.
1260 Completion candidates are looked up in `css-value-class-alist' by
1261 the symbol VALUE-CLASS."
1262 (seq-uniq
1263 (seq-mapcat
1264 (lambda (value)
1265 (if (stringp value)
1266 (list value)
1267 (css--value-class-lookup value)))
1268 (cdr (assq value-class css-value-class-alist)))))
1270 (defun css--property-values (property)
1271 "Return a list of value completion candidates for PROPERTY.
1272 Completion candidates are looked up in `css-property-alist' by
1273 the string PROPERTY."
1274 (or (gethash property css--property-value-cache)
1275 (let ((values
1276 (seq-uniq
1277 (seq-mapcat
1278 (lambda (value)
1279 (if (stringp value)
1280 (list value)
1281 (or (css--value-class-lookup value)
1282 (css--property-values (symbol-name value)))))
1283 (cdr (assoc property css-property-alist))))))
1284 (puthash property values css--property-value-cache))))
1286 (defun css--complete-property-value ()
1287 "Complete property value at point."
1288 (let ((property
1289 (save-excursion
1290 (re-search-backward ":[^/]" (line-beginning-position) t)
1291 (when (eq (char-after) ?:)
1292 (let ((property-end (point)))
1293 (skip-chars-backward "-[:alnum:]")
1294 (let ((prop (buffer-substring (point) property-end)))
1295 (car (member prop css-property-ids))))))))
1296 (when property
1297 (let ((end (point)))
1298 (save-excursion
1299 (skip-chars-backward "[:graph:]")
1300 (list (point) end
1301 (append '("inherit" "initial" "unset")
1302 (css--property-values property))))))))
1304 (defvar css--html-tags (mapcar #'car html-tag-alist)
1305 "List of HTML tags.
1306 Used to provide completion of HTML tags in selectors.")
1308 (defvar css--nested-selectors-allowed nil
1309 "Non-nil if nested selectors are allowed in the current mode.")
1310 (make-variable-buffer-local 'css--nested-selectors-allowed)
1312 (defvar css-class-list-function #'ignore
1313 "Called to provide completions of class names.
1314 This can be bound by buffers that are able to suggest class name
1315 completions, such as HTML mode buffers.")
1317 (defvar css-id-list-function #'ignore
1318 "Called to provide completions of IDs.
1319 This can be bound by buffers that are able to suggest ID
1320 completions, such as HTML mode buffers.")
1322 (defun css--foreign-completions (extractor)
1323 "Return a list of completions provided by other buffers.
1324 EXTRACTOR should be the name of a function that may be defined in
1325 one or more buffers. In each of the buffers where EXTRACTOR is
1326 defined, EXTRACTOR is called and the results are accumulated into
1327 a list of completions."
1328 (delete-dups
1329 (seq-mapcat
1330 (lambda (buf)
1331 (with-current-buffer buf
1332 (funcall (symbol-value extractor))))
1333 (buffer-list))))
1335 (defun css--complete-selector ()
1336 "Complete part of a CSS selector at point."
1337 (when (or (= (nth 0 (syntax-ppss)) 0) css--nested-selectors-allowed)
1338 (let ((end (point)))
1339 (save-excursion
1340 (skip-chars-backward "-[:alnum:]")
1341 (let ((start-char (char-before)))
1342 (list
1343 (point) end
1344 (completion-table-dynamic
1345 (lambda (_)
1346 (cond
1347 ((eq start-char ?.)
1348 (css--foreign-completions 'css-class-list-function))
1349 ((eq start-char ?#)
1350 (css--foreign-completions 'css-id-list-function))
1351 (t css--html-tags))))))))))
1353 (defun css-completion-at-point ()
1354 "Complete current symbol at point.
1355 Currently supports completion of CSS properties, property values,
1356 pseudo-elements, pseudo-classes, at-rules, bang-rules, and HTML
1357 tags, classes and IDs."
1358 (or (css--complete-bang-rule)
1359 (css--complete-property-value)
1360 (css--complete-pseudo-element-or-class)
1361 (css--complete-at-rule)
1362 (seq-let (prop-beg prop-end prop-table) (css--complete-property)
1363 (seq-let (sel-beg sel-end sel-table) (css--complete-selector)
1364 (when (or prop-table sel-table)
1365 ;; FIXME: If both prop-table and sel-table are set but
1366 ;; prop-beg/prop-end is different from sel-beg/sel-end
1367 ;; we have a problem!
1368 `(,@(if prop-table
1369 (list prop-beg prop-end)
1370 (list sel-beg sel-end))
1371 ,(completion-table-merge prop-table sel-table)
1372 :exit-function
1373 ,(lambda (string status)
1374 (and (eq status 'finished)
1375 prop-table
1376 (test-completion string prop-table)
1377 (not (and sel-table
1378 (test-completion string sel-table)))
1379 (progn (insert ": ;")
1380 (forward-char -1))))))))))
1382 ;;;###autoload
1383 (define-derived-mode css-mode prog-mode "CSS"
1384 "Major mode to edit Cascading Style Sheets (CSS).
1385 \\<css-mode-map>
1386 This mode provides syntax highlighting, indentation, completion,
1387 and documentation lookup for CSS.
1389 Use `\\[complete-symbol]' to complete CSS properties, property values,
1390 pseudo-elements, pseudo-classes, at-rules, bang-rules, and HTML
1391 tags, classes and IDs. Completion candidates for HTML class
1392 names and IDs are found by looking through open HTML mode
1393 buffers.
1395 Use `\\[info-lookup-symbol]' to look up documentation of CSS properties, at-rules,
1396 pseudo-classes, and pseudo-elements on the Mozilla Developer
1397 Network (MDN).
1399 \\{css-mode-map}"
1400 (setq-local font-lock-defaults css-font-lock-defaults)
1401 (setq-local comment-start "/*")
1402 (setq-local comment-start-skip "/\\*+[ \t]*")
1403 (setq-local comment-end "*/")
1404 (setq-local comment-end-skip "[ \t]*\\*+/")
1405 (setq-local syntax-propertize-function
1406 css-syntax-propertize-function)
1407 (setq-local fill-paragraph-function #'css-fill-paragraph)
1408 (setq-local adaptive-fill-function #'css-adaptive-fill)
1409 (setq-local add-log-current-defun-function #'css-current-defun-name)
1410 (smie-setup css-smie-grammar #'css-smie-rules
1411 :forward-token #'css-smie--forward-token
1412 :backward-token #'css-smie--backward-token)
1413 (setq-local electric-indent-chars
1414 (append css-electric-keys electric-indent-chars))
1415 (setq-local font-lock-fontify-region-function #'css--fontify-region)
1416 (add-hook 'completion-at-point-functions
1417 #'css-completion-at-point nil 'local))
1419 (defvar comment-continue)
1421 (defun css-fill-paragraph (&optional justify)
1422 (save-excursion
1423 ;; Fill succeeding comment when invoked right before a multi-line
1424 ;; comment.
1425 (when (save-excursion
1426 (beginning-of-line)
1427 (comment-search-forward (point-at-eol) t))
1428 (goto-char (match-end 0)))
1429 (let ((ppss (syntax-ppss))
1430 (eol (line-end-position)))
1431 (cond
1432 ((and (nth 4 ppss)
1433 (save-excursion
1434 (goto-char (nth 8 ppss))
1435 (forward-comment 1)
1436 (prog1 (not (bolp))
1437 (setq eol (point)))))
1438 ;; Filling inside a comment whose comment-end marker is not \n.
1439 ;; This code is meant to be generic, so that it works not only for
1440 ;; css-mode but for all modes.
1441 (save-restriction
1442 (narrow-to-region (nth 8 ppss) eol)
1443 (comment-normalize-vars) ;Will define comment-continue.
1444 (let ((fill-paragraph-function nil)
1445 (paragraph-separate
1446 (if (and comment-continue
1447 (string-match "[^ \t]" comment-continue))
1448 (concat "\\(?:[ \t]*\\(?:"
1449 (regexp-quote comment-continue) "\\|"
1450 comment-start-skip "\\|"
1451 comment-end-skip "\\)\\)?"
1452 "\\(?:" paragraph-separate "\\)")
1453 paragraph-separate))
1454 (paragraph-start
1455 (if (and comment-continue
1456 (string-match "[^ \t]" comment-continue))
1457 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
1458 "\\)?\\(?:" paragraph-start "\\)")
1459 paragraph-start)))
1460 (fill-paragraph justify)
1461 ;; Don't try filling again.
1462 t)))
1464 ((and (null (nth 8 ppss))
1465 (or (nth 1 ppss)
1466 (and (ignore-errors
1467 (down-list 1)
1468 (when (<= (point) eol)
1469 (setq ppss (syntax-ppss)))))))
1470 (goto-char (nth 1 ppss))
1471 (let ((end (save-excursion
1472 (ignore-errors (forward-sexp 1) (copy-marker (point) t)))))
1473 (when end
1474 (while (re-search-forward "[{;}]" end t)
1475 (cond
1476 ;; This is a false positive inside a string or comment.
1477 ((nth 8 (syntax-ppss)) nil)
1478 ;; This is a false positive when encountering an
1479 ;; interpolated variable (bug#19751).
1480 ((eq (char-before (- (point) 1)) ?#) nil)
1481 ((eq (char-before) ?\})
1482 (save-excursion
1483 (forward-char -1)
1484 (skip-chars-backward " \t")
1485 (when (and (not (bolp))
1486 (scss-smie--not-interpolation-p))
1487 (newline))))
1489 (while
1490 (progn
1491 (setq eol (line-end-position))
1492 (and (forward-comment 1)
1493 (> (point) eol)
1494 ;; A multi-line comment should be on its own line.
1495 (save-excursion (forward-comment -1)
1496 (when (< (point) eol)
1497 (newline)
1498 t)))))
1499 (if (< (point) eol) (newline)))))
1500 (goto-char (nth 1 ppss))
1501 (indent-region (line-beginning-position 2) end)
1502 ;; Don't use the default filling code.
1503 t)))))))
1505 (defun css-adaptive-fill ()
1506 (when (looking-at "[ \t]*/\\*[ \t]*")
1507 (let ((str (match-string 0)))
1508 (and (string-match "/\\*" str)
1509 (replace-match " *" t t str)))))
1511 (defun css-current-defun-name ()
1512 "Return the name of the CSS section at point, or nil."
1513 (save-excursion
1514 (let ((max (max (point-min) (- (point) 1600)))) ; approx 20 lines back
1515 (when (search-backward "{" max t)
1516 (skip-chars-backward " \t\r\n")
1517 (beginning-of-line)
1518 (if (looking-at "^[ \t]*\\([^{\r\n]*[^ {\t\r\n]\\)")
1519 (match-string-no-properties 1))))))
1521 ;;; SCSS mode
1523 (defvar scss-mode-syntax-table
1524 (let ((st (make-syntax-table css-mode-syntax-table)))
1525 (modify-syntax-entry ?/ ". 124" st)
1526 (modify-syntax-entry ?\n ">" st)
1527 ;; Variable names are prefixed by $.
1528 (modify-syntax-entry ?$ "_" st)
1529 (modify-syntax-entry ?% "_" st)
1530 st))
1532 (defun scss-font-lock-keywords ()
1533 (append `((,(concat "$" css-ident-re) (0 font-lock-variable-name-face)))
1534 (css--font-lock-keywords 'sassy)
1535 `((,(concat "@mixin[ \t]+\\(" css-ident-re "\\)[ \t]*(")
1536 (1 font-lock-function-name-face)))))
1538 (defun scss-smie--not-interpolation-p ()
1539 (save-excursion
1540 (forward-char -1)
1541 (or (zerop (skip-chars-backward "-[:alnum:]"))
1542 (not (looking-back "#{\\$" (- (point) 3))))))
1544 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.scss\\'" . scss-mode))
1545 ;;;###autoload
1546 (define-derived-mode scss-mode css-mode "SCSS"
1547 "Major mode to edit \"Sassy CSS\" files."
1548 (setq-local comment-start "// ")
1549 (setq-local comment-end "")
1550 (setq-local comment-continue " *")
1551 (setq-local comment-start-skip "/[*/]+[ \t]*")
1552 (setq-local comment-end-skip "[ \t]*\\(?:\n\\|\\*+/\\)")
1553 (setq-local css--at-ids (append css-at-ids scss-at-ids))
1554 (setq-local css--bang-ids (append css-bang-ids scss-bang-ids))
1555 (setq-local css--nested-selectors-allowed t)
1556 (setq-local font-lock-defaults
1557 (list (scss-font-lock-keywords) nil t)))
1561 (defvar css--mdn-lookup-history nil)
1563 (defcustom css-lookup-url-format
1564 "https://developer.mozilla.org/en-US/docs/Web/CSS/%s?raw&macros"
1565 "Format for a URL where CSS documentation can be found.
1566 The format should include a single \"%s\" substitution.
1567 The name of the CSS property, @-id, pseudo-class, or pseudo-element
1568 to look up will be substituted there."
1569 :version "26.1"
1570 :type 'string
1571 :group 'css)
1573 (defun css--mdn-after-render ()
1574 (setf header-line-format nil)
1575 (goto-char (point-min))
1576 (let ((window (get-buffer-window (current-buffer) 'visible)))
1577 (when window
1578 (when (re-search-forward "^Summary" nil 'move)
1579 (beginning-of-line)
1580 (set-window-start window (point))))))
1582 (defconst css--mdn-symbol-regexp
1583 (concat "\\("
1584 ;; @-ids.
1585 "\\(@" (regexp-opt css-at-ids) "\\)"
1586 "\\|"
1587 ;; ;; Known properties.
1588 (regexp-opt css-property-ids t)
1589 "\\|"
1590 ;; Pseudo-classes.
1591 "\\(:" (regexp-opt css-pseudo-class-ids) "\\)"
1592 "\\|"
1593 ;; Pseudo-elements with either one or two ":"s.
1594 "\\(::?" (regexp-opt css-pseudo-element-ids) "\\)"
1595 "\\)")
1596 "Regular expression to match the CSS symbol at point.")
1598 (defconst css--mdn-property-regexp
1599 (concat "\\_<" (regexp-opt css-property-ids t) "\\s-*\\(?:\\=\\|:\\)")
1600 "Regular expression to match a CSS property.")
1602 (defconst css--mdn-completion-list
1603 (nconc
1604 ;; @-ids.
1605 (mapcar (lambda (atrule) (concat "@" atrule)) css-at-ids)
1606 ;; Pseudo-classes.
1607 (mapcar (lambda (class) (concat ":" class)) css-pseudo-class-ids)
1608 ;; Pseudo-elements with either one or two ":"s.
1609 (mapcar (lambda (elt) (concat ":" elt)) css-pseudo-element-ids)
1610 (mapcar (lambda (elt) (concat "::" elt)) css-pseudo-element-ids)
1611 ;; Properties.
1612 css-property-ids)
1613 "List of all symbols available for lookup via MDN.")
1615 (defun css--mdn-find-symbol ()
1616 "A helper for `css-lookup-symbol' that finds the symbol at point.
1617 Returns the symbol, a string, or nil if none found."
1618 (save-excursion
1619 ;; Skip any whitespace between the word and point.
1620 (skip-chars-backward "- \t")
1621 ;; Skip backward over a word.
1622 (skip-chars-backward "-[:alnum:]")
1623 ;; Now skip ":" or "@" to see if it's a pseudo-element or at-id.
1624 (skip-chars-backward "@:")
1625 (if (looking-at css--mdn-symbol-regexp)
1626 (match-string-no-properties 0)
1627 (let ((bound (save-excursion
1628 (beginning-of-line)
1629 (point))))
1630 (when (re-search-backward css--mdn-property-regexp bound t)
1631 (match-string-no-properties 1))))))
1633 ;;;###autoload
1634 (defun css-lookup-symbol (symbol)
1635 "Display the CSS documentation for SYMBOL, as found on MDN.
1636 When this command is used interactively, it picks a default
1637 symbol based on the CSS text before point -- either an @-keyword,
1638 a property name, a pseudo-class, or a pseudo-element, depending
1639 on what is seen near point."
1640 (interactive
1641 (list
1642 (let* ((sym (css--mdn-find-symbol))
1643 (enable-recursive-minibuffers t)
1644 (value (completing-read
1645 (if sym
1646 (format "Describe CSS symbol (default %s): " sym)
1647 "Describe CSS symbol: ")
1648 css--mdn-completion-list nil nil nil
1649 'css--mdn-lookup-history sym)))
1650 (if (equal value "") sym value))))
1651 (when symbol
1652 ;; If we see a single-colon pseudo-element like ":after", turn it
1653 ;; into "::after".
1654 (when (and (eq (aref symbol 0) ?:)
1655 (member (substring symbol 1) css-pseudo-element-ids))
1656 (setq symbol (concat ":" symbol)))
1657 (let ((url (format css-lookup-url-format symbol))
1658 (buffer (get-buffer-create "*MDN CSS*")))
1659 (save-selected-window
1660 ;; Make sure to display the buffer before calling `eww', as
1661 ;; that calls `pop-to-buffer-same-window'.
1662 (switch-to-buffer-other-window buffer)
1663 (with-current-buffer buffer
1664 (eww-mode)
1665 (add-hook 'eww-after-render-hook #'css--mdn-after-render nil t)
1666 (eww url))))))
1668 (provide 'css-mode)
1669 ;;; css-mode.el ends here