I'm trying to write a small program to indent lisp files using lisp-mode so I can get Emacs-compatible indentation even when using a different program.

Here's my first attempt to write a program to visit a file, override its mode and, indent it, and then write it back.

I'm wondering if there's a way to non-interactively open a buffer to a file without enabling the modes associated with that file. It seems more elegant than enabling text-mode and then lisp-mode.

:;exec /usr/bin/env emacs -Q --script "$0" "$@"

(mapcar (lambda (filename)
          (find-file filename)
          (indent-region (point-min) (point-max))

I copied the file into indent2.el and ran indent.el a few times with indent2 as an argument.

It seems to be working correctly, but produces the message

> ./indent.el ./indent2.el
Setting up indent for shell type sh
Indentation variables are now local.
Indentation setup for shell type sh
Indenting region...
Indenting region...done

which means that Emacs is processing the shebang even when being used non-interactively. Is there a way to get it to bypass that step?


Use insert-file-contents to read text from file and write-region to write text to file. User commands like find-file / save-buffer / write-file have many interactive features thus usually are supposed used by user directly, i.e., via key binding or M-x, not from Lisp code.

(defun my-indent-lisp-file (filename)
    (insert-file-contents filename)
    (indent-region (point-min) (point-max))
    (write-region nil nil filename)))

By the way, if your code is in Emacs Lisp, you should use emacs-lisp-mode. lisp-mode is for Common Lisp, I think.

  • Thank you. When using the script on a copy of itself though, I still see the Setting up indent for shell type sh message (because of the #! preamble). It seems to be coming from the write-region command and there doesn't seem to be a way to suppress it. I think it's harmless though. – Gregory Nisbet Dec 2 '18 at 9:04
  • 1
    @GregoryNisbet That message doesn't come from the above code, it stills shows if you keeps only the first two lines. – xuchunyang Dec 2 '18 at 9:47
  • @GregoryNisbet For the sake of simplicity, I suggest using #!/usr/bin/env emacs --script, if it doesn't work, use #!/path/to/emacs --script. Don't worry about portability if you are the only one who will use the script. – xuchunyang Dec 2 '18 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.