1 ;;; css-mode.el --- Major mode to edit CSS files -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2015 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 ;; - attribute value completion
33 ;; - fix font-lock errors with multi-line selectors
38 "Cascading Style Sheets (CSS) editing mode."
41 (defconst css-pseudo-class-ids
42 '("active" "checked" "disabled" "empty" "enabled" "first"
43 "first-child" "first-of-type" "focus" "hover" "indeterminate" "lang"
44 "last-child" "last-of-type" "left" "link" "nth-child"
45 "nth-last-child" "nth-last-of-type" "nth-of-type" "only-child"
46 "only-of-type" "right" "root" "target" "visited")
47 "Identifiers for pseudo-classes.")
49 (defconst css-pseudo-element-ids
50 '("after" "before" "first-letter" "first-line")
51 "Identifiers for pseudo-elements.")
54 '("charset" "font-face" "import" "media" "namespace" "page")
55 "Identifiers that appear in the form @foo.")
57 (defconst css-descriptor-ids
58 '("ascent" "baseline" "bbox" "cap-height" "centerline" "definition-src"
59 "descent" "font-family" "font-size" "font-stretch" "font-style"
60 "font-variant" "font-weight" "mathline" "panose-1" "slope" "src" "stemh"
61 "stemv" "topline" "unicode-range" "units-per-em" "widths" "x-height")
62 "Identifiers for font descriptors.")
64 (defconst css-media-ids
65 '("all" "aural" "bitmap" "continuous" "grid" "paged" "static" "tactile"
67 "Identifiers for types of media.")
69 (defconst css-property-ids
70 '(;; CSS 2.1 properties (http://www.w3.org/TR/CSS21/propidx.html).
72 ;; Properties duplicated by any of the CSS3 modules below have
74 "azimuth" "border-collapse" "border-spacing" "bottom"
75 "caption-side" "clear" "clip" "content" "counter-increment"
76 "counter-reset" "cue" "cue-after" "cue-before" "direction" "display"
77 "elevation" "empty-cells" "float" "height" "left" "line-height"
78 "list-style" "list-style-image" "list-style-position"
79 "list-style-type" "margin" "margin-bottom" "margin-left"
80 "margin-right" "margin-top" "max-height" "max-width" "min-height"
81 "min-width" "orphans" "overflow" "padding" "padding-bottom"
82 "padding-left" "padding-right" "padding-top" "page-break-after"
83 "page-break-before" "page-break-inside" "pause" "pause-after"
84 "pause-before" "pitch" "pitch-range" "play-during" "position"
85 "quotes" "richness" "right" "speak" "speak-header" "speak-numeral"
86 "speak-punctuation" "speech-rate" "stress" "table-layout" "top"
87 "unicode-bidi" "vertical-align" "visibility" "voice-family" "volume"
88 "widows" "width" "z-index"
91 ;; (http://www.w3.org/TR/css3-animations/#property-index)
92 "animation" "animation-delay" "animation-direction"
93 "animation-duration" "animation-fill-mode"
94 "animation-iteration-count" "animation-name"
95 "animation-play-state" "animation-timing-function"
97 ;; CSS Backgrounds and Borders Module Level 3
98 ;; (http://www.w3.org/TR/css3-background/#property-index)
99 "background" "background-attachment" "background-clip"
100 "background-color" "background-image" "background-origin"
101 "background-position" "background-repeat" "background-size"
102 "border" "border-bottom" "border-bottom-color"
103 "border-bottom-left-radius" "border-bottom-right-radius"
104 "border-bottom-style" "border-bottom-width" "border-color"
105 "border-image" "border-image-outset" "border-image-repeat"
106 "border-image-slice" "border-image-source" "border-image-width"
107 "border-left" "border-left-color" "border-left-style"
108 "border-left-width" "border-radius" "border-right"
109 "border-right-color" "border-right-style" "border-right-width"
110 "border-style" "border-top" "border-top-color"
111 "border-top-left-radius" "border-top-right-radius"
112 "border-top-style" "border-top-width" "border-width" "box-shadow"
114 ;; CSS Basic User Interface Module Level 3 (CSS3 UI)
115 ;; (http://www.w3.org/TR/css3-ui/#property-index)
116 "box-sizing" "caret-color" "cursor" "nav-down" "nav-left"
117 "nav-right" "nav-up" "outline" "outline-color" "outline-offset"
118 "outline-style" "outline-width" "resize" "text-overflow"
120 ;; CSS Color Module Level 3
121 ;; (http://www.w3.org/TR/css3-color/#property)
124 ;; CSS Flexible Box Layout Module Level 1
125 ;; (http://www.w3.org/TR/css-flexbox-1/#property-index)
126 "align-content" "align-items" "align-self" "flex" "flex-basis"
127 "flex-direction" "flex-flow" "flex-grow" "flex-shrink" "flex-wrap"
128 "justify-content" "order"
130 ;; CSS Fonts Module Level 3
131 ;; (http://www.w3.org/TR/css3-fonts/#property-index)
132 "font" "font-family" "font-feature-settings" "font-kerning"
133 "font-language-override" "font-size" "font-size-adjust"
134 "font-stretch" "font-style" "font-synthesis" "font-variant"
135 "font-variant-alternates" "font-variant-caps"
136 "font-variant-east-asian" "font-variant-ligatures"
137 "font-variant-numeric" "font-variant-position" "font-weight"
139 ;; CSS Text Decoration Module Level 3
140 ;; (http://dev.w3.org/csswg/css-text-decor-3/#property-index)
141 "text-decoration" "text-decoration-color" "text-decoration-line"
142 "text-decoration-skip" "text-decoration-style" "text-emphasis"
143 "text-emphasis-color" "text-emphasis-position" "text-emphasis-style"
144 "text-shadow" "text-underline-position"
146 ;; CSS Text Module Level 3
147 ;; (http://www.w3.org/TR/css3-text/#property-index)
148 "hanging-punctuation" "hyphens" "letter-spacing" "line-break"
149 "overflow-wrap" "tab-size" "text-align" "text-align-last"
150 "text-indent" "text-justify" "text-transform" "white-space"
151 "word-break" "word-spacing" "word-wrap"
153 ;; CSS Transforms Module Level 1
154 ;; (http://www.w3.org/TR/css3-2d-transforms/#property-index)
155 "backface-visibility" "perspective" "perspective-origin"
156 "transform" "transform-origin" "transform-style"
159 ;; (http://www.w3.org/TR/css3-transitions/#property-index)
160 "transition" "transition-delay" "transition-duration"
161 "transition-property" "transition-timing-function"
163 ;; Filter Effects Module Level 1
164 ;; (http://www.w3.org/TR/filter-effects/#property-index)
165 "color-interpolation-filters" "filter" "flood-color"
166 "flood-opacity" "lighting-color")
167 "Identifiers for properties.")
169 (defcustom css-electric-keys
'(?\
} ?\
;) ;; '()
170 "Self inserting keys which should trigger re-indentation."
172 :type
'(repeat character
)
173 :options
'((?\
} ?\
;))
176 (defvar css-mode-syntax-table
177 (let ((st (make-syntax-table)))
179 (modify-syntax-entry ?
/ ". 14" st
)
180 (modify-syntax-entry ?
* ". 23b" st
)
182 (modify-syntax-entry ?
\" "\"" st
)
183 (modify-syntax-entry ?
\' "\"" st
)
185 (modify-syntax-entry ?\
{ "(}" st
)
186 (modify-syntax-entry ?\
} "){" st
)
187 ;; Args in url(...) thingies and other "function calls".
188 (modify-syntax-entry ?\
( "()" st
)
189 (modify-syntax-entry ?\
) ")(" st
)
190 ;; To match attributes in selectors.
191 (modify-syntax-entry ?\
[ "(]" st
)
192 (modify-syntax-entry ?\
] ")[" st
)
193 ;; Special chars that sometimes come at the beginning of words.
194 (modify-syntax-entry ?
@ "'" st
)
195 ;; (modify-syntax-entry ?: "'" st)
196 (modify-syntax-entry ?
# "'" st
)
197 ;; Distinction between words and symbols.
198 (modify-syntax-entry ?-
"_" st
)
201 (defconst css-escapes-re
202 "\\\\\\(?:[^\000-\037\177]\\|[0-9a-fA-F]+[ \n\t\r\f]?\\)")
203 (defconst css-nmchar-re
(concat "\\(?:[-[:alnum:]]\\|" css-escapes-re
"\\)"))
204 (defconst css-nmstart-re
(concat "\\(?:[[:alpha:]]\\|" css-escapes-re
"\\)"))
205 (defconst css-ident-re
;; (concat css-nmstart-re css-nmchar-re "*")
206 ;; Apparently, "at rules" names can start with a dash, e.g. @-moz-keyframes.
207 (concat css-nmchar-re
"+"))
208 (defconst css-proprietary-nmstart-re
;; Vendor-specific properties.
209 (concat "[-_]" (regexp-opt '("ms" "moz" "o" "khtml" "webkit")) "-"))
210 (defconst css-name-re
(concat css-nmchar-re
"+"))
212 (defconst scss--hash-re
"#\\(?:{[$-_[:alnum:]]+}\\|[[:alnum:]]+\\)")
214 (defface css-selector
'((t :inherit font-lock-function-name-face
))
215 "Face to use for selectors."
217 (defface css-property
'((t :inherit font-lock-variable-name-face
))
218 "Face to use for properties."
220 (defface css-proprietary-property
'((t :inherit
(css-property italic
)))
221 "Face to use for vendor-specific properties.")
223 (defun css--font-lock-keywords (&optional sassy
)
225 (regexp-opt (append (if sassy
'("global"))
227 (0 font-lock-builtin-face
))
228 ;; Atrules keywords. IDs not in css-at-ids are valid (ignored).
229 ;; In fact the regexp should probably be
230 ;; (,(concat "\\(@" css-ident-re "\\)\\([ \t\n][^;{]*\\)[;{]")
231 ;; (1 font-lock-builtin-face))
232 ;; Since "An at-rule consists of everything up to and including the next
233 ;; semicolon (;) or the next block, whichever comes first."
234 (,(concat "@" css-ident-re
) (0 font-lock-builtin-face
))
236 ;; FIXME: attribute selectors don't work well because they may contain
237 ;; strings which have already been highlighted as f-l-string-face and
238 ;; thus prevent this highlighting from being applied (actually now that
239 ;; I use `keep' this should work better). But really the part of the
240 ;; selector between [...] should simply not be highlighted.
244 ;; We don't allow / as first char, so as not to
245 ;; take a comment as the beginning of a selector.
246 "[^@/:{} \t\n][^:{}]+"
247 ;; Same as for non-sassy except we do want to allow { and }
248 ;; chars in selectors in the case of #{$foo}
249 ;; variable interpolation!
250 (concat "\\(?:" scss--hash-re
251 "\\|[^@/:{} \t\n#]\\)"
252 "[^:{}#]*\\(?:" scss--hash-re
"[^:{}#]*\\)*"))
253 ;; Even though pseudo-elements should be prefixed by ::, a
254 ;; single colon is accepted for backward compatibility.
255 "\\(?:\\(:" (regexp-opt (append css-pseudo-class-ids
256 css-pseudo-element-ids
) t
)
257 "\\|\\::" (regexp-opt css-pseudo-element-ids t
) "\\)"
261 (concat "[^:{}\n#]*\\(?:" scss--hash-re
"[^:{}\n#]*\\)*"))
263 "\\)\\(?:\n[ \t]*\\)*{")
264 (1 'css-selector keep
))
265 ;; In the above rule, we allow the open-brace to be on some subsequent
266 ;; line. This will only work if we properly mark the intervening text
267 ;; as being part of a multiline element (and even then, this only
268 ;; ensures proper refontification, but not proper discovery).
269 ("^[ \t]*{" (0 (save-excursion
270 (goto-char (match-beginning 0))
271 (skip-chars-backward " \n\t")
272 (put-text-property (point) (match-end 0)
273 'font-lock-multiline t
)
276 ;; Properties. Again, we don't limit ourselves to css-property-ids.
277 (,(concat "\\(?:[{;]\\|^\\)[ \t]*\\("
278 "\\(?:\\(" css-proprietary-nmstart-re
"\\)\\|"
279 css-nmstart-re
"\\)" css-nmchar-re
"*"
281 (1 (if (match-end 2) 'css-proprietary-property
'css-property
)))))
283 (defvar css-font-lock-keywords
(css--font-lock-keywords))
285 (defvar css-font-lock-defaults
286 '(css-font-lock-keywords nil t
))
288 (defcustom css-indent-offset
4
289 "Basic size of one indentation step."
295 (defconst css-smie-grammar
297 (smie-precs->prec2
'((assoc ";") (assoc ",") (left ":")))))
299 (defun css-smie--forward-token ()
301 ((and (eq (char-before) ?\
})
302 (scss-smie--not-interpolation-p)
303 ;; FIXME: If the next char is not whitespace, what should we do?
304 (or (memq (char-after) '(?\s ?
\t ?
\n))
305 (looking-at comment-start-skip
)))
306 (if (memq (char-after) '(?\s ?
\t ?
\n))
307 (forward-char 1) (forward-comment 1))
309 ((progn (forward-comment (point-max))
310 (looking-at "[;,:]"))
311 (forward-char 1) (match-string 0))
312 (t (smie-default-forward-token))))
314 (defun css-smie--backward-token ()
316 (forward-comment (- (point)))
318 ;; FIXME: If the next char is not whitespace, what should we do?
319 ((and (eq (char-before) ?\
}) (scss-smie--not-interpolation-p)
320 (> pos
(point))) ";")
321 ((memq (char-before) '(?\
; ?\, ?\:))
322 (forward-char -
1) (string (char-after)))
323 (t (smie-default-backward-token)))))
325 (defun css-smie-rules (kind token
)
326 (pcase (cons kind token
)
327 (`(:elem . basic
) css-indent-offset
)
329 (`(:list-intro .
,(or `";" `"")) t
) ;"" stands for BOB (bug#15467).
330 (`(:before .
,(or "{" "("))
331 (if (smie-rule-hanging-p) (smie-rule-parent 0)))))
335 (defun css--complete-property ()
336 "Complete property at point."
339 (skip-chars-backward "-[:alnum:]")
340 (let ((start (point)))
341 (skip-chars-backward " \t\r\n")
342 (when (memq (char-before) '(?\
{ ?\
;))
343 (list start pos css-property-ids
))))))
345 (defun css--complete-pseudo-element-or-class ()
346 "Complete pseudo-element or pseudo-class at point."
349 (skip-chars-backward "-[:alnum:]")
350 (when (eq (char-before) ?\
:)
352 (if (eq (char-before (- (point) 1)) ?\
:)
353 css-pseudo-element-ids
354 css-pseudo-class-ids
))))))
356 (defun css--complete-at-rule ()
357 "Complete at-rule (statement beginning with `@') at point."
360 (skip-chars-backward "-[:alnum:]")
361 (when (eq (char-before) ?\
@)
362 (list (point) pos css-at-ids
)))))
364 (defun css-completion-at-point ()
365 "Complete current symbol at point.
366 Currently supports completion of CSS properties, pseudo-elements,
367 pseudo-classes, and at-rules."
368 (or (css--complete-property)
369 (css--complete-pseudo-element-or-class)
370 (css--complete-at-rule)))
373 (define-derived-mode css-mode fundamental-mode
"CSS"
374 "Major mode to edit Cascading Style Sheets."
375 (setq-local font-lock-defaults css-font-lock-defaults
)
376 (setq-local comment-start
"/*")
377 (setq-local comment-start-skip
"/\\*+[ \t]*")
378 (setq-local comment-end
"*/")
379 (setq-local comment-end-skip
"[ \t]*\\*+/")
380 (setq-local parse-sexp-ignore-comments t
)
381 (setq-local fill-paragraph-function
'css-fill-paragraph
)
382 (setq-local add-log-current-defun-function
#'css-current-defun-name
)
383 (smie-setup css-smie-grammar
#'css-smie-rules
384 :forward-token
#'css-smie--forward-token
385 :backward-token
#'css-smie--backward-token
)
386 (setq-local electric-indent-chars
387 (append css-electric-keys electric-indent-chars
))
388 (add-hook 'completion-at-point-functions
389 #'css-completion-at-point nil
'local
))
391 (defvar comment-continue
)
393 (defun css-fill-paragraph (&optional justify
)
395 (let ((ppss (syntax-ppss))
396 (eol (line-end-position)))
400 (goto-char (nth 8 ppss
))
403 (setq eol
(point)))))
404 ;; Filling inside a comment whose comment-end marker is not \n.
405 ;; This code is meant to be generic, so that it works not only for
406 ;; css-mode but for all modes.
408 (narrow-to-region (nth 8 ppss
) eol
)
409 (comment-normalize-vars) ;Will define comment-continue.
410 (let ((fill-paragraph-function nil
)
412 (if (and comment-continue
413 (string-match "[^ \t]" comment-continue
))
414 (concat "\\(?:[ \t]*" (regexp-quote comment-continue
)
415 "\\)?\\(?:" paragraph-separate
"\\)")
418 (if (and comment-continue
419 (string-match "[^ \t]" comment-continue
))
420 (concat "\\(?:[ \t]*" (regexp-quote comment-continue
)
421 "\\)?\\(?:" paragraph-start
"\\)")
423 (fill-paragraph justify
)
424 ;; Don't try filling again.
427 ((and (null (nth 8 ppss
))
431 (when (<= (point) eol
)
432 (setq ppss
(syntax-ppss)))))))
433 (goto-char (nth 1 ppss
))
434 (let ((end (save-excursion
435 (ignore-errors (forward-sexp 1) (copy-marker (point) t
)))))
437 (while (re-search-forward "[{;}]" end t
)
439 ;; This is a false positive inside a string or comment.
440 ((nth 8 (syntax-ppss)) nil
)
441 ;; This is a false positive when encountering an
442 ;; interpolated variable (bug#19751).
443 ((eq (char-before (- (point) 1)) ?
#) nil
)
444 ((eq (char-before) ?\
})
447 (skip-chars-backward " \t")
448 (when (and (not (bolp))
449 (scss-smie--not-interpolation-p))
454 (setq eol
(line-end-position))
455 (and (forward-comment 1)
457 ;; A multi-line comment should be on its own line.
458 (save-excursion (forward-comment -
1)
459 (when (< (point) eol
)
462 (if (< (point) eol
) (newline)))))
463 (goto-char (nth 1 ppss
))
464 (indent-region (line-beginning-position 2) end
)
465 ;; Don't use the default filling code.
468 (defun css-current-defun-name ()
469 "Return the name of the CSS section at point, or nil."
471 (let ((max (max (point-min) (- (point) 1600)))) ; approx 20 lines back
472 (when (search-backward "{" max t
)
473 (skip-chars-backward " \t\r\n")
475 (if (looking-at "^[ \t]*\\([^{\r\n]*[^ {\t\r\n]\\)")
476 (match-string-no-properties 1))))))
480 (defvar scss-mode-syntax-table
481 (let ((st (make-syntax-table css-mode-syntax-table
)))
482 (modify-syntax-entry ?
/ ". 124" st
)
483 (modify-syntax-entry ?
\n ">" st
)
486 (defvar scss-font-lock-keywords
487 (append `((,(concat "$" css-ident-re
) (0 font-lock-variable-name-face
)))
488 (css--font-lock-keywords 'sassy
)
489 `((,(concat "@mixin[ \t]+\\(" css-ident-re
"\\)[ \t]*(")
490 (1 font-lock-function-name-face
)))))
492 (defun scss-smie--not-interpolation-p ()
495 (or (zerop (skip-chars-backward "-[:alnum:]"))
496 (not (looking-back "#{\\$" (- (point) 3))))))
498 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.scss\\'" . scss-mode))
500 (define-derived-mode scss-mode css-mode
"SCSS"
501 "Major mode to edit \"Sassy CSS\" files."
502 (setq-local comment-start
"// ")
503 (setq-local comment-end
"")
504 (setq-local comment-start-skip
"/[*/]+[ \t]*")
505 (setq-local comment-end-skip
"[ \t]*\\(?:\n\\|\\*+/\\)")
506 (setq-local font-lock-defaults
'(scss-font-lock-keywords nil t
)))
509 ;;; css-mode.el ends here