Indenting even more nicely

I’ve been using this for some time, as I mentioned a few days ago:

(defun indent-buffer ()
  "Indent an entire buffer using the current syntax settings."
  (interactive)
  (save-excursion
   (global-trim)
   (goto-char (point-min))
   (while (re-search-forward "\t" nil t)
     (replace-match " " t t)))
  (indent-region (point-min) (point-max)))

With the massive re-indenting process that inspired that post, I came across the “need” to also re-fill comments (ie, reformat comments to fit within our in-house 120-character right margins) at the same time.

The resulting functions look like this:

(defun comment-forward ()
 "Advance the point to the next comment."
 (interactive)
 (skip-syntax-forward "^<!")         ; next comment-like char
 (cond
   ;; actually starts a comment; skip delimiter
   ((eql (face-at-point) 'font-lock-comment-delimiter-face)
    (skip-syntax-forward "<!"))
   ;; end of file
   ((>= (point) (1- (point-max)))
    nil)
   ;; not a comment here (maybe in a string or something)
   (t
     (forward-char)
     (comment-forward))))
(defun fill-all-comments ()
 "Re-fill all comments in the buffer"
 (interactive)
 (save-excursion
   (goto-char (point-min))
   (while (comment-forward)
     (fill-paragraph))))
(defun replace-all-tabs-with-spaces ()
 "Replace every TAB byte with a space."
 (save-excursion
   (goto-char (point-min))
   (while (re-search-forward "\t" nil t)
     (replace-match " " t t))))
(defun indent-buffer ()
 "Indent an entire buffer using the current syntax settings."
 (interactive)
 (global-trim)
 (replace-all-tabs-with-spaces)
 (indent-region (point-min) (point-max))
 (fill-all-comments))

The next step, of course, is to figure out how to nicely break up over-long code lines …

 

 

PS. That didn’t last long.

I replaced the use of replace-all-tabs-with-spaces with the nicer:

(defun strip-indentation ()
  "Replace   leading   whitespace   (tab/spaces)   in   preparation   of
re-indenting. Skips whitespace within comments or strings."
  (save-excursion
   (goto-char (point-min))
   (while (re-search-forward "^[ \t]+" nil t)
          (unless (member (face-at-point) '(font-lock-string-face
                                            font-lock-comment-face))
            (replace-match " " t t)))))

What do you think? Add your comments →