Fix documentation of 'menu-set-font' and 'set-frame-font'
[emacs.git] / lisp / textmodes / css-mode.el
blob424cdb7f8308afacfaa07ffb064110379633d8ec
1 ;;; css-mode.el --- Major mode to edit CSS files -*- lexical-binding: t -*-
3 ;; Copyright (C) 2006-2015 Free Software Foundation, Inc.
5 ;; Author: Stefan Monnier <monnier@iro.umontreal.ca>
6 ;; Maintainer: Simen Heggestøyl <simenheg@gmail.com>
7 ;; Keywords: hypermedia
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; Yet another CSS mode.
28 ;;; Todo:
30 ;; - electric ; and }
31 ;; - filling code with auto-fill-mode
32 ;; - attribute value completion
33 ;; - fix font-lock errors with multi-line selectors
35 ;;; Code:
37 (defgroup css nil
38 "Cascading Style Sheets (CSS) editing mode."
39 :group 'languages)
41 (defconst css-pseudo-class-ids
42 '("active" "checked" "disabled" "empty" "enabled" "first"
43 "first-child" "first-of-type" "focus" "hover" "indeterminate" "lang"
44 "last-child" "last-of-type" "left" "link" "not" "nth-child"
45 "nth-last-child" "nth-last-of-type" "nth-of-type" "only-child"
46 "only-of-type" "right" "root" "target" "visited")
47 "Identifiers for pseudo-classes.")
49 (defconst css-pseudo-element-ids
50 '("after" "before" "first-letter" "first-line")
51 "Identifiers for pseudo-elements.")
53 (defconst css-at-ids
54 '("charset" "font-face" "import" "media" "namespace" "page")
55 "Identifiers that appear in the form @foo.")
57 (defconst css-descriptor-ids
58 '("ascent" "baseline" "bbox" "cap-height" "centerline" "definition-src"
59 "descent" "font-family" "font-size" "font-stretch" "font-style"
60 "font-variant" "font-weight" "mathline" "panose-1" "slope" "src" "stemh"
61 "stemv" "topline" "unicode-range" "units-per-em" "widths" "x-height")
62 "Identifiers for font descriptors.")
64 (defconst css-media-ids
65 '("all" "aural" "bitmap" "continuous" "grid" "paged" "static" "tactile"
66 "visual")
67 "Identifiers for types of media.")
69 (defconst css-property-ids
70 '(;; CSS 2.1 properties (http://www.w3.org/TR/CSS21/propidx.html).
72 ;; Properties duplicated by any of the CSS3 modules below have
73 ;; been removed.
74 "azimuth" "border-collapse" "border-spacing" "bottom"
75 "caption-side" "clear" "clip" "content" "counter-increment"
76 "counter-reset" "cue" "cue-after" "cue-before" "direction" "display"
77 "elevation" "empty-cells" "float" "height" "left" "line-height"
78 "list-style" "list-style-image" "list-style-position"
79 "list-style-type" "margin" "margin-bottom" "margin-left"
80 "margin-right" "margin-top" "max-height" "max-width" "min-height"
81 "min-width" "orphans" "overflow" "padding" "padding-bottom"
82 "padding-left" "padding-right" "padding-top" "page-break-after"
83 "page-break-before" "page-break-inside" "pause" "pause-after"
84 "pause-before" "pitch" "pitch-range" "play-during" "position"
85 "quotes" "richness" "right" "speak" "speak-header" "speak-numeral"
86 "speak-punctuation" "speech-rate" "stress" "table-layout" "top"
87 "unicode-bidi" "vertical-align" "visibility" "voice-family" "volume"
88 "widows" "width" "z-index"
90 ;; CSS Animations
91 ;; (http://www.w3.org/TR/css3-animations/#property-index)
92 "animation" "animation-delay" "animation-direction"
93 "animation-duration" "animation-fill-mode"
94 "animation-iteration-count" "animation-name"
95 "animation-play-state" "animation-timing-function"
97 ;; CSS Backgrounds and Borders Module Level 3
98 ;; (http://www.w3.org/TR/css3-background/#property-index)
99 "background" "background-attachment" "background-clip"
100 "background-color" "background-image" "background-origin"
101 "background-position" "background-repeat" "background-size"
102 "border" "border-bottom" "border-bottom-color"
103 "border-bottom-left-radius" "border-bottom-right-radius"
104 "border-bottom-style" "border-bottom-width" "border-color"
105 "border-image" "border-image-outset" "border-image-repeat"
106 "border-image-slice" "border-image-source" "border-image-width"
107 "border-left" "border-left-color" "border-left-style"
108 "border-left-width" "border-radius" "border-right"
109 "border-right-color" "border-right-style" "border-right-width"
110 "border-style" "border-top" "border-top-color"
111 "border-top-left-radius" "border-top-right-radius"
112 "border-top-style" "border-top-width" "border-width" "box-shadow"
114 ;; CSS Basic User Interface Module Level 3 (CSS3 UI)
115 ;; (http://www.w3.org/TR/css3-ui/#property-index)
116 "box-sizing" "caret-color" "cursor" "nav-down" "nav-left"
117 "nav-right" "nav-up" "outline" "outline-color" "outline-offset"
118 "outline-style" "outline-width" "resize" "text-overflow"
120 ;; CSS Color Module Level 3
121 ;; (http://www.w3.org/TR/css3-color/#property)
122 "color" "opacity"
124 ;; CSS Flexible Box Layout Module Level 1
125 ;; (http://www.w3.org/TR/css-flexbox-1/#property-index)
126 "align-content" "align-items" "align-self" "flex" "flex-basis"
127 "flex-direction" "flex-flow" "flex-grow" "flex-shrink" "flex-wrap"
128 "justify-content" "order"
130 ;; CSS Fonts Module Level 3
131 ;; (http://www.w3.org/TR/css3-fonts/#property-index)
132 "font" "font-family" "font-feature-settings" "font-kerning"
133 "font-language-override" "font-size" "font-size-adjust"
134 "font-stretch" "font-style" "font-synthesis" "font-variant"
135 "font-variant-alternates" "font-variant-caps"
136 "font-variant-east-asian" "font-variant-ligatures"
137 "font-variant-numeric" "font-variant-position" "font-weight"
139 ;; CSS Text Decoration Module Level 3
140 ;; (http://dev.w3.org/csswg/css-text-decor-3/#property-index)
141 "text-decoration" "text-decoration-color" "text-decoration-line"
142 "text-decoration-skip" "text-decoration-style" "text-emphasis"
143 "text-emphasis-color" "text-emphasis-position" "text-emphasis-style"
144 "text-shadow" "text-underline-position"
146 ;; CSS Text Module Level 3
147 ;; (http://www.w3.org/TR/css3-text/#property-index)
148 "hanging-punctuation" "hyphens" "letter-spacing" "line-break"
149 "overflow-wrap" "tab-size" "text-align" "text-align-last"
150 "text-indent" "text-justify" "text-transform" "white-space"
151 "word-break" "word-spacing" "word-wrap"
153 ;; CSS Transforms Module Level 1
154 ;; (http://www.w3.org/TR/css3-2d-transforms/#property-index)
155 "backface-visibility" "perspective" "perspective-origin"
156 "transform" "transform-origin" "transform-style"
158 ;; CSS Transitions
159 ;; (http://www.w3.org/TR/css3-transitions/#property-index)
160 "transition" "transition-delay" "transition-duration"
161 "transition-property" "transition-timing-function"
163 ;; Filter Effects Module Level 1
164 ;; (http://www.w3.org/TR/filter-effects/#property-index)
165 "color-interpolation-filters" "filter" "flood-color"
166 "flood-opacity" "lighting-color")
167 "Identifiers for properties.")
169 (defcustom css-electric-keys '(?\} ?\;) ;; '()
170 "Self inserting keys which should trigger re-indentation."
171 :version "22.2"
172 :type '(repeat character)
173 :options '((?\} ?\;))
174 :group 'css)
176 (defvar css-mode-syntax-table
177 (let ((st (make-syntax-table)))
178 ;; C-style comments.
179 (modify-syntax-entry ?/ ". 14" st)
180 (modify-syntax-entry ?* ". 23b" st)
181 ;; Strings.
182 (modify-syntax-entry ?\" "\"" st)
183 (modify-syntax-entry ?\' "\"" st)
184 ;; Blocks.
185 (modify-syntax-entry ?\{ "(}" st)
186 (modify-syntax-entry ?\} "){" st)
187 ;; Args in url(...) thingies and other "function calls".
188 (modify-syntax-entry ?\( "()" st)
189 (modify-syntax-entry ?\) ")(" st)
190 ;; To match attributes in selectors.
191 (modify-syntax-entry ?\[ "(]" st)
192 (modify-syntax-entry ?\] ")[" st)
193 ;; Special chars that sometimes come at the beginning of words.
194 (modify-syntax-entry ?@ "'" st)
195 ;; (modify-syntax-entry ?: "'" st)
196 (modify-syntax-entry ?# "'" st)
197 ;; Distinction between words and symbols.
198 (modify-syntax-entry ?- "_" st)
199 st))
201 (defconst css-escapes-re
202 "\\\\\\(?:[^\000-\037\177]\\|[0-9a-fA-F]+[ \n\t\r\f]?\\)")
203 (defconst css-nmchar-re (concat "\\(?:[-[:alnum:]]\\|" css-escapes-re "\\)"))
204 (defconst css-nmstart-re (concat "\\(?:[[:alpha:]]\\|" css-escapes-re "\\)"))
205 (defconst css-ident-re ;; (concat css-nmstart-re css-nmchar-re "*")
206 ;; Apparently, "at rules" names can start with a dash, e.g. @-moz-keyframes.
207 (concat css-nmchar-re "+"))
208 (defconst css-proprietary-nmstart-re ;; Vendor-specific properties.
209 (concat "[-_]" (regexp-opt '("ms" "moz" "o" "khtml" "webkit")) "-"))
210 (defconst css-name-re (concat css-nmchar-re "+"))
212 (defconst scss--hash-re "#\\(?:{[$-_[:alnum:]]+}\\|[[:alnum:]]+\\)")
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)
220 (defface css-proprietary-property '((t :inherit (css-property italic)))
221 "Face to use for vendor-specific properties.")
223 (defun css--font-lock-keywords (&optional sassy)
224 `((,(concat "!\\s-*"
225 (regexp-opt (append (if sassy '("global"))
226 '("important"))))
227 (0 font-lock-builtin-face))
228 ;; Atrules keywords. IDs not in css-at-ids are valid (ignored).
229 ;; In fact the regexp should probably be
230 ;; (,(concat "\\(@" css-ident-re "\\)\\([ \t\n][^;{]*\\)[;{]")
231 ;; (1 font-lock-builtin-face))
232 ;; Since "An at-rule consists of everything up to and including the next
233 ;; semicolon (;) or the next block, whichever comes first."
234 (,(concat "@" css-ident-re) (0 font-lock-builtin-face))
235 ;; Selectors.
236 ;; FIXME: attribute selectors don't work well because they may contain
237 ;; strings which have already been highlighted as f-l-string-face and
238 ;; thus prevent this highlighting from being applied (actually now that
239 ;; I use `keep' this should work better). But really the part of the
240 ;; selector between [...] should simply not be highlighted.
241 (,(concat
242 "^[ \t]*\\("
243 (if (not sassy)
244 ;; We don't allow / as first char, so as not to
245 ;; take a comment as the beginning of a selector.
246 "[^@/:{} \t\n][^:{}]+"
247 ;; Same as for non-sassy except we do want to allow { and }
248 ;; chars in selectors in the case of #{$foo}
249 ;; variable interpolation!
250 (concat "\\(?:" scss--hash-re
251 "\\|[^@/:{} \t\n#]\\)"
252 "[^:{}#]*\\(?:" scss--hash-re "[^:{}#]*\\)*"))
253 ;; Even though pseudo-elements should be prefixed by ::, a
254 ;; single colon is accepted for backward compatibility.
255 "\\(?:\\(:" (regexp-opt (append css-pseudo-class-ids
256 css-pseudo-element-ids) t)
257 "\\|\\::" (regexp-opt css-pseudo-element-ids t) "\\)"
258 "\\(?:([^\)]+)\\)?"
259 (if (not sassy)
260 "[^:{}\n]*"
261 (concat "[^:{}\n#]*\\(?:" scss--hash-re "[^:{}\n#]*\\)*"))
262 "\\)*"
263 "\\)\\(?:\n[ \t]*\\)*{")
264 (1 'css-selector keep))
265 ;; In the above rule, we allow the open-brace to be on some subsequent
266 ;; line. This will only work if we properly mark the intervening text
267 ;; as being part of a multiline element (and even then, this only
268 ;; ensures proper refontification, but not proper discovery).
269 ("^[ \t]*{" (0 (save-excursion
270 (goto-char (match-beginning 0))
271 (skip-chars-backward " \n\t")
272 (put-text-property (point) (match-end 0)
273 'font-lock-multiline t)
274 ;; No face.
275 nil)))
276 ;; Properties. Again, we don't limit ourselves to css-property-ids.
277 (,(concat "\\(?:[{;]\\|^\\)[ \t]*\\("
278 "\\(?:\\(" css-proprietary-nmstart-re "\\)\\|"
279 css-nmstart-re "\\)" css-nmchar-re "*"
280 "\\)\\s-*:")
281 (1 (if (match-end 2) 'css-proprietary-property 'css-property)))))
283 (defvar css-font-lock-keywords (css--font-lock-keywords))
285 (defvar css-font-lock-defaults
286 '(css-font-lock-keywords nil t))
288 (defcustom css-indent-offset 4
289 "Basic size of one indentation step."
290 :version "22.2"
291 :type 'integer)
293 (require 'smie)
295 (defconst css-smie-grammar
296 (smie-prec2->grammar
297 (smie-precs->prec2 '((assoc ";") (assoc ",") (left ":")))))
299 (defun css-smie--forward-token ()
300 (cond
301 ((and (eq (char-before) ?\})
302 (scss-smie--not-interpolation-p)
303 ;; FIXME: If the next char is not whitespace, what should we do?
304 (or (memq (char-after) '(?\s ?\t ?\n))
305 (looking-at comment-start-skip)))
306 (if (memq (char-after) '(?\s ?\t ?\n))
307 (forward-char 1) (forward-comment 1))
308 ";")
309 ((progn (forward-comment (point-max))
310 (looking-at "[;,:]"))
311 (forward-char 1) (match-string 0))
312 (t (smie-default-forward-token))))
314 (defun css-smie--backward-token ()
315 (let ((pos (point)))
316 (forward-comment (- (point)))
317 (cond
318 ;; FIXME: If the next char is not whitespace, what should we do?
319 ((and (eq (char-before) ?\}) (scss-smie--not-interpolation-p)
320 (> pos (point))) ";")
321 ((memq (char-before) '(?\; ?\, ?\:))
322 (forward-char -1) (string (char-after)))
323 (t (smie-default-backward-token)))))
325 (defun css-smie-rules (kind token)
326 (pcase (cons kind token)
327 (`(:elem . basic) css-indent-offset)
328 (`(:elem . arg) 0)
329 (`(:list-intro . ,(or `";" `"")) t) ;"" stands for BOB (bug#15467).
330 (`(:before . "{")
331 (when (smie-rule-hanging-p)
332 (smie-backward-sexp ";")
333 (smie-indent-virtual)))
334 (`(:before . ,(or "{" "("))
335 (if (smie-rule-hanging-p) (smie-rule-parent 0)))))
337 ;;; Completion
339 (defun css--complete-property ()
340 "Complete property at point."
341 (save-excursion
342 (let ((pos (point)))
343 (skip-chars-backward "-[:alnum:]")
344 (let ((start (point)))
345 (skip-chars-backward " \t\r\n")
346 (when (memq (char-before) '(?\{ ?\;))
347 (list start pos css-property-ids))))))
349 (defun css--complete-pseudo-element-or-class ()
350 "Complete pseudo-element or pseudo-class at point."
351 (save-excursion
352 (let ((pos (point)))
353 (skip-chars-backward "-[:alnum:]")
354 (when (eq (char-before) ?\:)
355 (list (point) pos
356 (if (eq (char-before (- (point) 1)) ?\:)
357 css-pseudo-element-ids
358 css-pseudo-class-ids))))))
360 (defun css--complete-at-rule ()
361 "Complete at-rule (statement beginning with `@') at point."
362 (save-excursion
363 (let ((pos (point)))
364 (skip-chars-backward "-[:alnum:]")
365 (when (eq (char-before) ?\@)
366 (list (point) pos css-at-ids)))))
368 (defun css-completion-at-point ()
369 "Complete current symbol at point.
370 Currently supports completion of CSS properties, pseudo-elements,
371 pseudo-classes, and at-rules."
372 (or (css--complete-property)
373 (css--complete-pseudo-element-or-class)
374 (css--complete-at-rule)))
376 ;;;###autoload
377 (define-derived-mode css-mode prog-mode "CSS"
378 "Major mode to edit Cascading Style Sheets."
379 (setq-local font-lock-defaults css-font-lock-defaults)
380 (setq-local comment-start "/*")
381 (setq-local comment-start-skip "/\\*+[ \t]*")
382 (setq-local comment-end "*/")
383 (setq-local comment-end-skip "[ \t]*\\*+/")
384 (setq-local fill-paragraph-function #'css-fill-paragraph)
385 (setq-local adaptive-fill-function #'css-adaptive-fill)
386 (setq-local add-log-current-defun-function #'css-current-defun-name)
387 (smie-setup css-smie-grammar #'css-smie-rules
388 :forward-token #'css-smie--forward-token
389 :backward-token #'css-smie--backward-token)
390 (setq-local electric-indent-chars
391 (append css-electric-keys electric-indent-chars))
392 (add-hook 'completion-at-point-functions
393 #'css-completion-at-point nil 'local))
395 (defvar comment-continue)
397 (defun css-fill-paragraph (&optional justify)
398 (save-excursion
399 ;; Fill succeeding comment when invoked right before a multi-line
400 ;; comment.
401 (when (save-excursion
402 (beginning-of-line)
403 (comment-search-forward (point-at-eol) t))
404 (goto-char (match-end 0)))
405 (let ((ppss (syntax-ppss))
406 (eol (line-end-position)))
407 (cond
408 ((and (nth 4 ppss)
409 (save-excursion
410 (goto-char (nth 8 ppss))
411 (forward-comment 1)
412 (prog1 (not (bolp))
413 (setq eol (point)))))
414 ;; Filling inside a comment whose comment-end marker is not \n.
415 ;; This code is meant to be generic, so that it works not only for
416 ;; css-mode but for all modes.
417 (save-restriction
418 (narrow-to-region (nth 8 ppss) eol)
419 (comment-normalize-vars) ;Will define comment-continue.
420 (let ((fill-paragraph-function nil)
421 (paragraph-separate
422 (if (and comment-continue
423 (string-match "[^ \t]" comment-continue))
424 (concat "\\(?:[ \t]*\\(?:"
425 (regexp-quote comment-continue) "\\|"
426 comment-start-skip "\\|"
427 comment-end-skip "\\)\\)?"
428 "\\(?:" paragraph-separate "\\)")
429 paragraph-separate))
430 (paragraph-start
431 (if (and comment-continue
432 (string-match "[^ \t]" comment-continue))
433 (concat "\\(?:[ \t]*" (regexp-quote comment-continue)
434 "\\)?\\(?:" paragraph-start "\\)")
435 paragraph-start)))
436 (fill-paragraph justify)
437 ;; Don't try filling again.
438 t)))
440 ((and (null (nth 8 ppss))
441 (or (nth 1 ppss)
442 (and (ignore-errors
443 (down-list 1)
444 (when (<= (point) eol)
445 (setq ppss (syntax-ppss)))))))
446 (goto-char (nth 1 ppss))
447 (let ((end (save-excursion
448 (ignore-errors (forward-sexp 1) (copy-marker (point) t)))))
449 (when end
450 (while (re-search-forward "[{;}]" end t)
451 (cond
452 ;; This is a false positive inside a string or comment.
453 ((nth 8 (syntax-ppss)) nil)
454 ;; This is a false positive when encountering an
455 ;; interpolated variable (bug#19751).
456 ((eq (char-before (- (point) 1)) ?#) nil)
457 ((eq (char-before) ?\})
458 (save-excursion
459 (forward-char -1)
460 (skip-chars-backward " \t")
461 (when (and (not (bolp))
462 (scss-smie--not-interpolation-p))
463 (newline))))
465 (while
466 (progn
467 (setq eol (line-end-position))
468 (and (forward-comment 1)
469 (> (point) eol)
470 ;; A multi-line comment should be on its own line.
471 (save-excursion (forward-comment -1)
472 (when (< (point) eol)
473 (newline)
474 t)))))
475 (if (< (point) eol) (newline)))))
476 (goto-char (nth 1 ppss))
477 (indent-region (line-beginning-position 2) end)
478 ;; Don't use the default filling code.
479 t)))))))
481 (defun css-adaptive-fill ()
482 (when (looking-at "[ \t]*/\\*[ \t]*")
483 (let ((str (match-string 0)))
484 (and (string-match "/\\*" str)
485 (replace-match " *" t t str)))))
487 (defun css-current-defun-name ()
488 "Return the name of the CSS section at point, or nil."
489 (save-excursion
490 (let ((max (max (point-min) (- (point) 1600)))) ; approx 20 lines back
491 (when (search-backward "{" max t)
492 (skip-chars-backward " \t\r\n")
493 (beginning-of-line)
494 (if (looking-at "^[ \t]*\\([^{\r\n]*[^ {\t\r\n]\\)")
495 (match-string-no-properties 1))))))
497 ;;; SCSS mode
499 (defvar scss-mode-syntax-table
500 (let ((st (make-syntax-table css-mode-syntax-table)))
501 (modify-syntax-entry ?/ ". 124" st)
502 (modify-syntax-entry ?\n ">" st)
503 st))
505 (defvar scss-font-lock-keywords
506 (append `((,(concat "$" css-ident-re) (0 font-lock-variable-name-face)))
507 (css--font-lock-keywords 'sassy)
508 `((,(concat "@mixin[ \t]+\\(" css-ident-re "\\)[ \t]*(")
509 (1 font-lock-function-name-face)))))
511 (defun scss-smie--not-interpolation-p ()
512 (save-excursion
513 (forward-char -1)
514 (or (zerop (skip-chars-backward "-[:alnum:]"))
515 (not (looking-back "#{\\$" (- (point) 3))))))
517 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.scss\\'" . scss-mode))
518 ;;;###autoload
519 (define-derived-mode scss-mode css-mode "SCSS"
520 "Major mode to edit \"Sassy CSS\" files."
521 (setq-local comment-start "// ")
522 (setq-local comment-end "")
523 (setq-local comment-continue " *")
524 (setq-local comment-start-skip "/[*/]+[ \t]*")
525 (setq-local comment-end-skip "[ \t]*\\(?:\n\\|\\*+/\\)")
526 (setq-local font-lock-defaults '(scss-font-lock-keywords nil t)))
528 (provide 'css-mode)
529 ;;; css-mode.el ends here