How do I configure emacs for editing HTML files that contain Javascript?

MakeDummy picture MakeDummy · Dec 16, 2010 · Viewed 16.7k times · Source

I have started the painful first steps of using emacs to edit an HTML file with both HTML tags and javascript content. I have installed nxhtml and tried using it - i.e set up to use nxhtml-mumamo-mode for .html files. But I am not loving it. When I am editing the Javascript portion of the code the tab indents do not behave as they do when editing C/C++ code. It starts putting tabs within the line and if you try and hit tab in the white space preceding a line it inserts the tab rather than re-tabifying the line.

Another aspect that I don't like is that it doesn't do syntax colouring like the usual C/C++ modes do. I much prefer the behaviour of the default java-mode when editing HTML files but that doesn't play nicely with the HTML code. :-(

1) Is there a better mode for editing HTML files with Javascript portions?

2) Is there a way to get nxhtml to use the default java-mode for the javascript portions?

Regards,

M

Answer

Kai Carver picture Kai Carver · Aug 11, 2012

Another solution is multi-web-mode:

https://github.com/fgallina/multi-web-mode

which may be more easily configurable than the already mentioned multi-mode.

You just configure your preferred modes in your .emacs file like this:

(require 'multi-web-mode)
(setq mweb-default-major-mode 'html-mode)
(setq mweb-tags 
  '((php-mode "<\\?php\\|<\\? \\|<\\?=" "\\?>")
    (js-mode  "<script[^>]*>" "</script>")
    (css-mode "<style[^>]*>" "</style>")))
(setq mweb-filename-extensions '("php" "htm" "html" "ctp" "phtml" "php4" "php5"))
(multi-web-global-mode 1)

More on Emacs's multiple multiple modes (sigh) here:

http://www.emacswiki.org/emacs/MultipleModes

UPDATE: simplified the regexps to detect JavaScript or CSS areas to make them work with HTML5 -- no need for super-precise and fragile regular expressions.