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