indent-region-as

Posted by David N. Welton Fri, 06 Jun 2008 20:35:00 GMT

At times, when I'm working with an HTML file - an article about programming, for instance - I need to include a snippet of code inside a <pre> tag or a <code> tag. It's very annoying to have to indent that code by hand, and since the language may be anything from Hecl, to Erlang, to Java to C, I don't want to use something like two-mode-mode for Emacs, so I threw the following elisp together:

(defun indent-region-as (other-mode)
  "Indent selected region as some other mode.  Used in order to indent source code contained within HTML."
  (interactive "aMode to use: ")

  (save-excursion
(let ((old-mode major-mode))
  (narrow-to-region (region-beginning) (region-end))
  (funcall other-mode)
  (indent-region (region-beginning) (region-end) nil)
  (funcall old-mode)))
  (widen))

To use it:

  1. Put it in your .emacs file.
  2. Select the region to indent according to the other mode.
  3. M-x indent-region-as - which will prompt you for the other mode to use. You need to give the function for that mode, such as tcl-mode, java-mode, ruby-mode or whatever.

My elisp is a bit rusty, so I'm sure it's possible to improve the code above, but it does the job for me.

Tags  | 2 comments | no trackbacks

Comments

  1. Diego "Flameeyes" Pettenò said about 18 hours later:

    Hey thanks a lot for this! :)

    I happened to do something like that (well, the article was in docbook, but it's the same problem) and wondered why there wasn't an easy way... well now there is, thanks :)

  2. Harald Meland said 2 days later:
    I'd use ``make-indirect-buffer'' for this; that way, you can have all the bells and whistles of the programming language in question (syntax highlighting, etc) while the text ends up in the HTML buffer.

Trackbacks

Use the following link to trackback from your own site:
http://journal.dedasys.com/articles/trackback/1875

Comments are disabled