]> code.delx.au - gnu-emacs/blob - lisp/textmodes/css-mode.el
Highlight vendor specific properties.
[gnu-emacs] / lisp / textmodes / css-mode.el
1 ;;; css-mode.el --- Major mode to edit CSS files
2
3 ;; Copyright (C) 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: hypermedia
7
8 ;; This file is part of GNU Emacs.
9
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.
14
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.
19
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/>.
22
23 ;;; Commentary:
24
25 ;; Yet another CSS mode.
26
27 ;;; Todo:
28
29 ;; - electric ; and }
30 ;; - filling code with auto-fill-mode
31 ;; - completion
32 ;; - fix font-lock errors with multi-line selectors
33
34 ;;; Code:
35
36 (defgroup css nil
37 "Cascading Style Sheets (CSS) editing mode."
38 :group 'languages)
39
40 (eval-when-compile (require 'cl))
41
42 (defun css-extract-keyword-list (res)
43 (with-temp-buffer
44 (url-insert-file-contents "http://www.w3.org/TR/REC-CSS2/css2.txt")
45 (goto-char (point-max))
46 (search-backward "Appendix H. Index")
47 (forward-line)
48 (delete-region (point-min) (point))
49 (let ((result nil)
50 keys)
51 (dolist (re res)
52 (goto-char (point-min))
53 (setq keys nil)
54 (while (re-search-forward (cdr re) nil t)
55 (push (match-string 1) keys))
56 (push (cons (car re) (sort keys 'string-lessp)) result))
57 (nreverse result))))
58
59 (defun css-extract-parse-val-grammar (string env)
60 (let ((start 0)
61 (elems ())
62 name)
63 (while (string-match
64 (concat "\\(?:"
65 (concat "<a [^>]+><span [^>]+>\\(?:"
66 "&lt;\\([^&]+\\)&gt;\\|'\\([^']+\\)'"
67 "\\)</span></a>")
68 "\\|" "\\(\\[\\)"
69 "\\|" "\\(]\\)"
70 "\\|" "\\(||\\)"
71 "\\|" "\\(|\\)"
72 "\\|" "\\([*+?]\\)"
73 "\\|" "\\({[^}]+}\\)"
74 "\\|" "\\(\\w+\\(?:-\\w+\\)*\\)"
75 "\\)[ \t\n]*")
76 string start)
77 ;; (assert (eq start (match-beginning 0)))
78 (setq start (match-end 0))
79 (cond
80 ;; Reference to a type of value.
81 ((setq name (match-string-no-properties 1 string))
82 (push (intern name) elems))
83 ;; Reference to another property's values.
84 ((setq name (match-string-no-properties 2 string))
85 (setq elems (delete-dups (append (cdr (assoc name env)) elems))))
86 ;; A literal
87 ((setq name (match-string-no-properties 9 string))
88 (push name elems))
89 ;; We just ignore the rest. I.e. we ignore the structure because
90 ;; it's too difficult to exploit anyway (it would allow us to only
91 ;; complete top/center/bottom after one of left/center/right and
92 ;; vice-versa).
93 (t nil)))
94 elems))
95
96
97 (defun css-extract-props-and-vals ()
98 (with-temp-buffer
99 (url-insert-file-contents "http://www.w3.org/TR/CSS21/propidx.html")
100 (goto-char (point-min))
101 (let ((props ()))
102 (while (re-search-forward "#propdef-\\([^\"]+\\)\"><span class=\"propinst-\\1 xref\">'\\1'</span></a>" nil t)
103 (let ((prop (match-string-no-properties 1)))
104 (save-excursion
105 (goto-char (match-end 0))
106 (search-forward "<td>")
107 (let ((vals-string (buffer-substring (point)
108 (progn
109 (re-search-forward "[ \t\n]+|[ \t\n]+<a href=\"cascade.html#value-def-inherit\" class=\"noxref\"><span class=\"value-inst-inherit\">inherit</span></a>")
110 (match-beginning 0)))))
111 ;;
112 (push (cons prop (css-extract-parse-val-grammar vals-string props))
113 props)))))
114 props)))
115
116 ;; Extraction was done with:
117 ;; (css-extract-keyword-list
118 ;; '((pseudo . "^ +\\* :\\([^ \n,]+\\)")
119 ;; (at . "^ +\\* @\\([^ \n,]+\\)")
120 ;; (descriptor . "^ +\\* '\\([^ '\n]+\\)' (descriptor)")
121 ;; (media . "^ +\\* '\\([^ '\n]+\\)' media group")
122 ;; (property . "^ +\\* '\\([^ '\n]+\\)',")))
123
124 (defconst css-pseudo-ids
125 '("active" "after" "before" "first" "first-child" "first-letter" "first-line"
126 "focus" "hover" "lang" "left" "link" "right" "visited")
127 "Identifiers for pseudo-elements and pseudo-classes.")
128
129 (defconst css-at-ids
130 '("charset" "font-face" "import" "media" "page")
131 "Identifiers that appear in the form @foo.")
132
133 (defconst css-descriptor-ids
134 '("ascent" "baseline" "bbox" "cap-height" "centerline" "definition-src"
135 "descent" "font-family" "font-size" "font-stretch" "font-style"
136 "font-variant" "font-weight" "mathline" "panose-1" "slope" "src" "stemh"
137 "stemv" "topline" "unicode-range" "units-per-em" "widths" "x-height")
138 "Identifiers for font descriptors.")
139
140 (defconst css-media-ids
141 '("all" "aural" "bitmap" "continuous" "grid" "paged" "static" "tactile"
142 "visual")
143 "Identifiers for types of media.")
144
145 (defconst css-property-ids
146 '("azimuth" "background" "background-attachment" "background-color"
147 "background-image" "background-position" "background-repeat" "block"
148 "border" "border-bottom" "border-bottom-color" "border-bottom-style"
149 "border-bottom-width" "border-collapse" "border-color" "border-left"
150 "border-left-color" "border-left-style" "border-left-width" "border-right"
151 "border-right-color" "border-right-style" "border-right-width"
152 "border-spacing" "border-style" "border-top" "border-top-color"
153 "border-top-style" "border-top-width" "border-width" "bottom"
154 "caption-side" "clear" "clip" "color" "compact" "content"
155 "counter-increment" "counter-reset" "cue" "cue-after" "cue-before"
156 "cursor" "dashed" "direction" "display" "dotted" "double" "elevation"
157 "empty-cells" "float" "font" "font-family" "font-size" "font-size-adjust"
158 "font-stretch" "font-style" "font-variant" "font-weight" "groove" "height"
159 "hidden" "inline" "inline-table" "inset" "left" "letter-spacing"
160 "line-height" "list-item" "list-style" "list-style-image"
161 "list-style-position" "list-style-type" "margin" "margin-bottom"
162 "margin-left" "margin-right" "margin-top" "marker-offset" "marks"
163 "max-height" "max-width" "min-height" "min-width" "orphans" "outline"
164 "outline-color" "outline-style" "outline-width" "outset" "overflow"
165 "padding" "padding-bottom" "padding-left" "padding-right" "padding-top"
166 "page" "page-break-after" "page-break-before" "page-break-inside" "pause"
167 "pause-after" "pause-before" "pitch" "pitch-range" "play-during" "position"
168 "quotes" "richness" "ridge" "right" "run-in" "size" "solid" "speak"
169 "speak-header" "speak-numeral" "speak-punctuation" "speech-rate" "stress"
170 "table" "table-caption" "table-cell" "table-column" "table-column-group"
171 "table-footer-group" "table-header-group" "table-layout" "table-row"
172 "table-row-group" "text-align" "text-decoration" "text-indent"
173 "text-shadow" "text-transform" "top" "unicode-bidi" "vertical-align"
174 "visibility" "voice-family" "volume" "white-space" "widows" "width"
175 "word-spacing" "z-index")
176 "Identifiers for properties.")
177
178 (defcustom css-electric-keys '(?\} ?\;) ;; '()
179 "Self inserting keys which should trigger re-indentation."
180 :version "22.2"
181 :type '(repeat character)
182 :options '((?\} ?\;))
183 :group 'css)
184
185 (defvar css-mode-syntax-table
186 (let ((st (make-syntax-table)))
187 ;; C-style comments.
188 (modify-syntax-entry ?/ ". 14" st)
189 (modify-syntax-entry ?* ". 23" st)
190 ;; Strings.
191 (modify-syntax-entry ?\" "\"" st)
192 (modify-syntax-entry ?\' "\"" st)
193 ;; Blocks.
194 (modify-syntax-entry ?\{ "(}" st)
195 (modify-syntax-entry ?\} "){" st)
196 ;; Args in url(...) thingies and other "function calls".
197 (modify-syntax-entry ?\( "()" st)
198 (modify-syntax-entry ?\) ")(" st)
199 ;; To match attributes in selectors.
200 (modify-syntax-entry ?\[ "(]" st)
201 (modify-syntax-entry ?\] ")[" st)
202 ;; Special chars that sometimes come at the beginning of words.
203 (modify-syntax-entry ?@ "'" st)
204 ;; (modify-syntax-entry ?: "'" st)
205 (modify-syntax-entry ?# "'" st)
206 ;; Distinction between words and symbols.
207 (modify-syntax-entry ?- "_" st)
208 st))
209
210 (defconst css-escapes-re
211 "\\\\\\(?:[^\000-\037\177]\\|[0-9a-fA-F]+[ \n\t\r\f]?\\)")
212 (defconst css-nmchar-re (concat "\\(?:[-[:alnum:]]\\|" css-escapes-re "\\)"))
213 (defconst css-nmstart-re (concat "\\(?:[[:alpha:]]\\|" css-escapes-re "\\)"))
214 (defconst css-ident-re (concat css-nmstart-re css-nmchar-re "*"))
215 (defconst css-proprietary-nmstart-re ;; Vendor-specific properties.
216 "[-_]\\(?:ms\\|moz\\|o\\|webkit\\|khtml\\)-")
217 (defconst css-name-re (concat css-nmchar-re "+"))
218
219 (defface css-selector '((t :inherit font-lock-function-name-face))
220 "Face to use for selectors."
221 :group 'css)
222 (defface css-property '((t :inherit font-lock-variable-name-face))
223 "Face to use for properties."
224 :group 'css)
225 (defface css-proprietary-property '((t :inherit (css-property italic)))
226 "Face to use for vendor-specific properties.")
227
228 (defvar css-font-lock-keywords
229 `(("!\\s-*important" . font-lock-builtin-face)
230 ;; Atrules keywords. IDs not in css-at-ids are valid (ignored).
231 ;; In fact the regexp should probably be
232 ;; (,(concat "\\(@" css-ident-re "\\)\\([ \t\n][^;{]*\\)[;{]")
233 ;; (1 font-lock-builtin-face))
234 ;; Since "An at-rule consists of everything up to and including the next
235 ;; semicolon (;) or the next block, whichever comes first."
236 (,(concat "@" css-ident-re) . font-lock-builtin-face)
237 ;; Selectors.
238 ;; FIXME: attribute selectors don't work well because they may contain
239 ;; strings which have already been highlighted as f-l-string-face and
240 ;; thus prevent this highlighting from being applied (actually now that
241 ;; I use `append' this should work better). But really the part of hte
242 ;; selector between [...] should simply not be highlighted.
243 (,(concat "^\\([ \t]*[^@:{\n][^:{\n]+\\(?::" (regexp-opt css-pseudo-ids t)
244 "\\(?:([^)]+)\\)?[^:{\n]*\\)*\\)\\(?:\n[ \t]*\\)*{")
245 (1 'css-selector append))
246 ;; In the above rule, we allow the open-brace to be on some subsequent
247 ;; line. This will only work if we properly mark the intervening text
248 ;; as being part of a multiline element (and even then, this only
249 ;; ensures proper refontification, but not proper discovery).
250 ("^[ \t]*{" (0 (save-excursion
251 (goto-char (match-beginning 0))
252 (skip-chars-backward " \n\t")
253 (put-text-property (point) (match-end 0)
254 'font-lock-multiline t)
255 ;; No face.
256 nil)))
257 ;; Properties. Again, we don't limit ourselves to css-property-ids.
258 (,(concat "\\(?:[{;]\\|^\\)[ \t]*\\("
259 "\\(?:\\(" css-proprietary-nmstart-re "\\)\\|"
260 css-nmstart-re "\\)" css-nmchar-re "*"
261 "\\)\\s-*:")
262 (1 (if (match-end 2) 'css-proprietary-property 'css-property)))))
263
264 (defvar css-font-lock-defaults
265 '(css-font-lock-keywords nil t))
266
267 ;;;###autoload (add-to-list 'auto-mode-alist (cons (purecopy "\\.css\\'") 'css-mode))
268 ;;;###autoload
269 (define-derived-mode css-mode fundamental-mode "CSS"
270 "Major mode to edit Cascading Style Sheets."
271 (set (make-local-variable 'font-lock-defaults) css-font-lock-defaults)
272 (set (make-local-variable 'comment-start) "/*")
273 (set (make-local-variable 'comment-start-skip) "/\\*+[ \t]*")
274 (set (make-local-variable 'comment-end) "*/")
275 (set (make-local-variable 'comment-end-skip) "[ \t]*\\*+/")
276 (set (make-local-variable 'forward-sexp-function) 'css-forward-sexp)
277 (set (make-local-variable 'parse-sexp-ignore-comments) t)
278 (set (make-local-variable 'indent-line-function) 'css-indent-line)
279 (set (make-local-variable 'fill-paragraph-function)
280 'css-fill-paragraph)
281 (when css-electric-keys
282 (let ((fc (make-char-table 'auto-fill-chars)))
283 (set-char-table-parent fc auto-fill-chars)
284 (dolist (c css-electric-keys)
285 (aset fc c 'indent-according-to-mode))
286 (set (make-local-variable 'auto-fill-chars) fc))))
287
288 (defvar comment-continue)
289
290 (defun css-fill-paragraph (&optional justify)
291 (save-excursion
292 (let ((ppss (syntax-ppss))
293 (eol (line-end-position)))
294 (cond
295 ((and (nth 4 ppss)
296 (save-excursion
297 (goto-char (nth 8 ppss))
298 (forward-comment 1)
299 (prog1 (not (bolp))
300 (setq eol (point)))))
301 ;; Filling inside a comment whose comment-end marker is not \n.
302 ;; This code is meant to be generic, so that it works not only for
303 ;; css-mode but for all modes.
304 (save-restriction
305 (narrow-to-region (nth 8 ppss) eol)
306 (comment-normalize-vars) ;Will define comment-continue.
307 (let ((fill-paragraph-function nil)
308 (paragraph-separate
309 (if (and comment-continue
310 (string-match "[^ \t]" comment-continue))
311 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
312 "\\)?\\(?:" paragraph-separate "\\)")
313 paragraph-separate))
314 (paragraph-start
315 (if (and comment-continue
316 (string-match "[^ \t]" comment-continue))
317 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
318 "\\)?\\(?:" paragraph-start "\\)")
319 paragraph-start)))
320 (fill-paragraph justify)
321 ;; Don't try filling again.
322 t)))
323
324 ((and (null (nth 8 ppss))
325 (or (nth 1 ppss)
326 (and (ignore-errors
327 (down-list 1)
328 (when (<= (point) eol)
329 (setq ppss (syntax-ppss)))))))
330 (goto-char (nth 1 ppss))
331 (let ((end (save-excursion
332 (ignore-errors (forward-sexp 1) (copy-marker (point) t)))))
333 (when end
334 (while (re-search-forward "[{;}]" end t)
335 (cond
336 ;; This is a false positive inside a string or comment.
337 ((nth 8 (syntax-ppss)) nil)
338 ((eq (char-before) ?\})
339 (save-excursion
340 (forward-char -1)
341 (skip-chars-backward " \t")
342 (unless (bolp) (newline))))
343 (t
344 (while
345 (progn
346 (setq eol (line-end-position))
347 (and (forward-comment 1)
348 (> (point) eol)
349 ;; A multi-line comment should be on its own line.
350 (save-excursion (forward-comment -1)
351 (when (< (point) eol)
352 (newline)
353 t)))))
354 (if (< (point) eol) (newline)))))
355 (goto-char (nth 1 ppss))
356 (indent-region (line-beginning-position 2) end)
357 ;; Don't use the default filling code.
358 t)))))))
359
360 ;;; Navigation and indentation.
361
362 (defconst css-navigation-syntax-table
363 (let ((st (make-syntax-table css-mode-syntax-table)))
364 (map-char-table (lambda (c v)
365 ;; Turn punctuation (code = 1) into symbol (code = 1).
366 (if (eq (car-safe v) 1)
367 (set-char-table-range st c (cons 3 (cdr v)))))
368 st)
369 st))
370
371 (defun css-backward-sexp (n)
372 (let ((forward-sexp-function nil))
373 (if (< n 0) (css-forward-sexp (- n))
374 (while (> n 0)
375 (setq n (1- n))
376 (forward-comment (- (point-max)))
377 (if (not (eq (char-before) ?\;))
378 (backward-sexp 1)
379 (while (progn (backward-sexp 1)
380 (save-excursion
381 (forward-comment (- (point-max)))
382 ;; FIXME: We should also skip punctuation.
383 (not (or (bobp) (memq (char-before) '(?\; ?\{))))))))))))
384
385 (defun css-forward-sexp (n)
386 (let ((forward-sexp-function nil))
387 (if (< n 0) (css-backward-sexp (- n))
388 (while (> n 0)
389 (setq n (1- n))
390 (forward-comment (point-max))
391 (if (not (eq (char-after) ?\;))
392 (forward-sexp 1)
393 (while (progn (forward-sexp 1)
394 (save-excursion
395 (forward-comment (point-max))
396 ;; FIXME: We should also skip punctuation.
397 (not (memq (char-after) '(?\; ?\})))))))))))
398
399 (defun css-indent-calculate-virtual ()
400 (if (or (save-excursion (skip-chars-backward " \t") (bolp))
401 (if (looking-at "\\s(")
402 (save-excursion
403 (forward-char 1) (skip-chars-forward " \t")
404 (not (or (eolp) (looking-at comment-start-skip))))))
405 (current-column)
406 (css-indent-calculate)))
407
408 (defcustom css-indent-offset 4
409 "Basic size of one indentation step."
410 :version "22.2"
411 :type 'integer
412 :group 'css)
413
414 (defun css-indent-calculate ()
415 (let ((ppss (syntax-ppss))
416 pos)
417 (with-syntax-table css-navigation-syntax-table
418 (save-excursion
419 (cond
420 ;; Inside a string.
421 ((nth 3 ppss) 'noindent)
422 ;; Inside a comment.
423 ((nth 4 ppss)
424 (setq pos (point))
425 (forward-line -1)
426 (skip-chars-forward " \t")
427 (if (>= (nth 8 ppss) (point))
428 (progn
429 (goto-char (nth 8 ppss))
430 (if (eq (char-after pos) ?*)
431 (forward-char 1)
432 (if (not (looking-at comment-start-skip))
433 (error "Internal css-mode error")
434 (goto-char (match-end 0))))
435 (current-column))
436 (if (and (eq (char-after pos) ?*) (eq (char-after) ?*))
437 (current-column)
438 ;; 'noindent
439 (current-column)
440 )))
441 ;; In normal code.
442 (t
443 (or
444 (when (looking-at "\\s)")
445 (forward-char 1)
446 (backward-sexp 1)
447 (css-indent-calculate-virtual))
448 (when (looking-at comment-start-skip)
449 (forward-comment (point-max))
450 (css-indent-calculate))
451 (when (save-excursion (forward-comment (- (point-max)))
452 (setq pos (point))
453 (eq (char-syntax (preceding-char)) ?\())
454 (goto-char (1- pos))
455 (if (not (looking-at "\\s([ \t]*"))
456 (error "Internal css-mode error")
457 (if (or (memq (char-after (match-end 0)) '(?\n nil))
458 (save-excursion (goto-char (match-end 0))
459 (looking-at comment-start-skip)))
460 (+ (css-indent-calculate-virtual) css-indent-offset)
461 (progn (goto-char (match-end 0)) (current-column)))))
462 (progn
463 (css-backward-sexp 1)
464 (if (looking-at "\\s(")
465 (css-indent-calculate)
466 (css-indent-calculate-virtual))))))))))
467
468
469 (defun css-indent-line ()
470 "Indent current line according to CSS indentation rules."
471 (interactive)
472 (let* ((savep (point))
473 (forward-sexp-function nil)
474 (indent (condition-case nil
475 (save-excursion
476 (forward-line 0)
477 (skip-chars-forward " \t")
478 (if (>= (point) savep) (setq savep nil))
479 (css-indent-calculate))
480 (error nil))))
481 (if (not (numberp indent)) 'noindent
482 (if savep
483 (save-excursion (indent-line-to indent))
484 (indent-line-to indent)))))
485
486 (provide 'css-mode)
487 ;; arch-tag: b4d8b8e2-b130-4e74-b3aa-cd8f1ab659d0
488 ;;; css-mode.el ends here