1 ;;; css-mode.el --- Major mode to edit CSS files -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2013 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 ?* ". 23" 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 (defconst css-proprietary-nmstart-re ;; Vendor-specific properties.
215 (concat "[-_]" (regexp-opt '("ms" "moz" "o" "khtml" "webkit")) "-"))
216 (defconst css-name-re (concat css-nmchar-re "+"))
218 (defface css-selector '((t :inherit font-lock-function-name-face))
219 "Face to use for selectors."
221 (defface css-property '((t :inherit font-lock-variable-name-face))
222 "Face to use for properties."
224 (defface css-proprietary-property '((t :inherit (css-property italic)))
225 "Face to use for vendor-specific properties.")
227 (defvar css-font-lock-keywords
228 `(("!\\s-*important" . font-lock-builtin-face)
229 ;; Atrules keywords. IDs not in css-at-ids are valid (ignored).
230 ;; In fact the regexp should probably be
231 ;; (,(concat "\\(@" css-ident-re "\\)\\([ \t\n][^;{]*\\)[;{]")
232 ;; (1 font-lock-builtin-face))
233 ;; Since "An at-rule consists of everything up to and including the next
234 ;; semicolon (;) or the next block, whichever comes first."
235 (,(concat "@" css-ident-re) . font-lock-builtin-face)
237 ;; FIXME: attribute selectors don't work well because they may contain
238 ;; strings which have already been highlighted as f-l-string-face and
239 ;; thus prevent this highlighting from being applied (actually now that
240 ;; I use `append' this should work better). But really the part of hte
241 ;; selector between [...] should simply not be highlighted.
242 (,(concat "^\\([ \t]*[^@:{}\n][^:{}]+\\(?::" (regexp-opt css-pseudo-ids t)
243 "\\(?:([^)]+)\\)?[^:{\n]*\\)*\\)\\(?:\n[ \t]*\\)*{")
244 (1 'css-selector append))
245 ;; In the above rule, we allow the open-brace to be on some subsequent
246 ;; line. This will only work if we properly mark the intervening text
247 ;; as being part of a multiline element (and even then, this only
248 ;; ensures proper refontification, but not proper discovery).
249 ("^[ \t]*{" (0 (save-excursion
250 (goto-char (match-beginning 0))
251 (skip-chars-backward " \n\t")
252 (put-text-property (point) (match-end 0)
253 'font-lock-multiline t)
256 ;; Properties. Again, we don't limit ourselves to css-property-ids.
257 (,(concat "\\(?:[{;]\\|^\\)[ \t]*\\("
258 "\\(?:\\(" css-proprietary-nmstart-re "\\)\\|"
259 css-nmstart-re "\\)" css-nmchar-re "*"
261 (1 (if (match-end 2) 'css-proprietary-property 'css-property)))))
263 (defvar css-font-lock-defaults
264 '(css-font-lock-keywords nil t))
267 (define-derived-mode css-mode fundamental-mode "CSS"
268 "Major mode to edit Cascading Style Sheets."
269 (setq-local font-lock-defaults css-font-lock-defaults)
270 (setq-local comment-start "/*")
271 (setq-local comment-start-skip "/\\*+[ \t]*")
272 (setq-local comment-end "*/")
273 (setq-local comment-end-skip "[ \t]*\\*+/")
274 (setq-local forward-sexp-function 'css-forward-sexp)
275 (setq-local parse-sexp-ignore-comments t)
276 (setq-local indent-line-function 'css-indent-line)
277 (setq-local fill-paragraph-function 'css-fill-paragraph)
278 (setq-local add-log-current-defun-function #'css-current-defun-name)
279 (when css-electric-keys
280 (let ((fc (make-char-table 'auto-fill-chars)))
281 (set-char-table-parent fc auto-fill-chars)
282 (dolist (c css-electric-keys)
283 (aset fc c 'indent-according-to-mode))
284 (setq-local auto-fill-chars fc))))
286 (defvar comment-continue)
288 (defun css-fill-paragraph (&optional justify)
290 (let ((ppss (syntax-ppss))
291 (eol (line-end-position)))
295 (goto-char (nth 8 ppss))
298 (setq eol (point)))))
299 ;; Filling inside a comment whose comment-end marker is not \n.
300 ;; This code is meant to be generic, so that it works not only for
301 ;; css-mode but for all modes.
303 (narrow-to-region (nth 8 ppss) eol)
304 (comment-normalize-vars) ;Will define comment-continue.
305 (let ((fill-paragraph-function nil)
307 (if (and comment-continue
308 (string-match "[^ \t]" comment-continue))
309 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
310 "\\)?\\(?:" paragraph-separate "\\)")
313 (if (and comment-continue
314 (string-match "[^ \t]" comment-continue))
315 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
316 "\\)?\\(?:" paragraph-start "\\)")
318 (fill-paragraph justify)
319 ;; Don't try filling again.
322 ((and (null (nth 8 ppss))
326 (when (<= (point) eol)
327 (setq ppss (syntax-ppss)))))))
328 (goto-char (nth 1 ppss))
329 (let ((end (save-excursion
330 (ignore-errors (forward-sexp 1) (copy-marker (point) t)))))
332 (while (re-search-forward "[{;}]" end t)
334 ;; This is a false positive inside a string or comment.
335 ((nth 8 (syntax-ppss)) nil)
336 ((eq (char-before) ?\})
339 (skip-chars-backward " \t")
340 (unless (bolp) (newline))))
344 (setq eol (line-end-position))
345 (and (forward-comment 1)
347 ;; A multi-line comment should be on its own line.
348 (save-excursion (forward-comment -1)
349 (when (< (point) eol)
352 (if (< (point) eol) (newline)))))
353 (goto-char (nth 1 ppss))
354 (indent-region (line-beginning-position 2) end)
355 ;; Don't use the default filling code.
358 ;;; Navigation and indentation.
360 (defconst css-navigation-syntax-table
361 (let ((st (make-syntax-table css-mode-syntax-table)))
362 (map-char-table (lambda (c v)
363 ;; Turn punctuation (code = 1) into symbol (code = 1).
364 (if (eq (car-safe v) 1)
365 (set-char-table-range st c (cons 3 (cdr v)))))
369 (defun css-backward-sexp (n)
370 (let ((forward-sexp-function nil))
371 (if (< n 0) (css-forward-sexp (- n))
374 (forward-comment (- (point-max)))
375 (if (not (eq (char-before) ?\;))
377 (while (progn (backward-sexp 1)
379 (forward-comment (- (point-max)))
380 ;; FIXME: We should also skip punctuation.
381 (not (or (bobp) (memq (char-before) '(?\; ?\{))))))))))))
383 (defun css-forward-sexp (n)
384 (let ((forward-sexp-function nil))
385 (if (< n 0) (css-backward-sexp (- n))
388 (forward-comment (point-max))
389 (if (not (eq (char-after) ?\;))
391 (while (progn (forward-sexp 1)
393 (forward-comment (point-max))
394 ;; FIXME: We should also skip punctuation.
395 (not (memq (char-after) '(?\; ?\})))))))))))
397 (defun css-indent-calculate-virtual ()
398 (if (or (save-excursion (skip-chars-backward " \t") (bolp))
399 (if (looking-at "\\s(")
401 (forward-char 1) (skip-chars-forward " \t")
402 (not (or (eolp) (looking-at comment-start-skip))))))
404 (css-indent-calculate)))
406 (defcustom css-indent-offset 4
407 "Basic size of one indentation step."
412 (defun css-indent-calculate ()
413 (let ((ppss (syntax-ppss))
415 (with-syntax-table css-navigation-syntax-table
419 ((nth 3 ppss) 'noindent)
424 (skip-chars-forward " \t")
425 (if (>= (nth 8 ppss) (point))
427 (goto-char (nth 8 ppss))
428 (if (eq (char-after pos) ?*)
430 (if (not (looking-at comment-start-skip))
431 (error "Internal css-mode error")
432 (goto-char (match-end 0))))
434 (if (and (eq (char-after pos) ?*) (eq (char-after) ?*))
442 (when (looking-at "\\s)")
445 (css-indent-calculate-virtual))
446 (when (looking-at comment-start-skip)
447 (forward-comment (point-max))
448 (css-indent-calculate))
449 (when (save-excursion (forward-comment (- (point-max)))
451 (eq (char-syntax (preceding-char)) ?\())
453 (if (not (looking-at "\\s([ \t]*"))
454 (error "Internal css-mode error")
455 (if (or (memq (char-after (match-end 0)) '(?\n nil))
456 (save-excursion (goto-char (match-end 0))
457 (looking-at comment-start-skip)))
458 (+ (css-indent-calculate-virtual) css-indent-offset)
459 (progn (goto-char (match-end 0)) (current-column)))))
461 (css-backward-sexp 1)
462 (if (looking-at "\\s(")
463 (css-indent-calculate)
464 (css-indent-calculate-virtual))))))))))
467 (defun css-indent-line ()
468 "Indent current line according to CSS indentation rules."
470 (let* ((savep (point))
471 (forward-sexp-function nil)
472 (indent (condition-case nil
475 (skip-chars-forward " \t")
476 (if (>= (point) savep) (setq savep nil))
477 (css-indent-calculate))
479 (if (not (numberp indent)) 'noindent
481 (save-excursion (indent-line-to indent))
482 (indent-line-to indent)))))
484 (defun css-current-defun-name ()
485 "Return the name of the CSS section at point, or nil."
487 (let ((max (max (point-min) (- (point) 1600)))) ; approx 20 lines back
488 (when (search-backward "{" max t)
489 (skip-chars-backward " \t\r\n")
491 (if (looking-at "^[ \t]*\\([^{\r\n]*[^ {\t\r\n]\\)")
492 (match-string-no-properties 1))))))
495 ;;; css-mode.el ends here