[Tex/LaTex] Editing LuaLaTeX files in emacs

editorsemacsluatex

(A follow-up question to Which is the best editor for LuaTeX?)

Emacs offers the LaTeX-mode in AUCTeX for editing LaTeX files, while it has the Lua-mode for editing Lua-files.

Consider the following code:

\documentclass{article}
\usepackage{luacode}
\begin{document}
\begin{luacode*}
for i=1,2,3 do
for j=1,2,3 do
tex.sprint("Test");
end
end
\end{luacode*}
\end{document}

In Emacs latex-mode I get the following screenshot:

But it is not possible to indent the lua-code with the tab-key or highlight Lua-code key words. If I turn on lua-mode in emacs, I get editing features for the Lua-code, but not for the latex-code, e.g.:

Is it possible to have both modes work together? (I have looked at this page: http://emacswiki.org/emacs/MultipleModes but I am not sure which mode to use and how to set it up)

Best Answer

It may be possible to have Emacs switch major modes depending on the position of point, but this can quickly become computationally-intensive and can break workflows (especially those that make heavy use of temporary variables). It would be better to adopt the Org model of source code editing: send the interesting bits to a separate buffer and change the mode on that buffer. (For the record, I tried using indirect buffers, but having different font-locks on two views of the same buffer seems to trip up Emacs a bit.)

Bind LaTeX-edit-Lua-code-start to your favorite key. Beware though; editing is asynchronous. You must save for it to reinsert itself into the parent. Kill the buffer, lose your changes.

Update:

I've uploaded the code to GitHub and submitted a pull request to MELPA under the name auctex-lua, and it is available to download through that package repository. If you have not done so already, you will have to 'install' MELPA by adding it to your .emacs anywhere before a call to package-initialize:

(add-to-list 'package-archives
  '("melpa" . "http://melpa.milkbox.net/packages/") t)

I can confirm that the install works swimmingly! For the code, please refer to GitHub. It would be impossible to maintain on here. :-)

screenshot