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