]> code.delx.au - gnu-emacs/blob - lisp/textmodes/css-mode.el
Support completion of attribute values in CSS mode
[gnu-emacs] / lisp / textmodes / css-mode.el
1 ;;; css-mode.el --- Major mode to edit CSS files -*- lexical-binding: t -*-
2
3 ;; Copyright (C) 2006-2016 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Maintainer: Simen Heggestøyl <simenheg@gmail.com>
7 ;; Keywords: hypermedia
8
9 ;; This file is part of GNU Emacs.
10
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.
15
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.
20
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/>.
23
24 ;;; Commentary:
25
26 ;; Yet another CSS mode.
27
28 ;;; Todo:
29
30 ;; - electric ; and }
31 ;; - filling code with auto-fill-mode
32 ;; - fix font-lock errors with multi-line selectors
33
34 ;;; Code:
35
36 (require 'seq)
37 (require 'smie)
38
39 (defgroup css nil
40 "Cascading Style Sheets (CSS) editing mode."
41 :group 'languages)
42
43 (defconst css-pseudo-class-ids
44 '("active" "checked" "disabled" "empty" "enabled" "first"
45 "first-child" "first-of-type" "focus" "hover" "indeterminate" "lang"
46 "last-child" "last-of-type" "left" "link" "not" "nth-child"
47 "nth-last-child" "nth-last-of-type" "nth-of-type" "only-child"
48 "only-of-type" "right" "root" "target" "visited")
49 "Identifiers for pseudo-classes.")
50
51 (defconst css-pseudo-element-ids
52 '("after" "before" "first-letter" "first-line")
53 "Identifiers for pseudo-elements.")
54
55 (defconst css-at-ids
56 '("charset" "font-face" "import" "media" "namespace" "page")
57 "Identifiers that appear in the form @foo.")
58
59 (defconst css-bang-ids
60 '("important")
61 "Identifiers that appear in the form !foo.")
62
63 (defconst scss-bang-ids
64 '("default" "global" "optional")
65 "Additional identifiers that appear in the form !foo in SCSS.")
66
67 (defconst css-descriptor-ids
68 '("ascent" "baseline" "bbox" "cap-height" "centerline" "definition-src"
69 "descent" "font-family" "font-size" "font-stretch" "font-style"
70 "font-variant" "font-weight" "mathline" "panose-1" "slope" "src" "stemh"
71 "stemv" "topline" "unicode-range" "units-per-em" "widths" "x-height")
72 "Identifiers for font descriptors.")
73
74 (defconst css-media-ids
75 '("all" "aural" "bitmap" "continuous" "grid" "paged" "static" "tactile"
76 "visual")
77 "Identifiers for types of media.")
78
79 (defconst css-property-alist
80 ;; CSS 2.1 properties (http://www.w3.org/TR/CSS21/propidx.html).
81 ;;
82 ;; Properties duplicated by any of the CSS3 modules below have been
83 ;; removed.
84 '(("azimuth" angle "left-side" "far-left" "left" "center-left"
85 "center" "center-right" "right" "far-right" "right-side" "behind"
86 "leftwards" "rightwards")
87 ("border-collapse" "collapse" "separate")
88 ("border-spacing" length)
89 ("bottom" length percentage "auto")
90 ("caption-side" "top" "bottom")
91 ("clear" "none" "left" "right" "both")
92 ("clip" shape "auto")
93 ("content" "normal" "none" string uri counter "attr()"
94 "open-quote" "close-quote" "no-open-quote" "no-close-quote")
95 ("counter-increment" identifier integer "none")
96 ("counter-reset" identifier integer "none")
97 ("cue" cue-before cue-after)
98 ("cue-after" uri "none")
99 ("cue-before" uri "none")
100 ("direction" "ltr" "rtl")
101 ("display" "inline" "block" "list-item" "inline-block" "table"
102 "inline-table" "table-row-group" "table-header-group"
103 "table-footer-group" "table-row" "table-column-group"
104 "table-column" "table-cell" "table-caption" "none"
105 ;; CSS Flexible Box Layout Module Level 1
106 ;; (https://www.w3.org/TR/css3-flexbox/#valdef-display-flex)
107 "flex" "inline-flex")
108 ("elevation" angle "below" "level" "above" "higher" "lower")
109 ("empty-cells" "show" "hide")
110 ("float" "left" "right" "none")
111 ("height" length percentage "auto")
112 ("left" length percentage "auto")
113 ("line-height" "normal" number length percentage)
114 ("list-style" list-style-type list-style-position
115 list-style-image)
116 ("list-style-image" uri "none")
117 ("list-style-position" "inside" "outside")
118 ("list-style-type" "disc" "circle" "square" "decimal"
119 "decimal-leading-zero" "lower-roman" "upper-roman" "lower-greek"
120 "lower-latin" "upper-latin" "armenian" "georgian" "lower-alpha"
121 "upper-alpha" "none")
122 ("margin" margin-width)
123 ("margin-bottom" margin-width)
124 ("margin-left" margin-width)
125 ("margin-right" margin-width)
126 ("margin-top" margin-width)
127 ("max-height" length percentage "none")
128 ("max-width" length percentage "none")
129 ("min-height" length percentage)
130 ("min-width" length percentage)
131 ("padding" padding-width)
132 ("padding-bottom" padding-width)
133 ("padding-left" padding-width)
134 ("padding-right" padding-width)
135 ("padding-top" padding-width)
136 ("page-break-after" "auto" "always" "avoid" "left" "right")
137 ("page-break-before" "auto" "always" "avoid" "left" "right")
138 ("page-break-inside" "avoid" "auto")
139 ("pause" time percentage)
140 ("pause-after" time percentage)
141 ("pause-before" time percentage)
142 ("pitch" frequency "x-low" "low" "medium" "high" "x-high")
143 ("pitch-range" number)
144 ("play-during" uri "mix" "repeat" "auto" "none")
145 ("position" "static" "relative" "absolute" "fixed")
146 ("quotes" string "none")
147 ("richness" number)
148 ("right" length percentage "auto")
149 ("speak" "normal" "none" "spell-out")
150 ("speak-header" "once" "always")
151 ("speak-numeral" "digits" "continuous")
152 ("speak-punctuation" "code" "none")
153 ("speech-rate" number "x-slow" "slow" "medium" "fast" "x-fast"
154 "faster" "slower")
155 ("stress" number)
156 ("table-layout" "auto" "fixed")
157 ("top" length percentage "auto")
158 ("unicode-bidi" "normal" "embed" "bidi-override")
159 ("vertical-align" "baseline" "sub" "super" "top" "text-top"
160 "middle" "bottom" "text-bottom" percentage length)
161 ("visibility" "visible" "hidden" "collapse")
162 ("voice-family" specific-voice generic-voice specific-voice
163 generic-voice)
164 ("volume" number percentage "silent" "x-soft" "soft" "medium"
165 "loud" "x-loud")
166 ("width" length percentage "auto")
167 ("z-index" "auto" integer)
168
169 ;; CSS Animations
170 ;; (http://www.w3.org/TR/css3-animations/#property-index)
171 ("animation" single-animation-name time single-timing-function
172 single-animation-iteration-count single-animation-direction
173 single-animation-fill-mode single-animation-play-state)
174 ("animation-delay" time)
175 ("animation-direction" single-animation-direction)
176 ("animation-duration" time)
177 ("animation-fill-mode" single-animation-fill-mode)
178 ("animation-iteration-count" single-animation-iteration-count)
179 ("animation-name" single-animation-name)
180 ("animation-play-state" single-animation-play-state)
181 ("animation-timing-function" single-timing-function)
182
183 ;; CSS Backgrounds and Borders Module Level 3
184 ;; (http://www.w3.org/TR/css3-background/#property-index)
185 ("background" bg-layer final-bg-layer)
186 ("background-attachment" attachment)
187 ("background-clip" box)
188 ("background-color" color)
189 ("background-image" bg-image)
190 ("background-origin" box)
191 ("background-position" position)
192 ("background-repeat" repeat-style)
193 ("background-size" bg-size)
194 ("border" line-width line-style color)
195 ("border-bottom" line-width line-style color)
196 ("border-bottom-color" color)
197 ("border-bottom-left-radius" length percentage)
198 ("border-bottom-right-radius" length percentage)
199 ("border-bottom-style" line-style)
200 ("border-bottom-width" line-width)
201 ("border-color" color)
202 ("border-image" border-image-source border-image-slice
203 border-image-width border-image-outset border-image-repeat)
204 ("border-image-outset" length number)
205 ("border-image-repeat" "stretch" "repeat" "round" "space")
206 ("border-image-slice" number percentage "fill")
207 ("border-image-source" "none" image)
208 ("border-image-width" length percentage number "auto")
209 ("border-left" line-width line-style color)
210 ("border-left-color" color)
211 ("border-left-style" line-style)
212 ("border-left-width" line-width)
213 ("border-radius" length percentage)
214 ("border-right" line-width line-style color)
215 ("border-right-color" color)
216 ("border-right-style" line-style)
217 ("border-right-width" line-width)
218 ("border-style" line-style)
219 ("border-top" line-width line-style color)
220 ("border-top-color" color)
221 ("border-top-left-radius" length percentage)
222 ("border-top-right-radius" length percentage)
223 ("border-top-style" line-style)
224 ("border-top-width" line-width)
225 ("border-width" line-width)
226 ("box-shadow" "none" shadow)
227
228 ;; CSS Basic User Interface Module Level 3 (CSS3 UI)
229 ;; (http://www.w3.org/TR/css3-ui/#property-index)
230 ("box-sizing" "content-box" "border-box")
231 ("caret-color" "auto" color)
232 ("cursor" uri x y "auto" "default" "none" "context-menu" "help"
233 "pointer" "progress" "wait" "cell" "crosshair" "text"
234 "vertical-text" "alias" "copy" "move" "no-drop" "not-allowed"
235 "grab" "grabbing" "e-resize" "n-resize" "ne-resize" "nw-resize"
236 "s-resize" "se-resize" "sw-resize" "w-resize" "ew-resize"
237 "ns-resize" "nesw-resize" "nwse-resize" "col-resize" "row-resize"
238 "all-scroll" "zoom-in" "zoom-out")
239 ("nav-down" "auto" id "current" "root" target-name)
240 ("nav-left" "auto" id "current" "root" target-name)
241 ("nav-right" "auto" id "current" "root" target-name)
242 ("nav-up" "auto" id "current" "root" target-name)
243 ("outline" outline-color outline-style outline-width)
244 ("outline-color" color "invert")
245 ("outline-offset" length)
246 ("outline-style" "auto" border-style)
247 ("outline-width" border-width)
248 ("resize" "none" "both" "horizontal" "vertical")
249 ("text-overflow" "clip" "ellipsis" string)
250
251 ;; CSS Color Module Level 3
252 ;; (http://www.w3.org/TR/css3-color/#property)
253 ("color" color)
254 ("opacity" alphavalue)
255
256 ;; CSS Flexible Box Layout Module Level 1
257 ;; (http://www.w3.org/TR/css-flexbox-1/#property-index)
258 ("align-content" "flex-start" "flex-end" "center" "space-between"
259 "space-around" "stretch")
260 ("align-items" "flex-start" "flex-end" "center" "baseline"
261 "stretch")
262 ("align-self" "auto" "flex-start" "flex-end" "center" "baseline"
263 "stretch")
264 ("flex" "none" flex-grow flex-shrink flex-basis)
265 ("flex-basis" "auto" "content" width)
266 ("flex-direction" "row" "row-reverse" "column" "column-reverse")
267 ("flex-flow" flex-direction flex-wrap)
268 ("flex-grow" number)
269 ("flex-shrink" number)
270 ("flex-wrap" "nowrap" "wrap" "wrap-reverse")
271 ("justify-content" "flex-start" "flex-end" "center"
272 "space-between" "space-around")
273 ("order" integer)
274
275 ;; CSS Fonts Module Level 3
276 ;; (http://www.w3.org/TR/css3-fonts/#property-index)
277 ("font" font-style font-variant-css21 font-weight font-stretch
278 font-size line-height font-family "caption" "icon" "menu"
279 "message-box" "small-caption" "status-bar")
280 ("font-family" family-name generic-family)
281 ("font-feature-settings" "normal" feature-tag-value)
282 ("font-kerning" "auto" "normal" "none")
283 ("font-language-override" "normal" string)
284 ("font-size" absolute-size relative-size length percentage)
285 ("font-size-adjust" "none" number)
286 ("font-stretch" "normal" "ultra-condensed" "extra-condensed"
287 "condensed" "semi-condensed" "semi-expanded" "expanded"
288 "extra-expanded" "ultra-expanded")
289 ("font-style" "normal" "italic" "oblique")
290 ("font-synthesis" "none" "weight" "style")
291 ("font-variant" "normal" "none" common-lig-values
292 discretionary-lig-values historical-lig-values
293 contextual-alt-values "stylistic()" "historical-forms"
294 "styleset()" "character-variant()" "swash()" "ornaments()"
295 "annotation()" "small-caps" "all-small-caps" "petite-caps"
296 "all-petite-caps" "unicase" "titling-caps" numeric-figure-values
297 numeric-spacing-values numeric-fraction-values "ordinal"
298 "slashed-zero" east-asian-variant-values east-asian-width-values
299 "ruby")
300 ("font-variant-alternates" "normal" "stylistic()"
301 "historical-forms" "styleset()" "character-variant()" "swash()"
302 "ornaments()" "annotation()")
303 ("font-variant-caps" "normal" "small-caps" "all-small-caps"
304 "petite-caps" "all-petite-caps" "unicase" "titling-caps")
305 ("font-variant-east-asian" "normal" east-asian-variant-values
306 east-asian-width-values "ruby")
307 ("font-variant-ligatures" "normal" "none" common-lig-values
308 discretionary-lig-values historical-lig-values
309 contextual-alt-values)
310 ("font-variant-numeric" "normal" numeric-figure-values
311 numeric-spacing-values numeric-fraction-values "ordinal"
312 "slashed-zero")
313 ("font-variant-position" "normal" "sub" "super")
314 ("font-weight" "normal" "bold" "bolder" "lighter" "100" "200"
315 "300" "400" "500" "600" "700" "800" "900")
316
317 ;; CSS Fragmentation Module Level 3
318 ;; (https://www.w3.org/TR/css-break-3/#property-index)
319 ("box-decoration-break" "slice" "clone")
320 ("break-after" "auto" "avoid" "avoid-page" "page" "left" "right"
321 "recto" "verso" "avoid-column" "column" "avoid-region" "region")
322 ("break-before" "auto" "avoid" "avoid-page" "page" "left" "right"
323 "recto" "verso" "avoid-column" "column" "avoid-region" "region")
324 ("break-inside" "auto" "avoid" "avoid-page" "avoid-column"
325 "avoid-region")
326 ("orphans" integer)
327 ("widows" integer)
328
329 ;; CSS Multi-column Layout Module
330 ;; (https://www.w3.org/TR/css3-multicol/#property-index)
331 ;; "break-after", "break-before", and "break-inside" are left out
332 ;; below, because they're already included in CSS Fragmentation
333 ;; Module Level 3.
334 ("column-count" integer "auto")
335 ("column-fill" "auto" "balance")
336 ("column-gap" length "normal")
337 ("column-rule" column-rule-width column-rule-style
338 column-rule-color "transparent")
339 ("column-rule-color" color)
340 ("column-rule-style" border-style)
341 ("column-rule-width" border-width)
342 ("column-span" "none" "all")
343 ("column-width" length "auto")
344 ("columns" column-width column-count)
345
346 ;; CSS Overflow Module Level 3
347 ;; (http://www.w3.org/TR/css-overflow-3/#property-index)
348 ("max-lines" "none" integer)
349 ("overflow" "visible" "hidden" "scroll" "auto" "paged-x" "paged-y"
350 "paged-x-controls" "paged-y-controls" "fragments")
351 ("overflow-x" "visible" "hidden" "scroll" "auto" "paged-x"
352 "paged-y" "paged-x-controls" "paged-y-controls" "fragments")
353 ("overflow-y" "visible" "hidden" "scroll" "auto" "paged-x"
354 "paged-y" "paged-x-controls" "paged-y-controls" "fragments")
355
356 ;; CSS Text Decoration Module Level 3
357 ;; (http://dev.w3.org/csswg/css-text-decor-3/#property-index)
358 ("text-decoration" text-decoration-line text-decoration-style
359 text-decoration-color)
360 ("text-decoration-color" color)
361 ("text-decoration-line" "none" "underline" "overline"
362 "line-through" "blink")
363 ("text-decoration-skip" "none" "objects" "spaces" "ink" "edges"
364 "box-decoration")
365 ("text-decoration-style" "solid" "double" "dotted" "dashed"
366 "wavy")
367 ("text-emphasis" text-emphasis-style text-emphasis-color)
368 ("text-emphasis-color" color)
369 ("text-emphasis-position" "over" "under" "right" "left")
370 ("text-emphasis-style" "none" "filled" "open" "dot" "circle"
371 "double-circle" "triangle" "sesame" string)
372 ("text-shadow" "none" length color)
373 ("text-underline-position" "auto" "under" "left" "right")
374
375 ;; CSS Text Module Level 3
376 ;; (http://www.w3.org/TR/css3-text/#property-index)
377 ("hanging-punctuation" "none" "first" "force-end" "allow-end"
378 "last")
379 ("hyphens" "none" "manual" "auto")
380 ("letter-spacing" "normal" length)
381 ("line-break" "auto" "loose" "normal" "strict")
382 ("overflow-wrap" "normal" "break-word")
383 ("tab-size" integer length)
384 ("text-align" "start" "end" "left" "right" "center" "justify"
385 "match-parent")
386 ("text-align-last" "auto" "start" "end" "left" "right" "center"
387 "justify")
388 ("text-indent" length percentage)
389 ("text-justify" "auto" "none" "inter-word" "distribute")
390 ("text-transform" "none" "capitalize" "uppercase" "lowercase"
391 "full-width")
392 ("white-space" "normal" "pre" "nowrap" "pre-wrap" "pre-line")
393 ("word-break" "normal" "keep-all" "break-all")
394 ("word-spacing" "normal" length percentage)
395 ("word-wrap" "normal" "break-word")
396
397 ;; CSS Transforms Module Level 1
398 ;; (http://www.w3.org/TR/css3-2d-transforms/#property-index)
399 ("backface-visibility" "visible" "hidden")
400 ("perspective" "none" length)
401 ("perspective-origin" "left" "center" "right" "top" "bottom"
402 percentage length)
403 ("transform" "none" transform-list)
404 ("transform-origin" "left" "center" "right" "top" "bottom"
405 percentage length)
406 ("transform-style" "flat" "preserve-3d")
407
408 ;; CSS Transitions
409 ;; (http://www.w3.org/TR/css3-transitions/#property-index)
410 ("transition" single-transition)
411 ("transition-delay" time)
412 ("transition-duration" time)
413 ("transition-property" "none" single-transition-property "all")
414 ("transition-timing-function" single-transition-timing-function)
415
416 ;; Filter Effects Module Level 1
417 ;; (http://www.w3.org/TR/filter-effects/#property-index)
418 ("color-interpolation-filters" "auto" "sRGB" "linearRGB")
419 ("filter" "none" filter-function-list)
420 ("flood-color" color)
421 ("flood-opacity" number percentage)
422 ("lighting-color" color))
423 "Identifiers for properties and their possible values.
424 The CAR of each entry is the name of a property, while the CDR is
425 a list of possible values for that property. String values in
426 the CDRs represent literal values, while symbols represent one of
427 the value classes found in `css-value-class-alist'. If a symbol
428 is not found in `css-value-class-alist', it's interpreted as a
429 reference back to one of the properties in this list. Some
430 symbols, such as `number' or `identifier', don't produce any
431 further value candidates, since that list would be infinite.")
432
433 (defconst css-property-ids
434 (mapcar #'car css-property-alist)
435 "Identifiers for properties.")
436
437 (defconst css-value-class-alist
438 '((absolute-size
439 "xx-small" "x-small" "small" "medium" "large" "x-large"
440 "xx-large")
441 (alphavalue number)
442 (attachment "scroll" "fixed" "local")
443 (bg-image image "none")
444 (bg-layer bg-image position repeat-style attachment box)
445 (bg-size length percentage "auto" "cover" "contain")
446 (box "border-box" "padding-box" "content-box")
447 (color
448 "aqua" "black" "blue" "fuchsia" "gray" "green" "lime" "maroon"
449 "navy" "olive" "orange" "purple" "red" "silver" "teal" "white"
450 "yellow" "transparent")
451 (common-lig-values "common-ligatures" "no-common-ligatures")
452 (contextual-alt-values "contextual" "no-contextual")
453 (counter "counter()" "counters()")
454 (discretionary-lig-values
455 "discretionary-ligatures" "no-discretionary-ligatures")
456 (east-asian-variant-values
457 "jis78" "jis83" "jis90" "jis04" "simplified" "traditional")
458 (east-asian-width-values "full-width" "proportional-width")
459 (family-name "Courier" "Helvetica" "Times")
460 (feature-tag-value string integer "on" "off")
461 (filter-function
462 "blur()" "brightness()" "contrast()" "drop-shadow()"
463 "grayscale()" "hue-rotate()" "invert()" "opacity()" "sepia()"
464 "saturate()")
465 (filter-function-list filter-function uri)
466 (final-bg-layer
467 bg-image position repeat-style attachment box color)
468 (font-variant-css21 "normal" "small-caps")
469 (generic-family
470 "serif" "sans-serif" "cursive" "fantasy" "monospace")
471 (generic-voice "male" "female" "child")
472 (gradient
473 linear-gradient radial-gradient repeating-linear-gradient
474 repeating-radial-gradient)
475 (historical-lig-values
476 "historical-ligatures" "no-historical-ligatures")
477 (image uri image-list element-reference gradient)
478 (image-list "image()")
479 (length number)
480 (line-height "normal" number length percentage)
481 (line-style
482 "none" "hidden" "dotted" "dashed" "solid" "double" "groove"
483 "ridge" "inset" "outset")
484 (line-width length "thin" "medium" "thick")
485 (linear-gradient "linear-gradient()")
486 (margin-width "auto" length percentage)
487 (numeric-figure-values "lining-nums" "oldstyle-nums")
488 (numeric-fraction-values "diagonal-fractions" "stacked-fractions")
489 (numeric-spacing-values "proportional-nums" "tabular-nums")
490 (padding-width length percentage)
491 (position
492 "left" "center" "right" "top" "bottom" percentage length)
493 (radial-gradient "radial-gradient()")
494 (relative-size "larger" "smaller")
495 (repeat-style
496 "repeat-x" "repeat-y" "repeat" "space" "round" "no-repeat")
497 (repeating-linear-gradient "repeating-linear-gradient()")
498 (repeating-radial-gradient "repeating-radial-gradient()")
499 (shadow "inset" length color)
500 (shape "rect()")
501 (single-animation-direction
502 "normal" "reverse" "alternate" "alternate-reverse")
503 (single-animation-fill-mode "none" "forwards" "backwards" "both")
504 (single-animation-iteration-count "infinite" number)
505 (single-animation-name "none" identifier)
506 (single-animation-play-state "running" "paused")
507 (single-timing-function single-transition-timing-function)
508 (single-transition
509 "none" single-transition-property time
510 single-transition-timing-function)
511 (single-transition-property "all" identifier)
512 (single-transition-timing-function
513 "ease" "linear" "ease-in" "ease-out" "ease-in-out" "step-start"
514 "step-end" "steps()" "cubic-bezier()")
515 (specific-voice identifier)
516 (target-name string)
517 (transform-list
518 "matrix()" "translate()" "translateX()" "translateY()" "scale()"
519 "scaleX()" "scaleY()" "rotate()" "skew()" "skewX()" "skewY()"
520 "matrix3d()" "translate3d()" "translateZ()" "scale3d()"
521 "scaleZ()" "rotate3d()" "rotateX()" "rotateY()" "rotateZ()"
522 "perspective()")
523 (uri "url()")
524 (width length percentage "auto")
525 (x number)
526 (y number))
527 "Property value classes and their values.
528 The format is similar to that of `css-property-alist', except
529 that the CARs aren't actual CSS properties, but rather a name for
530 a class of values, and that symbols in the CDRs always refer to
531 other entries in this list, not to properties.
532
533 The following classes have been left out above because they
534 cannot be completed sensibly: `angle', `element-reference',
535 `frequency', `id', `identifier', `integer', `number',
536 `percentage', `string', and `time'.")
537
538 (defcustom css-electric-keys '(?\} ?\;) ;; '()
539 "Self inserting keys which should trigger re-indentation."
540 :version "22.2"
541 :type '(repeat character)
542 :options '((?\} ?\;))
543 :group 'css)
544
545 (defvar css-mode-syntax-table
546 (let ((st (make-syntax-table)))
547 ;; C-style comments.
548 (modify-syntax-entry ?/ ". 14" st)
549 (modify-syntax-entry ?* ". 23b" st)
550 ;; Strings.
551 (modify-syntax-entry ?\" "\"" st)
552 (modify-syntax-entry ?\' "\"" st)
553 ;; Blocks.
554 (modify-syntax-entry ?\{ "(}" st)
555 (modify-syntax-entry ?\} "){" st)
556 ;; Args in url(...) thingies and other "function calls".
557 (modify-syntax-entry ?\( "()" st)
558 (modify-syntax-entry ?\) ")(" st)
559 ;; To match attributes in selectors.
560 (modify-syntax-entry ?\[ "(]" st)
561 (modify-syntax-entry ?\] ")[" st)
562 ;; Special chars that sometimes come at the beginning of words.
563 (modify-syntax-entry ?@ "'" st)
564 ;; (modify-syntax-entry ?: "'" st)
565 (modify-syntax-entry ?# "'" st)
566 ;; Distinction between words and symbols.
567 (modify-syntax-entry ?- "_" st)
568 st))
569
570 (eval-and-compile
571 (defconst css--uri-re
572 (concat
573 "url\\((\\)[[:space:]]*\\(?:\\\\.\\|[^()[:space:]\n'\"]\\)+"
574 "[[:space:]]*\\()\\)")))
575
576 (defconst css-syntax-propertize-function
577 (syntax-propertize-rules
578 (css--uri-re (1 "|") (2 "|"))))
579
580 (defconst css-escapes-re
581 "\\\\\\(?:[^\000-\037\177]\\|[0-9a-fA-F]+[ \n\t\r\f]?\\)")
582 (defconst css-nmchar-re (concat "\\(?:[-[:alnum:]]\\|" css-escapes-re "\\)"))
583 (defconst css-nmstart-re (concat "\\(?:[[:alpha:]]\\|" css-escapes-re "\\)"))
584 (defconst css-ident-re ;; (concat css-nmstart-re css-nmchar-re "*")
585 ;; Apparently, "at rules" names can start with a dash, e.g. @-moz-keyframes.
586 (concat css-nmchar-re "+"))
587 (defconst css-proprietary-nmstart-re ;; Vendor-specific properties.
588 (concat "[-_]" (regexp-opt '("ms" "moz" "o" "khtml" "webkit")) "-"))
589 (defconst css-name-re (concat css-nmchar-re "+"))
590
591 (defconst scss--hash-re "#\\(?:{[$-_[:alnum:]]+}\\|[[:alnum:]]+\\)")
592
593 (defface css-selector '((t :inherit font-lock-function-name-face))
594 "Face to use for selectors."
595 :group 'css)
596 (defface css-property '((t :inherit font-lock-variable-name-face))
597 "Face to use for properties."
598 :group 'css)
599 (defface css-proprietary-property '((t :inherit (css-property italic)))
600 "Face to use for vendor-specific properties.")
601
602 (defun css--font-lock-keywords (&optional sassy)
603 `((,(concat "!\\s-*"
604 (regexp-opt (append (if sassy scss-bang-ids)
605 css-bang-ids)))
606 (0 font-lock-builtin-face))
607 ;; Atrules keywords. IDs not in css-at-ids are valid (ignored).
608 ;; In fact the regexp should probably be
609 ;; (,(concat "\\(@" css-ident-re "\\)\\([ \t\n][^;{]*\\)[;{]")
610 ;; (1 font-lock-builtin-face))
611 ;; Since "An at-rule consists of everything up to and including the next
612 ;; semicolon (;) or the next block, whichever comes first."
613 (,(concat "@" css-ident-re) (0 font-lock-builtin-face))
614 ;; Variables.
615 (,(concat "--" css-ident-re) (0 font-lock-variable-name-face))
616 ;; Selectors.
617 ;; FIXME: attribute selectors don't work well because they may contain
618 ;; strings which have already been highlighted as f-l-string-face and
619 ;; thus prevent this highlighting from being applied (actually now that
620 ;; I use `keep' this should work better). But really the part of the
621 ;; selector between [...] should simply not be highlighted.
622 (,(concat
623 "^[ \t]*\\("
624 (if (not sassy)
625 ;; We don't allow / as first char, so as not to
626 ;; take a comment as the beginning of a selector.
627 "[^@/:{}() \t\n][^:{}()]+"
628 ;; Same as for non-sassy except we do want to allow { and }
629 ;; chars in selectors in the case of #{$foo}
630 ;; variable interpolation!
631 (concat "\\(?:" scss--hash-re
632 "\\|[^@/:{}() \t\n#]\\)"
633 "[^:{}()#]*\\(?:" scss--hash-re "[^:{}()#]*\\)*"))
634 ;; Even though pseudo-elements should be prefixed by ::, a
635 ;; single colon is accepted for backward compatibility.
636 "\\(?:\\(:" (regexp-opt (append css-pseudo-class-ids
637 css-pseudo-element-ids) t)
638 "\\|\\::" (regexp-opt css-pseudo-element-ids t) "\\)"
639 "\\(?:([^)]+)\\)?"
640 (if (not sassy)
641 "[^:{}()\n]*"
642 (concat "[^:{}()\n#]*\\(?:" scss--hash-re "[^:{}()\n#]*\\)*"))
643 "\\)*"
644 "\\)\\(?:\n[ \t]*\\)*{")
645 (1 'css-selector keep))
646 ;; In the above rule, we allow the open-brace to be on some subsequent
647 ;; line. This will only work if we properly mark the intervening text
648 ;; as being part of a multiline element (and even then, this only
649 ;; ensures proper refontification, but not proper discovery).
650 ("^[ \t]*{" (0 (save-excursion
651 (goto-char (match-beginning 0))
652 (skip-chars-backward " \n\t")
653 (put-text-property (point) (match-end 0)
654 'font-lock-multiline t)
655 ;; No face.
656 nil)))
657 ;; Properties. Again, we don't limit ourselves to css-property-ids.
658 (,(concat "\\(?:[{;]\\|^\\)[ \t]*\\("
659 "\\(?:\\(" css-proprietary-nmstart-re "\\)\\|"
660 css-nmstart-re "\\)" css-nmchar-re "*"
661 "\\)\\s-*:")
662 (1 (if (match-end 2) 'css-proprietary-property 'css-property)))
663 ;; Make sure the parens in a url(...) expression receive the
664 ;; default face. This is done because the parens may sometimes
665 ;; receive generic string delimiter syntax (see
666 ;; `css-syntax-propertize-function').
667 (,css--uri-re
668 (1 'default t) (2 'default t))))
669
670 (defvar css-font-lock-keywords (css--font-lock-keywords))
671
672 (defvar css-font-lock-defaults
673 '(css-font-lock-keywords nil t))
674
675 (defcustom css-indent-offset 4
676 "Basic size of one indentation step."
677 :version "22.2"
678 :type 'integer
679 :safe 'integerp)
680
681 (defconst css-smie-grammar
682 (smie-prec2->grammar
683 (smie-precs->prec2 '((assoc ";") (assoc ",") (left ":")))))
684
685 (defun css-smie--forward-token ()
686 (cond
687 ((and (eq (char-before) ?\})
688 (scss-smie--not-interpolation-p)
689 ;; FIXME: If the next char is not whitespace, what should we do?
690 (or (memq (char-after) '(?\s ?\t ?\n))
691 (looking-at comment-start-skip)))
692 (if (memq (char-after) '(?\s ?\t ?\n))
693 (forward-char 1) (forward-comment 1))
694 ";")
695 ((progn (forward-comment (point-max))
696 (looking-at "[;,:]"))
697 (forward-char 1) (match-string 0))
698 (t (smie-default-forward-token))))
699
700 (defun css-smie--backward-token ()
701 (let ((pos (point)))
702 (forward-comment (- (point)))
703 (cond
704 ;; FIXME: If the next char is not whitespace, what should we do?
705 ((and (eq (char-before) ?\}) (scss-smie--not-interpolation-p)
706 (> pos (point))) ";")
707 ((memq (char-before) '(?\; ?\, ?\:))
708 (forward-char -1) (string (char-after)))
709 (t (smie-default-backward-token)))))
710
711 (defun css-smie-rules (kind token)
712 (pcase (cons kind token)
713 (`(:elem . basic) css-indent-offset)
714 (`(:elem . arg) 0)
715 (`(:list-intro . ,(or `";" `"")) t) ;"" stands for BOB (bug#15467).
716 (`(:before . "{")
717 (when (or (smie-rule-hanging-p) (smie-rule-bolp))
718 (smie-backward-sexp ";")
719 (smie-indent-virtual)))
720 (`(:before . ,(or "{" "("))
721 (if (smie-rule-hanging-p) (smie-rule-parent 0)))))
722
723 ;;; Completion
724
725 (defun css--complete-property ()
726 "Complete property at point."
727 (save-excursion
728 (let ((pos (point)))
729 (skip-chars-backward "-[:alnum:]")
730 (let ((start (point)))
731 (skip-chars-backward " \t\r\n")
732 (when (memq (char-before) '(?\{ ?\;))
733 (list start pos css-property-ids))))))
734
735 (defun css--complete-pseudo-element-or-class ()
736 "Complete pseudo-element or pseudo-class at point."
737 (save-excursion
738 (let ((pos (point)))
739 (skip-chars-backward "-[:alnum:]")
740 (when (eq (char-before) ?\:)
741 (list (point) pos
742 (if (eq (char-before (- (point) 1)) ?\:)
743 css-pseudo-element-ids
744 css-pseudo-class-ids))))))
745
746 (defun css--complete-at-rule ()
747 "Complete at-rule (statement beginning with `@') at point."
748 (save-excursion
749 (let ((pos (point)))
750 (skip-chars-backward "-[:alnum:]")
751 (when (eq (char-before) ?\@)
752 (list (point) pos css-at-ids)))))
753
754 (defvar css--property-value-cache
755 (make-hash-table :test 'equal :size (length css-property-alist))
756 "Cache of previously completed property values.")
757
758 (defun css--value-class-lookup (value-class)
759 "Return a list of value completion candidates for VALUE-CLASS.
760 Completion candidates are looked up in `css-value-class-alist' by
761 the symbol VALUE-CLASS."
762 (seq-mapcat
763 (lambda (value)
764 (if (stringp value)
765 (list value)
766 (css--value-class-lookup value)))
767 (cdr (assq value-class css-value-class-alist))))
768
769 (defun css--property-values (property)
770 "Return a list of value completion candidates for PROPERTY.
771 Completion candidates are looked up in `css-property-alist' by
772 the string PROPERTY."
773 (or (gethash property css--property-value-cache)
774 (seq-mapcat
775 (lambda (value)
776 (if (stringp value)
777 (list value)
778 (or (css--value-class-lookup value)
779 (css--property-values (symbol-name value)))))
780 (cdr (assoc property css-property-alist)))))
781
782 (defun css--complete-property-value ()
783 "Complete property value at point."
784 (let ((property
785 (save-excursion
786 (re-search-backward ":[^/]" (line-beginning-position) t)
787 (let ((property-end (point)))
788 (skip-chars-backward "-[:alnum:]")
789 (let ((property (buffer-substring (point) property-end)))
790 (car (member property css-property-ids)))))))
791 (when property
792 (let ((end (point)))
793 (save-excursion
794 (skip-chars-backward "[:graph:]")
795 (list (point) end
796 (cons "inherit" (css--property-values property))))))))
797
798 (defun css-completion-at-point ()
799 "Complete current symbol at point.
800 Currently supports completion of CSS properties, property values,
801 pseudo-elements, pseudo-classes, and at-rules."
802 (or (css--complete-property)
803 (css--complete-property-value)
804 (css--complete-pseudo-element-or-class)
805 (css--complete-at-rule)))
806
807 ;;;###autoload
808 (define-derived-mode css-mode prog-mode "CSS"
809 "Major mode to edit Cascading Style Sheets."
810 (setq-local font-lock-defaults css-font-lock-defaults)
811 (setq-local comment-start "/*")
812 (setq-local comment-start-skip "/\\*+[ \t]*")
813 (setq-local comment-end "*/")
814 (setq-local comment-end-skip "[ \t]*\\*+/")
815 (setq-local syntax-propertize-function
816 css-syntax-propertize-function)
817 (setq-local fill-paragraph-function #'css-fill-paragraph)
818 (setq-local adaptive-fill-function #'css-adaptive-fill)
819 (setq-local add-log-current-defun-function #'css-current-defun-name)
820 (smie-setup css-smie-grammar #'css-smie-rules
821 :forward-token #'css-smie--forward-token
822 :backward-token #'css-smie--backward-token)
823 (setq-local electric-indent-chars
824 (append css-electric-keys electric-indent-chars))
825 (add-hook 'completion-at-point-functions
826 #'css-completion-at-point nil 'local))
827
828 (defvar comment-continue)
829
830 (defun css-fill-paragraph (&optional justify)
831 (save-excursion
832 ;; Fill succeeding comment when invoked right before a multi-line
833 ;; comment.
834 (when (save-excursion
835 (beginning-of-line)
836 (comment-search-forward (point-at-eol) t))
837 (goto-char (match-end 0)))
838 (let ((ppss (syntax-ppss))
839 (eol (line-end-position)))
840 (cond
841 ((and (nth 4 ppss)
842 (save-excursion
843 (goto-char (nth 8 ppss))
844 (forward-comment 1)
845 (prog1 (not (bolp))
846 (setq eol (point)))))
847 ;; Filling inside a comment whose comment-end marker is not \n.
848 ;; This code is meant to be generic, so that it works not only for
849 ;; css-mode but for all modes.
850 (save-restriction
851 (narrow-to-region (nth 8 ppss) eol)
852 (comment-normalize-vars) ;Will define comment-continue.
853 (let ((fill-paragraph-function nil)
854 (paragraph-separate
855 (if (and comment-continue
856 (string-match "[^ \t]" comment-continue))
857 (concat "\\(?:[ \t]*\\(?:"
858 (regexp-quote comment-continue) "\\|"
859 comment-start-skip "\\|"
860 comment-end-skip "\\)\\)?"
861 "\\(?:" paragraph-separate "\\)")
862 paragraph-separate))
863 (paragraph-start
864 (if (and comment-continue
865 (string-match "[^ \t]" comment-continue))
866 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
867 "\\)?\\(?:" paragraph-start "\\)")
868 paragraph-start)))
869 (fill-paragraph justify)
870 ;; Don't try filling again.
871 t)))
872
873 ((and (null (nth 8 ppss))
874 (or (nth 1 ppss)
875 (and (ignore-errors
876 (down-list 1)
877 (when (<= (point) eol)
878 (setq ppss (syntax-ppss)))))))
879 (goto-char (nth 1 ppss))
880 (let ((end (save-excursion
881 (ignore-errors (forward-sexp 1) (copy-marker (point) t)))))
882 (when end
883 (while (re-search-forward "[{;}]" end t)
884 (cond
885 ;; This is a false positive inside a string or comment.
886 ((nth 8 (syntax-ppss)) nil)
887 ;; This is a false positive when encountering an
888 ;; interpolated variable (bug#19751).
889 ((eq (char-before (- (point) 1)) ?#) nil)
890 ((eq (char-before) ?\})
891 (save-excursion
892 (forward-char -1)
893 (skip-chars-backward " \t")
894 (when (and (not (bolp))
895 (scss-smie--not-interpolation-p))
896 (newline))))
897 (t
898 (while
899 (progn
900 (setq eol (line-end-position))
901 (and (forward-comment 1)
902 (> (point) eol)
903 ;; A multi-line comment should be on its own line.
904 (save-excursion (forward-comment -1)
905 (when (< (point) eol)
906 (newline)
907 t)))))
908 (if (< (point) eol) (newline)))))
909 (goto-char (nth 1 ppss))
910 (indent-region (line-beginning-position 2) end)
911 ;; Don't use the default filling code.
912 t)))))))
913
914 (defun css-adaptive-fill ()
915 (when (looking-at "[ \t]*/\\*[ \t]*")
916 (let ((str (match-string 0)))
917 (and (string-match "/\\*" str)
918 (replace-match " *" t t str)))))
919
920 (defun css-current-defun-name ()
921 "Return the name of the CSS section at point, or nil."
922 (save-excursion
923 (let ((max (max (point-min) (- (point) 1600)))) ; approx 20 lines back
924 (when (search-backward "{" max t)
925 (skip-chars-backward " \t\r\n")
926 (beginning-of-line)
927 (if (looking-at "^[ \t]*\\([^{\r\n]*[^ {\t\r\n]\\)")
928 (match-string-no-properties 1))))))
929
930 ;;; SCSS mode
931
932 (defvar scss-mode-syntax-table
933 (let ((st (make-syntax-table css-mode-syntax-table)))
934 (modify-syntax-entry ?/ ". 124" st)
935 (modify-syntax-entry ?\n ">" st)
936 ;; Variable names are prefixed by $.
937 (modify-syntax-entry ?$ "'" st)
938 st))
939
940 (defvar scss-font-lock-keywords
941 (append `((,(concat "$" css-ident-re) (0 font-lock-variable-name-face)))
942 (css--font-lock-keywords 'sassy)
943 `((,(concat "@mixin[ \t]+\\(" css-ident-re "\\)[ \t]*(")
944 (1 font-lock-function-name-face)))))
945
946 (defun scss-smie--not-interpolation-p ()
947 (save-excursion
948 (forward-char -1)
949 (or (zerop (skip-chars-backward "-[:alnum:]"))
950 (not (looking-back "#{\\$" (- (point) 3))))))
951
952 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.scss\\'" . scss-mode))
953 ;;;###autoload
954 (define-derived-mode scss-mode css-mode "SCSS"
955 "Major mode to edit \"Sassy CSS\" files."
956 (setq-local comment-start "// ")
957 (setq-local comment-end "")
958 (setq-local comment-continue " *")
959 (setq-local comment-start-skip "/[*/]+[ \t]*")
960 (setq-local comment-end-skip "[ \t]*\\(?:\n\\|\\*+/\\)")
961 (setq-local font-lock-defaults '(scss-font-lock-keywords nil t)))
962
963 (provide 'css-mode)
964 ;;; css-mode.el ends here