0

How do you clean up an html file?

For example, this file has one too many empty line between the div tags. I would like cleanup to leave only one blank line there.

<html>
  <body>
    <div>
      foo
    </div>


    <div>
      abc
    </div>
  </body>
</html>

What I tried in my emacs prelude

M-x help
d PATTERN   Show a list of functions, variables, and other items whose
              documentation matches the PATTERN (a list of words or a regexp).
entered 'clean html'

Nothing found

1
  • You may want to read (emacs) Blank Lines, particularly about the command delete-blank-lines, which is globally bound to C-x C-o by default.
    – Basil
    Commented Dec 29, 2017 at 8:53

2 Answers 2

1

You can just use query-regexp-replace (bound by default to C-M-%) to substitute three or more consecutive newlines with two newlines. You need to know how to add a newline to your query and replacement strings: C-q C-j. Altogether you'd type:

C-M-% C-q C-j \{3,\} RET C-q C-j C-q C-j RET !

0
(defun just-one-empty-line (&optional beg end)
  "Delete consecutive empty lines, retain just one.

Works on region if active.
Accepts optional arguments BEG END to specify a region"
  (interactive "*")
  (let ((beg (cond (beg)
           ((region-active-p)
            (region-beginning))
           (t (point-min))))
    (end (cond (end (copy-marker end))
           ((region-active-p)
            (copy-marker (region-end)))
           (t (copy-marker (point-max))))))
    (save-excursion
      (save-restriction
        (narrow-to-region beg end)
        (goto-char beg)
        (while (not (eobp))
          (while (looking-at "^\\([ \t]*\n\\)[ \t]*$")
            (delete-region (match-beginning 1) (match-end 1)))
          (forward-line 1))
    (widen)))))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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