tags:

views:

162

answers:

2

I can currently use sgml-pretty-print to pretty print an xml file in emacs, but it's a manual process:

  1. M-<
  2. C-space
  3. M->
  4. M-x sgml-pretty-print

I'd like this to happen automatically (or at least have some option to do so). I'm new to emacs/elisp, and do not understand how:

  1. emacs knows what code to run when you open a file (does this start in files.el?)
  2. If you wanted to override that code with your own, how to do that
+5  A: 

This should do the trick for you:

(add-hook 'find-file-hook 'my-sgml-find-file-hook)
(defun my-sgml-find-file-hook ()
  "run sgml pretty-print on the file when it's opened (if it's sgml)"
  (when (eq major-mode 'sgml-mode)
    (sgml-pretty-print (point-min) (point-max))))

The key pieces of information are the find-file-hook, point-min (-max), and major-mode.

If you want to learn more about elisp, you can take a look at this question, which gives some pointers on how to figure things out.

Trey Jackson
Furthermore, you can wrap the `sgml-pretty-print` function call in a `y-or-n-p` conditional statement to ask whether one wants the content to be pretty printed or not.
Török Gábor
Thanks, both of you. This works great.
Jonathan Yee
+3  A: 

A slightly simpler alternative to Trey Jackson's answer. Just add this to your ~/.emacs file:

(add-hook 'sgml-mode-hook #'(lambda ()
  (sgml-pretty-print (point-min) (point-max))))
Adam Rosenfield
Yes, it's a bit simpler, but TJ's solution allows you to run the function manually, too.
Török Gábor