Search code examples
htmlauto-indent

How to auto indent multiple files?


Currently, I generate static files and those files aren't indented properly. Emacs' auto indent works great with c-x h tab, but that's per file. I want to auto indent multiple files (Like 50 or so, thus it's not feasible to do it manually).

Is there any way to accomplish this? Whether it be using a different text editor or a script or etc. If it helps, most of the files are .html.


Solution

  • I tested the code below with some HTML files, it works well.

    (defun indent-file (file-name)
      (save-window-excursion
        (find-file file-name)
        (indent-region (point-min) (point-max))
        (write-region nil nil file-name)))
    
    ;; argv is a list stores command line option. In this case, it will be ("/your/directory/path").
    ;; directory-files-recursively will find files recursively, and it needs emacs 25.1 or later.
    (let* ((target-dir (car argv))
           (target-file-names  (directory-files-recursively target-dir ".*.html$")))
      (dolist (file-name target-file-names)
        (indent-file file-name)))
    
    1. Save the code above as 'indent-files.el'
    2. Run emacs --script indent-files.el "/your/directory/path" in terminal

    It will be tricky if you want to use emacs lisp as a common script language, although it actually could indeed. Here are some tips: https://swsnr.de/blog/2014/08/12/emacs-script-pitfalls/