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