]> code.delx.au - gnu-emacs/blob - lisp/textmodes/css-mode.el
Merge from emacs--rel--22
[gnu-emacs] / lisp / textmodes / css-mode.el
1 ;;; css-mode.el --- Major mode to edit CSS files
2
3 ;; Copyright (C) 2006, 2007 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Keywords: hypermedia
7
8 ;; This file is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 3, or (at your option)
11 ;; any later version.
12
13 ;; This file is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING. If not, write to
20 ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21 ;; Boston, MA 02110-1301, USA.
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 :type '(repeat character)
181 :options '((?\} ?\;))
182 :group 'css)
183
184 (defvar css-mode-syntax-table
185 (let ((st (make-syntax-table)))
186 ;; C-style comments.
187 (modify-syntax-entry ?/ ". 14" st)
188 (modify-syntax-entry ?* ". 23" st)
189 ;; Strings.
190 (modify-syntax-entry ?\" "\"" st)
191 (modify-syntax-entry ?\' "\"" st)
192 ;; Blocks.
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)
207 st))
208
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-name-re (concat css-nmchar-re "+"))
215
216 (defface css-selector '((t :inherit font-lock-function-name-face))
217 "Face to use for selectors."
218 :group 'css)
219 (defface css-property '((t :inherit font-lock-variable-name-face))
220 "Face to use for properties."
221 :group 'css)
222
223 (defvar css-font-lock-keywords
224 `(("!\\s-*important" . font-lock-builtin-face)
225 ;; Atrules keywords. IDs not in css-at-ids are valid (ignored).
226 ;; In fact the regexp should probably be
227 ;; (,(concat "\\(@" css-ident-re "\\)\\([ \t\n][^;{]*\\)[;{]")
228 ;; (1 font-lock-builtin-face))
229 ;; Since "An at-rule consists of everything up to and including the next
230 ;; semicolon (;) or the next block, whichever comes first."
231 (,(concat "@" css-ident-re) . font-lock-builtin-face)
232 ;; Selectors.
233 ;; FIXME: attribute selectors don't work well because they may contain
234 ;; strings which have already been highlighted as f-l-string-face and
235 ;; thus prevent this highlighting from being applied (actually now that
236 ;; I use `append' this should work better). But really the part of hte
237 ;; selector between [...] should simply not be highlighted.
238 (,(concat "^\\([ \t]*[^@:{\n][^:{\n]+\\(?::" (regexp-opt css-pseudo-ids t)
239 "\\(?:([^)]+)\\)?[^:{\n]*\\)*\\)\\(?:\n[ \t]*\\)*{")
240 (1 'css-selector append))
241 ;; In the above rule, we allow the open-brace to be on some subsequent
242 ;; line. This will only work if we properly mark the intervening text
243 ;; as being part of a multiline element (and even then, this only
244 ;; ensures proper refontification, but not proper discovery).
245 ("^[ \t]*{" (0 (save-excursion
246 (goto-char (match-beginning 0))
247 (skip-chars-backward " \n\t")
248 (put-text-property (point) (match-end 0)
249 'font-lock-multiline t)
250 ;; No face.
251 nil)))
252 ;; Properties. Again, we don't limit ourselves to css-property-ids.
253 (,(concat "\\(?:[{;]\\|^\\)[ \t]*\\(" css-ident-re "\\)\\s-*:")
254 (1 'css-property))))
255
256 (defvar css-font-lock-defaults
257 '(css-font-lock-keywords nil t))
258
259 (unless (fboundp 'prog-mode) (defalias 'prog-mode 'fundamental-mode))
260
261 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.css\\'" . css-mode))
262 ;;;###autoload
263 (define-derived-mode css-mode prog-mode "CSS"
264 "Major mode to edit Cascading Style Sheets."
265 (set (make-local-variable 'font-lock-defaults) css-font-lock-defaults)
266 (set (make-local-variable 'comment-start) "/*")
267 (set (make-local-variable 'comment-start-skip) "/\\*+[ \t]*")
268 (set (make-local-variable 'comment-end) "*/")
269 (set (make-local-variable 'comment-end-skip) "[ \t]*\\*+/")
270 (set (make-local-variable 'forward-sexp-function) 'css-forward-sexp)
271 (set (make-local-variable 'parse-sexp-ignore-comments) t)
272 (set (make-local-variable 'indent-line-function) 'css-indent-line)
273 (set (make-local-variable 'fill-paragraph-function)
274 'css-fill-paragraph)
275 (when css-electric-keys
276 (let ((fc (make-char-table 'auto-fill-chars)))
277 (set-char-table-parent fc auto-fill-chars)
278 (dolist (c css-electric-keys)
279 (aset fc c 'indent-according-to-mode))
280 (set (make-local-variable 'auto-fill-chars) fc))))
281
282 (defvar comment-continue)
283
284 (defun css-fill-paragraph (&optional justify)
285 (save-excursion
286 (let ((ppss (syntax-ppss))
287 (eol (line-end-position)))
288 (cond
289 ((and (nth 4 ppss)
290 (save-excursion
291 (goto-char (nth 8 ppss))
292 (forward-comment 1)
293 (prog1 (not (bolp))
294 (setq eol (point)))))
295 ;; Filling inside a comment whose comment-end marker is not \n.
296 ;; This code is meant to be generic, so that it works not only for
297 ;; css-mode but for all modes.
298 (save-restriction
299 (narrow-to-region (nth 8 ppss) eol)
300 (comment-normalize-vars) ;Will define comment-continue.
301 (let ((fill-paragraph-function nil)
302 (paragraph-separate
303 (if (and comment-continue
304 (string-match "[^ \t]" comment-continue))
305 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
306 "\\)?\\(?:" paragraph-separate "\\)")
307 paragraph-separate))
308 (paragraph-start
309 (if (and comment-continue
310 (string-match "[^ \t]" comment-continue))
311 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
312 "\\)?\\(?:" paragraph-start "\\)")
313 paragraph-start)))
314 (fill-paragraph justify)
315 ;; Don't try filling again.
316 t)))
317
318 ((and (null (nth 8 ppss))
319 (or (nth 1 ppss)
320 (and (ignore-errors
321 (down-list 1)
322 (when (<= (point) eol)
323 (setq ppss (syntax-ppss)))))))
324 (goto-char (nth 1 ppss))
325 (let ((end (save-excursion
326 (ignore-errors (forward-sexp 1) (copy-marker (point) t)))))
327 (when end
328 (while (re-search-forward "[{;}]" end t)
329 (cond
330 ;; This is a false positive inside a string or comment.
331 ((nth 8 (syntax-ppss)) nil)
332 ((eq (char-before) ?\})
333 (save-excursion
334 (forward-char -1)
335 (skip-chars-backward " \t")
336 (unless (bolp) (newline))))
337 (t
338 (while
339 (progn
340 (setq eol (line-end-position))
341 (and (forward-comment 1)
342 (> (point) eol)
343 ;; A multi-line comment should be on its own line.
344 (save-excursion (forward-comment -1)
345 (when (< (point) eol)
346 (newline)
347 t)))))
348 (if (< (point) eol) (newline)))))
349 (goto-char (nth 1 ppss))
350 (indent-region (line-beginning-position 2) end)
351 ;; Don't use the default filling code.
352 t)))))))
353
354 ;;; Navigation and indentation.
355
356 (defconst css-navigation-syntax-table
357 (let ((st (make-syntax-table css-mode-syntax-table)))
358 (map-char-table (lambda (c v)
359 ;; Turn punctuation (code = 1) into symbol (code = 1).
360 (if (eq (car-safe v) 1)
361 (set-char-table-range st c (cons 3 (cdr v)))))
362 st)
363 st))
364
365 (defun css-backward-sexp (n)
366 (let ((forward-sexp-function nil))
367 (if (< n 0) (css-forward-sexp (- n))
368 (while (> n 0)
369 (setq n (1- n))
370 (forward-comment (- (point-max)))
371 (if (not (eq (char-before) ?\;))
372 (backward-sexp 1)
373 (while (progn (backward-sexp 1)
374 (save-excursion
375 (forward-comment (- (point-max)))
376 ;; FIXME: We should also skip punctuation.
377 (not (memq (char-before) '(?\; ?\{)))))))))))
378
379 (defun css-forward-sexp (n)
380 (let ((forward-sexp-function nil))
381 (if (< n 0) (css-backward-sexp (- n))
382 (while (> n 0)
383 (setq n (1- n))
384 (forward-comment (point-max))
385 (if (not (eq (char-after) ?\;))
386 (forward-sexp 1)
387 (while (progn (forward-sexp 1)
388 (save-excursion
389 (forward-comment (point-max))
390 ;; FIXME: We should also skip punctuation.
391 (not (memq (char-after) '(?\; ?\})))))))))))
392
393 (defun css-indent-calculate-virtual ()
394 (if (or (save-excursion (skip-chars-backward " \t") (bolp))
395 (if (looking-at "\\s(")
396 (save-excursion
397 (forward-char 1) (skip-chars-forward " \t")
398 (not (or (eolp) (looking-at comment-start-skip))))))
399 (current-column)
400 (css-indent-calculate)))
401
402 (defcustom css-indent-offset 4
403 "Basic size of one indentation step."
404 :type 'integer
405 :group 'css)
406
407 (defun css-indent-calculate ()
408 (let ((ppss (syntax-ppss))
409 pos)
410 (with-syntax-table css-navigation-syntax-table
411 (save-excursion
412 (cond
413 ;; Inside a string.
414 ((nth 3 ppss) 'noindent)
415 ;; Inside a comment.
416 ((nth 4 ppss)
417 (setq pos (point))
418 (forward-line -1)
419 (skip-chars-forward " \t")
420 (if (>= (nth 8 ppss) (point))
421 (progn
422 (goto-char (nth 8 ppss))
423 (if (eq (char-after pos) ?*)
424 (forward-char 1)
425 (if (not (looking-at comment-start-skip))
426 (error "Internal css-mode error")
427 (goto-char (match-end 0))))
428 (current-column))
429 (if (and (eq (char-after pos) ?*) (eq (char-after) ?*))
430 (current-column)
431 ;; 'noindent
432 (current-column)
433 )))
434 ;; In normal code.
435 (t
436 (or
437 (when (looking-at "\\s)")
438 (forward-char 1)
439 (backward-sexp 1)
440 (css-indent-calculate-virtual))
441 (when (looking-at comment-start-skip)
442 (forward-comment (point-max))
443 (css-indent-calculate))
444 (when (save-excursion (forward-comment (- (point-max)))
445 (setq pos (point))
446 (eq (char-syntax (preceding-char)) ?\())
447 (goto-char (1- pos))
448 (if (not (looking-at "\\s([ \t]*"))
449 (error "Internal css-mode error")
450 (if (or (memq (char-after (match-end 0)) '(?\n nil))
451 (save-excursion (goto-char (match-end 0))
452 (looking-at comment-start-skip)))
453 (+ (css-indent-calculate-virtual) css-indent-offset)
454 (progn (goto-char (match-end 0)) (current-column)))))
455 (progn
456 (css-backward-sexp 1)
457 (if (looking-at "\\s(")
458 (css-indent-calculate)
459 (css-indent-calculate-virtual))))))))))
460
461
462 (defun css-indent-line ()
463 "Indent current line according to CSS indentation rules."
464 (interactive)
465 (let* ((savep (point))
466 (forward-sexp-function nil)
467 (indent (condition-case nil
468 (save-excursion
469 (forward-line 0)
470 (skip-chars-forward " \t")
471 (if (>= (point) savep) (setq savep nil))
472 (css-indent-calculate))
473 (error nil))))
474 (if (not (numberp indent)) 'noindent
475 (if savep
476 (save-excursion (indent-line-to indent))
477 (indent-line-to indent)))))
478
479 (provide 'css-mode)
480 ;; arch-tag: b4d8b8e2-b130-4e74-b3aa-cd8f1ab659d0
481 ;;; css-mode.el ends here