Emacs: Reformat Lines for Source Code 📜

By Xah Lee. Date: . Last updated: .

Toggle Code Block to One Line or Multi Lines

(defun xah-reformat-lines (&optional Width)
  "Reformat current block or selection into short lines or 1 long line.
When called for the first time, change to one line. Second call change it to multi-lines. Repeated call toggles.
If `universal-argument' is called first, ask user to type max length of line. By default, it is 80.

Note: this command is different from emacs `fill-region' or `fill-paragraph'.
This command never adds or delete non-whitespace chars. It only exchange whitespace sequence.

URL `http://xahlee.info/emacs/emacs/emacs_reformat_lines.html'
Created: 2016
Version: 2025-08-29"
  (interactive
   (list
    (if current-prefix-arg
        (cond
         ((not (numberp current-prefix-arg)) 80)
         (t (prefix-numeric-value current-prefix-arg)))
      80)))
  ;; This symbol has a property 'is-long-p, the possible values are t and nil. This property is used to easily determine whether to compact or uncompact, when this command is called again
  (let ((xisLong (if (eq last-command this-command) (get this-command 'is-long-p) nil))
        (xwidth (if Width Width 80))
        xbeg xend)
    (seq-setq (xbeg xend) (if (region-active-p) (list (region-beginning) (region-end)) (list (save-excursion (if (re-search-backward "\n[ \t]*\n" nil 1) (match-end 0) (point))) (save-excursion (if (re-search-forward "\n[ \t]*\n" nil 1) (match-beginning 0) (point))))))
    (if xisLong
        (save-excursion
          (save-restriction
            (narrow-to-region xbeg xend)
            (goto-char (point-min))
            (while (re-search-forward " +" nil 1)
              (when (> (- (point) (line-beginning-position)) xwidth)
                (replace-match "\n")))))
      (save-excursion
        (save-restriction
          (narrow-to-region xbeg xend)
          (goto-char (point-min))
          (while (re-search-forward "[ \n\t]+" xend :move) (replace-match " ")))))
    (put this-command 'is-long-p (not xisLong))))

Issues of Reformating Code

When working on programing language code, we want to reformat lines by a exchange of whitespaces.

Emacs Lines, Column, Cursor Position

Soft-Wrap Lines

Reformat Lines

Show Line Number, Column Number

Highlight Current Line, Screen Line