1 ;;; css-mode.el --- Major mode to edit CSS files -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2014 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: hypermedia
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; Yet another CSS mode.
30 ;; - filling code with auto-fill-mode
32 ;; - fix font-lock errors with multi-line selectors
37 "Cascading Style Sheets (CSS) editing mode."
41 (defun css-extract-keyword-list (res)
43 (url-insert-file-contents "http://www.w3.org/TR/REC-CSS2/css2.txt")
44 (goto-char (point-max))
45 (search-backward "Appendix H. Index")
47 (delete-region (point-min) (point))
51 (goto-char (point-min))
53 (while (re-search-forward (cdr re
) nil t
)
54 (push (match-string 1) keys
))
55 (push (cons (car re
) (sort keys
'string-lessp
)) result
))
58 (defun css-extract-parse-val-grammar (string env
)
64 (concat "<a [^>]+><span [^>]+>\\(?:"
65 "<\\([^&]+\\)>\\|'\\([^']+\\)'"
73 "\\|" "\\(\\w+\\(?:-\\w+\\)*\\)"
76 ;; (assert (eq start (match-beginning 0)))
77 (setq start
(match-end 0))
79 ;; Reference to a type of value.
80 ((setq name
(match-string-no-properties 1 string
))
81 (push (intern name
) elems
))
82 ;; Reference to another property's values.
83 ((setq name
(match-string-no-properties 2 string
))
84 (setq elems
(delete-dups (append (cdr (assoc name env
)) elems
))))
86 ((setq name
(match-string-no-properties 9 string
))
88 ;; We just ignore the rest. I.e. we ignore the structure because
89 ;; it's too difficult to exploit anyway (it would allow us to only
90 ;; complete top/center/bottom after one of left/center/right and
96 (defun css-extract-props-and-vals ()
98 (url-insert-file-contents "http://www.w3.org/TR/CSS21/propidx.html")
99 (goto-char (point-min))
101 (while (re-search-forward "#propdef-\\([^\"]+\\)\"><span class=\"propinst-\\1 xref\">'\\1'</span></a>" nil t
)
102 (let ((prop (match-string-no-properties 1)))
104 (goto-char (match-end 0))
105 (search-forward "<td>")
106 (let ((vals-string (buffer-substring (point)
108 (re-search-forward "[ \t\n]+|[ \t\n]+<a href=\"cascade.html#value-def-inherit\" class=\"noxref\"><span class=\"value-inst-inherit\">inherit</span></a>")
109 (match-beginning 0)))))
111 (push (cons prop
(css-extract-parse-val-grammar vals-string props
))
115 ;; Extraction was done with:
116 ;; (css-extract-keyword-list
117 ;; '((pseudo . "^ +\\* :\\([^ \n,]+\\)")
118 ;; (at . "^ +\\* @\\([^ \n,]+\\)")
119 ;; (descriptor . "^ +\\* '\\([^ '\n]+\\)' (descriptor)")
120 ;; (media . "^ +\\* '\\([^ '\n]+\\)' media group")
121 ;; (property . "^ +\\* '\\([^ '\n]+\\)',")))
123 (defconst css-pseudo-ids
124 '("active" "after" "before" "first" "first-child" "first-letter" "first-line"
125 "focus" "hover" "lang" "left" "link" "right" "visited")
126 "Identifiers for pseudo-elements and pseudo-classes.")
129 '("charset" "font-face" "import" "media" "page")
130 "Identifiers that appear in the form @foo.")
132 (defconst css-descriptor-ids
133 '("ascent" "baseline" "bbox" "cap-height" "centerline" "definition-src"
134 "descent" "font-family" "font-size" "font-stretch" "font-style"
135 "font-variant" "font-weight" "mathline" "panose-1" "slope" "src" "stemh"
136 "stemv" "topline" "unicode-range" "units-per-em" "widths" "x-height")
137 "Identifiers for font descriptors.")
139 (defconst css-media-ids
140 '("all" "aural" "bitmap" "continuous" "grid" "paged" "static" "tactile"
142 "Identifiers for types of media.")
144 (defconst css-property-ids
145 '("azimuth" "background" "background-attachment" "background-color"
146 "background-image" "background-position" "background-repeat" "block"
147 "border" "border-bottom" "border-bottom-color" "border-bottom-style"
148 "border-bottom-width" "border-collapse" "border-color" "border-left"
149 "border-left-color" "border-left-style" "border-left-width" "border-right"
150 "border-right-color" "border-right-style" "border-right-width"
151 "border-spacing" "border-style" "border-top" "border-top-color"
152 "border-top-style" "border-top-width" "border-width" "bottom"
153 "caption-side" "clear" "clip" "color" "compact" "content"
154 "counter-increment" "counter-reset" "cue" "cue-after" "cue-before"
155 "cursor" "dashed" "direction" "display" "dotted" "double" "elevation"
156 "empty-cells" "float" "font" "font-family" "font-size" "font-size-adjust"
157 "font-stretch" "font-style" "font-variant" "font-weight" "groove" "height"
158 "hidden" "inline" "inline-table" "inset" "left" "letter-spacing"
159 "line-height" "list-item" "list-style" "list-style-image"
160 "list-style-position" "list-style-type" "margin" "margin-bottom"
161 "margin-left" "margin-right" "margin-top" "marker-offset" "marks"
162 "max-height" "max-width" "min-height" "min-width" "orphans" "outline"
163 "outline-color" "outline-style" "outline-width" "outset" "overflow"
164 "padding" "padding-bottom" "padding-left" "padding-right" "padding-top"
165 "page" "page-break-after" "page-break-before" "page-break-inside" "pause"
166 "pause-after" "pause-before" "pitch" "pitch-range" "play-during" "position"
167 "quotes" "richness" "ridge" "right" "run-in" "size" "solid" "speak"
168 "speak-header" "speak-numeral" "speak-punctuation" "speech-rate" "stress"
169 "table" "table-caption" "table-cell" "table-column" "table-column-group"
170 "table-footer-group" "table-header-group" "table-layout" "table-row"
171 "table-row-group" "text-align" "text-decoration" "text-indent"
172 "text-shadow" "text-transform" "top" "unicode-bidi" "vertical-align"
173 "visibility" "voice-family" "volume" "white-space" "widows" "width"
174 "word-spacing" "z-index")
175 "Identifiers for properties.")
177 (defcustom css-electric-keys
'(?\
} ?\
;) ;; '()
178 "Self inserting keys which should trigger re-indentation."
180 :type
'(repeat character
)
181 :options
'((?\
} ?\
;))
184 (defvar css-mode-syntax-table
185 (let ((st (make-syntax-table)))
187 (modify-syntax-entry ?
/ ". 14" st
)
188 (modify-syntax-entry ?
* ". 23b" st
)
190 (modify-syntax-entry ?
\" "\"" st
)
191 (modify-syntax-entry ?
\' "\"" st
)
193 (modify-syntax-entry ?\
{ "(}" st
)
194 (modify-syntax-entry ?\
} "){" st
)
195 ;; Args in url(...) thingies and other "function calls".
196 (modify-syntax-entry ?\
( "()" st
)
197 (modify-syntax-entry ?\
) ")(" st
)
198 ;; To match attributes in selectors.
199 (modify-syntax-entry ?\
[ "(]" st
)
200 (modify-syntax-entry ?\
] ")[" st
)
201 ;; Special chars that sometimes come at the beginning of words.
202 (modify-syntax-entry ?
@ "'" st
)
203 ;; (modify-syntax-entry ?: "'" st)
204 (modify-syntax-entry ?
# "'" st
)
205 ;; Distinction between words and symbols.
206 (modify-syntax-entry ?-
"_" st
)
209 (defconst css-escapes-re
210 "\\\\\\(?:[^\000-\037\177]\\|[0-9a-fA-F]+[ \n\t\r\f]?\\)")
211 (defconst css-nmchar-re
(concat "\\(?:[-[:alnum:]]\\|" css-escapes-re
"\\)"))
212 (defconst css-nmstart-re
(concat "\\(?:[[:alpha:]]\\|" css-escapes-re
"\\)"))
213 (defconst css-ident-re
;; (concat css-nmstart-re css-nmchar-re "*")
214 ;; Apparently, "at rules" names can start with a dash, e.g. @-moz-keyframes.
215 (concat css-nmchar-re
"+"))
216 (defconst css-proprietary-nmstart-re
;; Vendor-specific properties.
217 (concat "[-_]" (regexp-opt '("ms" "moz" "o" "khtml" "webkit")) "-"))
218 (defconst css-name-re
(concat css-nmchar-re
"+"))
220 (defconst scss--hash-re
"#\\(?:{[$-_[:alnum:]]+}\\|[[:alnum:]]+\\)")
222 (defface css-selector
'((t :inherit font-lock-function-name-face
))
223 "Face to use for selectors."
225 (defface css-property
'((t :inherit font-lock-variable-name-face
))
226 "Face to use for properties."
228 (defface css-proprietary-property
'((t :inherit
(css-property italic
)))
229 "Face to use for vendor-specific properties.")
231 (defun css--font-lock-keywords (&optional sassy
)
233 (regexp-opt (append (if sassy
'("global"))
235 (0 font-lock-builtin-face
))
236 ;; Atrules keywords. IDs not in css-at-ids are valid (ignored).
237 ;; In fact the regexp should probably be
238 ;; (,(concat "\\(@" css-ident-re "\\)\\([ \t\n][^;{]*\\)[;{]")
239 ;; (1 font-lock-builtin-face))
240 ;; Since "An at-rule consists of everything up to and including the next
241 ;; semicolon (;) or the next block, whichever comes first."
242 (,(concat "@" css-ident-re
) (0 font-lock-builtin-face
))
244 ;; FIXME: attribute selectors don't work well because they may contain
245 ;; strings which have already been highlighted as f-l-string-face and
246 ;; thus prevent this highlighting from being applied (actually now that
247 ;; I use `keep' this should work better). But really the part of the
248 ;; selector between [...] should simply not be highlighted.
252 ;; We don't allow / as first char, so as not to
253 ;; take a comment as the beginning of a selector.
254 "[^@/:{} \t\n][^:{}]+"
255 ;; Same as for non-sassy except we do want to allow { and }
256 ;; chars in selectors in the case of #{$foo}
257 ;; variable interpolation!
258 (concat "\\(?:" scss--hash-re
259 "\\|[^@/:{} \t\n#]\\)"
260 "[^:{}#]*\\(?:" scss--hash-re
"[^:{}#]*\\)*"))
261 "\\(?::" (regexp-opt css-pseudo-ids t
)
265 (concat "[^:{}\n#]*\\(?:" scss--hash-re
"[^:{}\n#]*\\)*"))
267 "\\)\\(?:\n[ \t]*\\)*{")
268 (1 'css-selector keep
))
269 ;; In the above rule, we allow the open-brace to be on some subsequent
270 ;; line. This will only work if we properly mark the intervening text
271 ;; as being part of a multiline element (and even then, this only
272 ;; ensures proper refontification, but not proper discovery).
273 ("^[ \t]*{" (0 (save-excursion
274 (goto-char (match-beginning 0))
275 (skip-chars-backward " \n\t")
276 (put-text-property (point) (match-end 0)
277 'font-lock-multiline t
)
280 ;; Properties. Again, we don't limit ourselves to css-property-ids.
281 (,(concat "\\(?:[{;]\\|^\\)[ \t]*\\("
282 "\\(?:\\(" css-proprietary-nmstart-re
"\\)\\|"
283 css-nmstart-re
"\\)" css-nmchar-re
"*"
285 (1 (if (match-end 2) 'css-proprietary-property
'css-property
)))))
287 (defvar css-font-lock-keywords
(css--font-lock-keywords))
289 (defvar css-font-lock-defaults
290 '(css-font-lock-keywords nil t
))
292 (defcustom css-indent-offset
4
293 "Basic size of one indentation step."
299 (defconst css-smie-grammar
301 (smie-precs->prec2
'((assoc ";") (assoc ",") (left ":")))))
303 (defun css-smie--forward-token ()
305 ((and (eq (char-before) ?\
})
306 (scss-smie--not-interpolation-p)
307 ;; FIXME: If the next char is not whitespace, what should we do?
308 (or (memq (char-after) '(?\s ?
\t ?
\n))
309 (looking-at comment-start-skip
)))
310 (if (memq (char-after) '(?\s ?
\t ?
\n))
311 (forward-char 1) (forward-comment 1))
313 ((progn (forward-comment (point-max))
314 (looking-at "[;,:]"))
315 (forward-char 1) (match-string 0))
316 (t (smie-default-forward-token))))
318 (defun css-smie--backward-token ()
320 (forward-comment (- (point)))
322 ;; FIXME: If the next char is not whitespace, what should we do?
323 ((and (eq (char-before) ?\
}) (scss-smie--not-interpolation-p)
324 (> pos
(point))) ";")
325 ((memq (char-before) '(?\
; ?\, ?\:))
326 (forward-char -
1) (string (char-after)))
327 (t (smie-default-backward-token)))))
329 (defun css-smie-rules (kind token
)
330 (pcase (cons kind token
)
331 (`(:elem . basic
) css-indent-offset
)
333 (`(:list-intro .
,(or `";" `"")) t
) ;"" stands for BOB (bug#15467).
334 (`(:before .
"{") (if (smie-rule-hanging-p)
335 (smie-rule-parent 0)))))
338 (define-derived-mode css-mode fundamental-mode
"CSS"
339 "Major mode to edit Cascading Style Sheets."
340 (setq-local font-lock-defaults css-font-lock-defaults
)
341 (setq-local comment-start
"/*")
342 (setq-local comment-start-skip
"/\\*+[ \t]*")
343 (setq-local comment-end
"*/")
344 (setq-local comment-end-skip
"[ \t]*\\*+/")
345 (setq-local parse-sexp-ignore-comments t
)
346 (setq-local fill-paragraph-function
'css-fill-paragraph
)
347 (setq-local add-log-current-defun-function
#'css-current-defun-name
)
348 (smie-setup css-smie-grammar
#'css-smie-rules
349 :forward-token
#'css-smie--forward-token
350 :backward-token
#'css-smie--backward-token
)
351 (setq-local electric-indent-chars
352 (append css-electric-keys electric-indent-chars
)))
354 (defvar comment-continue
)
356 (defun css-fill-paragraph (&optional justify
)
358 (let ((ppss (syntax-ppss))
359 (eol (line-end-position)))
363 (goto-char (nth 8 ppss
))
366 (setq eol
(point)))))
367 ;; Filling inside a comment whose comment-end marker is not \n.
368 ;; This code is meant to be generic, so that it works not only for
369 ;; css-mode but for all modes.
371 (narrow-to-region (nth 8 ppss
) eol
)
372 (comment-normalize-vars) ;Will define comment-continue.
373 (let ((fill-paragraph-function nil
)
375 (if (and comment-continue
376 (string-match "[^ \t]" comment-continue
))
377 (concat "\\(?:[ \t]*" (regexp-quote comment-continue
)
378 "\\)?\\(?:" paragraph-separate
"\\)")
381 (if (and comment-continue
382 (string-match "[^ \t]" comment-continue
))
383 (concat "\\(?:[ \t]*" (regexp-quote comment-continue
)
384 "\\)?\\(?:" paragraph-start
"\\)")
386 (fill-paragraph justify
)
387 ;; Don't try filling again.
390 ((and (null (nth 8 ppss
))
394 (when (<= (point) eol
)
395 (setq ppss
(syntax-ppss)))))))
396 (goto-char (nth 1 ppss
))
397 (let ((end (save-excursion
398 (ignore-errors (forward-sexp 1) (copy-marker (point) t
)))))
400 (while (re-search-forward "[{;}]" end t
)
402 ;; This is a false positive inside a string or comment.
403 ((nth 8 (syntax-ppss)) nil
)
404 ((eq (char-before) ?\
})
407 (skip-chars-backward " \t")
408 (unless (bolp) (newline))))
412 (setq eol
(line-end-position))
413 (and (forward-comment 1)
415 ;; A multi-line comment should be on its own line.
416 (save-excursion (forward-comment -
1)
417 (when (< (point) eol
)
420 (if (< (point) eol
) (newline)))))
421 (goto-char (nth 1 ppss
))
422 (indent-region (line-beginning-position 2) end
)
423 ;; Don't use the default filling code.
426 (defun css-current-defun-name ()
427 "Return the name of the CSS section at point, or nil."
429 (let ((max (max (point-min) (- (point) 1600)))) ; approx 20 lines back
430 (when (search-backward "{" max t
)
431 (skip-chars-backward " \t\r\n")
433 (if (looking-at "^[ \t]*\\([^{\r\n]*[^ {\t\r\n]\\)")
434 (match-string-no-properties 1))))))
438 (defvar scss-mode-syntax-table
439 (let ((st (make-syntax-table css-mode-syntax-table
)))
440 (modify-syntax-entry ?
/ ". 124" st
)
441 (modify-syntax-entry ?
\n ">" st
)
444 (defvar scss-font-lock-keywords
445 (append `((,(concat "$" css-ident-re
) (0 font-lock-variable-name-face
)))
446 (css--font-lock-keywords 'sassy
)
447 `((,(concat "@mixin[ \t]+\\(" css-ident-re
"\\)[ \t]*(")
448 (1 font-lock-function-name-face
)))))
450 (defun scss-smie--not-interpolation-p ()
453 (or (zerop (skip-chars-backward "[:alnum:]"))
454 (not (looking-back "#{\\$" (- (point) 3))))))
456 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.scss\\'" . scss-mode))
458 (define-derived-mode scss-mode css-mode
"SCSS"
459 "Major mode to edit \"Sassy CSS\" files."
460 (setq-local comment-start
"// ")
461 (setq-local comment-end
"")
462 (setq-local comment-start-skip
"/[*/]+[ t]*")
463 (setq-local comment-end-skip
"[ \t]*\\(?:\n\\|\\*+/\\)")
464 (setq-local font-lock-defaults
'(scss-font-lock-keywords nil t
)))
467 ;;; css-mode.el ends here