Misc fixes, and use lexical-binding in more files.
[emacs.git] / lisp / textmodes / css-mode.el
blobef51fb250355a555b45d3679b1fb1d964e23a0dc
1 ;;; css-mode.el --- Major mode to edit CSS files -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2011 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/>.
23 ;;; Commentary:
25 ;; Yet another CSS mode.
27 ;;; Todo:
29 ;; - electric ; and }
30 ;; - filling code with auto-fill-mode
31 ;; - completion
32 ;; - fix font-lock errors with multi-line selectors
34 ;;; Code:
36 (defgroup css nil
37 "Cascading Style Sheets (CSS) editing mode."
38 :group 'languages)
40 (eval-when-compile (require 'cl))
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))))
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))
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)))))
112 (push (cons prop (css-extract-parse-val-grammar vals-string props))
113 props)))))
114 props)))
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]+\\)',")))
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.")
129 (defconst css-at-ids
130 '("charset" "font-face" "import" "media" "page")
131 "Identifiers that appear in the form @foo.")
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.")
140 (defconst css-media-ids
141 '("all" "aural" "bitmap" "continuous" "grid" "paged" "static" "tactile"
142 "visual")
143 "Identifiers for types of media.")
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.")
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)
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))
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 "+"))
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.")
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)))))
264 (defvar css-font-lock-defaults
265 '(css-font-lock-keywords nil t))
267 ;;;###autoload
268 (define-derived-mode css-mode fundamental-mode "CSS"
269 "Major mode to edit Cascading Style Sheets."
270 (set (make-local-variable 'font-lock-defaults) css-font-lock-defaults)
271 (set (make-local-variable 'comment-start) "/*")
272 (set (make-local-variable 'comment-start-skip) "/\\*+[ \t]*")
273 (set (make-local-variable 'comment-end) "*/")
274 (set (make-local-variable 'comment-end-skip) "[ \t]*\\*+/")
275 (set (make-local-variable 'forward-sexp-function) 'css-forward-sexp)
276 (set (make-local-variable 'parse-sexp-ignore-comments) t)
277 (set (make-local-variable 'indent-line-function) 'css-indent-line)
278 (set (make-local-variable 'fill-paragraph-function)
279 'css-fill-paragraph)
280 (when css-electric-keys
281 (let ((fc (make-char-table 'auto-fill-chars)))
282 (set-char-table-parent fc auto-fill-chars)
283 (dolist (c css-electric-keys)
284 (aset fc c 'indent-according-to-mode))
285 (set (make-local-variable 'auto-fill-chars) fc))))
287 (defvar comment-continue)
289 (defun css-fill-paragraph (&optional justify)
290 (save-excursion
291 (let ((ppss (syntax-ppss))
292 (eol (line-end-position)))
293 (cond
294 ((and (nth 4 ppss)
295 (save-excursion
296 (goto-char (nth 8 ppss))
297 (forward-comment 1)
298 (prog1 (not (bolp))
299 (setq eol (point)))))
300 ;; Filling inside a comment whose comment-end marker is not \n.
301 ;; This code is meant to be generic, so that it works not only for
302 ;; css-mode but for all modes.
303 (save-restriction
304 (narrow-to-region (nth 8 ppss) eol)
305 (comment-normalize-vars) ;Will define comment-continue.
306 (let ((fill-paragraph-function nil)
307 (paragraph-separate
308 (if (and comment-continue
309 (string-match "[^ \t]" comment-continue))
310 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
311 "\\)?\\(?:" paragraph-separate "\\)")
312 paragraph-separate))
313 (paragraph-start
314 (if (and comment-continue
315 (string-match "[^ \t]" comment-continue))
316 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
317 "\\)?\\(?:" paragraph-start "\\)")
318 paragraph-start)))
319 (fill-paragraph justify)
320 ;; Don't try filling again.
321 t)))
323 ((and (null (nth 8 ppss))
324 (or (nth 1 ppss)
325 (and (ignore-errors
326 (down-list 1)
327 (when (<= (point) eol)
328 (setq ppss (syntax-ppss)))))))
329 (goto-char (nth 1 ppss))
330 (let ((end (save-excursion
331 (ignore-errors (forward-sexp 1) (copy-marker (point) t)))))
332 (when end
333 (while (re-search-forward "[{;}]" end t)
334 (cond
335 ;; This is a false positive inside a string or comment.
336 ((nth 8 (syntax-ppss)) nil)
337 ((eq (char-before) ?\})
338 (save-excursion
339 (forward-char -1)
340 (skip-chars-backward " \t")
341 (unless (bolp) (newline))))
343 (while
344 (progn
345 (setq eol (line-end-position))
346 (and (forward-comment 1)
347 (> (point) eol)
348 ;; A multi-line comment should be on its own line.
349 (save-excursion (forward-comment -1)
350 (when (< (point) eol)
351 (newline)
352 t)))))
353 (if (< (point) eol) (newline)))))
354 (goto-char (nth 1 ppss))
355 (indent-region (line-beginning-position 2) end)
356 ;; Don't use the default filling code.
357 t)))))))
359 ;;; Navigation and indentation.
361 (defconst css-navigation-syntax-table
362 (let ((st (make-syntax-table css-mode-syntax-table)))
363 (map-char-table (lambda (c v)
364 ;; Turn punctuation (code = 1) into symbol (code = 1).
365 (if (eq (car-safe v) 1)
366 (set-char-table-range st c (cons 3 (cdr v)))))
368 st))
370 (defun css-backward-sexp (n)
371 (let ((forward-sexp-function nil))
372 (if (< n 0) (css-forward-sexp (- n))
373 (while (> n 0)
374 (setq n (1- n))
375 (forward-comment (- (point-max)))
376 (if (not (eq (char-before) ?\;))
377 (backward-sexp 1)
378 (while (progn (backward-sexp 1)
379 (save-excursion
380 (forward-comment (- (point-max)))
381 ;; FIXME: We should also skip punctuation.
382 (not (or (bobp) (memq (char-before) '(?\; ?\{))))))))))))
384 (defun css-forward-sexp (n)
385 (let ((forward-sexp-function nil))
386 (if (< n 0) (css-backward-sexp (- n))
387 (while (> n 0)
388 (setq n (1- n))
389 (forward-comment (point-max))
390 (if (not (eq (char-after) ?\;))
391 (forward-sexp 1)
392 (while (progn (forward-sexp 1)
393 (save-excursion
394 (forward-comment (point-max))
395 ;; FIXME: We should also skip punctuation.
396 (not (memq (char-after) '(?\; ?\})))))))))))
398 (defun css-indent-calculate-virtual ()
399 (if (or (save-excursion (skip-chars-backward " \t") (bolp))
400 (if (looking-at "\\s(")
401 (save-excursion
402 (forward-char 1) (skip-chars-forward " \t")
403 (not (or (eolp) (looking-at comment-start-skip))))))
404 (current-column)
405 (css-indent-calculate)))
407 (defcustom css-indent-offset 4
408 "Basic size of one indentation step."
409 :version "22.2"
410 :type 'integer
411 :group 'css)
413 (defun css-indent-calculate ()
414 (let ((ppss (syntax-ppss))
415 pos)
416 (with-syntax-table css-navigation-syntax-table
417 (save-excursion
418 (cond
419 ;; Inside a string.
420 ((nth 3 ppss) 'noindent)
421 ;; Inside a comment.
422 ((nth 4 ppss)
423 (setq pos (point))
424 (forward-line -1)
425 (skip-chars-forward " \t")
426 (if (>= (nth 8 ppss) (point))
427 (progn
428 (goto-char (nth 8 ppss))
429 (if (eq (char-after pos) ?*)
430 (forward-char 1)
431 (if (not (looking-at comment-start-skip))
432 (error "Internal css-mode error")
433 (goto-char (match-end 0))))
434 (current-column))
435 (if (and (eq (char-after pos) ?*) (eq (char-after) ?*))
436 (current-column)
437 ;; 'noindent
438 (current-column)
440 ;; In normal code.
443 (when (looking-at "\\s)")
444 (forward-char 1)
445 (backward-sexp 1)
446 (css-indent-calculate-virtual))
447 (when (looking-at comment-start-skip)
448 (forward-comment (point-max))
449 (css-indent-calculate))
450 (when (save-excursion (forward-comment (- (point-max)))
451 (setq pos (point))
452 (eq (char-syntax (preceding-char)) ?\())
453 (goto-char (1- pos))
454 (if (not (looking-at "\\s([ \t]*"))
455 (error "Internal css-mode error")
456 (if (or (memq (char-after (match-end 0)) '(?\n nil))
457 (save-excursion (goto-char (match-end 0))
458 (looking-at comment-start-skip)))
459 (+ (css-indent-calculate-virtual) css-indent-offset)
460 (progn (goto-char (match-end 0)) (current-column)))))
461 (progn
462 (css-backward-sexp 1)
463 (if (looking-at "\\s(")
464 (css-indent-calculate)
465 (css-indent-calculate-virtual))))))))))
468 (defun css-indent-line ()
469 "Indent current line according to CSS indentation rules."
470 (interactive)
471 (let* ((savep (point))
472 (forward-sexp-function nil)
473 (indent (condition-case nil
474 (save-excursion
475 (forward-line 0)
476 (skip-chars-forward " \t")
477 (if (>= (point) savep) (setq savep nil))
478 (css-indent-calculate))
479 (error nil))))
480 (if (not (numberp indent)) 'noindent
481 (if savep
482 (save-excursion (indent-line-to indent))
483 (indent-line-to indent)))))
485 (provide 'css-mode)
486 ;;; css-mode.el ends here