Emacs -- correctly indenting css code embedded within an html file
When I indent the following html file in emacs, the line 'background-color' is not indented correctly. Can emacs be made to use css-mode for the css part?
<!doctype html>
<html lang=en>
<head>
<meta charset=utf-8>
<title>Page</title>
<style type = "text/css">
h2 {
background-color: #BBB;
}
</style>
</head>
<body>
<p>
<h2>Title</h2>
</p>
</body>
</html>
Question asked: May 2011
Question edited: Dec 2013
Edit:
I have the impression that it is myopic to look for, or to develop,开发者_StackOverflow社区 a method for handling css and html in particular. The right solution is a broader one that handles a file consisting of any two subsets. Perhaps the question does not warrant serious attention because the two subsets should be isolated in their own files, but for quick tests and smaller examples the question stands. Suggestions of working solutions are welcome.
As you know, you're better off distributing HTML, Javascript, CSS, &c., among their own files, but often that's not possible, especially when working with legacy code. In such cases, I've found web-mode extremely valuable.
Unlike nXhtml and other such solutions, web-mode directly handles font-locking and indentation for each type of code, rather than attempting to invoke the proper major mode for wherever point happens to be, or trying to layer major modes atop one another in a way that's all but guaranteed not to work reliably. While this approach admittedly represents a substantial duplication of effort, and means you don't, for example, get the benefit of Steve Yegge's excellent js2-mode when editing inline Javascript, it does mean you get reliable font-locking and indentation, without having to spend a lot of time dealing with fragile chicanery; having installed and customized web-mode, you can more or less jump right in and start hacking away:
I spent more time than I'd care to remember dealing with MuMaMo and its ilk, and all I got out of it was headaches. (And improved discipline regarding the avoidance of inline CSS and Javascript, but that was purely out of self-defense.) Web-mode is a fantastic solution to that problem, and I recommend it without reservation.
Check out nXhtml mode: http://ourcomments.org/Emacs/nXhtml/doc/nxhtml.html
From its page:
Another important feature is the ability to mix several languages in one buffer and get the correct syntax highlighting and indentation for each of them.
Edit: the EmacsWiki article on multiple modes has some other options (on top of Mumamo, which is what nXhtml uses). One that you may find particularly interesting is multi-web-mode, which changes the mode based on where the point is.
I have only used nXhtml mode myself, but multi-web-mode may be simpler to set up and easier to use—while I did like nXhtml, I distinctly remember its being a hassle to set up.
精彩评论