When a line in my CSS file appears to be too long (typically a property followed by a bunch of values), I want to split them in to several new lines like this:

What I dream of

But I have to manually enter spaces before the lines to achieve that. In reality, when I hit TAB with my cursor on the url line, what I get is this:

What I actually get

The worst thing is that, after manually inserting the spaces, when I hit TAB again on the same line, it goes back to the ugly format.

This is not a significant issue but it really pains me and I really hope we can have a decent solution here. Thanks in advance!

M-x version:

GNU Emacs 25.1.1 (x86_64-apple-darwin16.1.0, NS appkit-1504.60 Version 10.12.1 (Build 16B2555)) of 2016-11-27

Insert below code into your emacs setup:

(defadvice smie-indent-line (after smie-indent-line-after-hack activate)
  "Customize your own css coding style."
  (if (eq major-mode 'css-mode)
      (let* ((cur-line (buffer-substring-no-properties
        (if (string-match "^\\( +\\)url" cur-line)
            (let* ((empty-spaces (match-string 1 cur-line)))
              (replace-regexp empty-spaces
                              (make-string (+ (length empty-spaces) css-indent-offset) 32)
                              (line-beginning-position) (line-end-position)))))))

My code is copied from http://blog.binchen.org/posts/indent-jsx-in-emacs.html with a little modification.

I will show you how to solve similar problems for other languages:

  • Learn Emacs lisp
  • Press C-h k ENTER and read documentation. In my case, it's documentation of newline-and-indent. It says "Indentation is done using the value of `indent-line-function'."
  • Press C-h v indent-line-function. Now you know you need hack smie-indent-line
  • Done

I just committed a fix to CSS mode, so it should hopefully work as you describe out of the box in the next Emacs release. (Or you could always fetch the latest version from the master branch if you don't want to wait for a release.)

  • I've tested the new version and it works perfectly. Thanks! (Though I'm experiencing issues with displaying RGB colours inside css-mode...) – nerrons Jun 8 '17 at 9:17
  • Yeah, the new indent part is awesome, but the just-added colour displaying thing doesn't work right, so I guess I will simply add your commit to the original css-mode.el. – nerrons Jun 8 '17 at 10:03
  • Thanks for testing it out. Could you submit a bug report with M-x report-emacs-bug and describe there the problems you're experiencing with the new colorization feature? (You should be able to turn it off by setting css-fontify-colors to nil, by the way.) – simenheg Jun 8 '17 at 15:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.