Can emacs re-indent a big blob of HTML for me?

后端 未结 10 1965
生来不讨喜
生来不讨喜 2021-01-29 20:09

When editing HTML in emacs, is there a way to automatically pretty-format a blob of markup, changing something like this:

  
相关标签:
10条回答
  • 2021-01-29 20:40

    Tidy can do what you want, but only for whole buffer it seems (and the result is XHTML)

    M-x tidy-buffer
    
    0 讨论(0)
  • 2021-01-29 20:46

    http://www.delorie.com/gnu/docs/emacs/emacs_277.html

    After selecting the region you want to fix. (To select the whole buffer use C-x h)

    C-M-q

    Reindent all the lines within one parenthetical grouping(indent-sexp).

    C-M-\

    Reindent all lines in the region (indent-region).

    0 讨论(0)
  • 2021-01-29 20:51

    i wrote a function myself to do this for xml, which works well in nxml-mode. should work pretty well for html as well:

    (defun jta-reformat-xml ()
      "Reformats xml to make it readable (respects current selection)."
      (interactive)
      (save-excursion
        (let ((beg (point-min))
              (end (point-max)))
          (if (and mark-active transient-mark-mode)
              (progn
                (setq beg (min (point) (mark)))
                (setq end (max (point) (mark))))
            (widen))
          (setq end (copy-marker end t))
          (goto-char beg)
          (while (re-search-forward ">\\s-*<" end t)
            (replace-match ">\n<" t t))
          (goto-char beg)
          (indent-region beg end nil))))
    
    0 讨论(0)
  • 2021-01-29 20:53

    You can do sgml-pretty-print and then indent-for-tab on the same region/buffer, provided you are in html-mode or nxml-mode.

    sgml-pretty-print adds new lines to proper places and indent-for-tab adds nice indentation. Together they lead to properly formatted html/xml.

    0 讨论(0)
  • 2021-01-29 20:53

    You can do a replace regexp

     M-x replace-regexp
    
     \(</[^>]+>\)
    
     \1C-q-j
    

    Indent the whole buffer

     C-x h
     M-x indent-region
    
    0 讨论(0)
  • 2021-01-29 20:53

    In emacs 25, which I'm currently building from source, assuming you are in HTML mode, use
    Ctrl-x
    h

    to select all, and then press Tab.

    0 讨论(0)
提交回复
热议问题