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