editor/format: preserve indentation for regions

This commit is contained in:
Henrik Lissner 2018-09-02 20:46:13 +02:00
parent c885cd2b9d
commit 75b39a9396
No known key found for this signature in database
GPG key ID: 5F6C0EA160557395

View file

@ -155,7 +155,23 @@ snippets or single lines."
(interactive "r") (interactive "r")
(save-restriction (save-restriction
(narrow-to-region beg end) (narrow-to-region beg end)
(+format/buffer))) ;; Since we're piping a region of text to the formatter, remove any leading
;; indentation to make it look like a file.
(let ((indent (save-excursion
(goto-char beg)
(skip-chars-forward " \t\n")
(current-indentation))))
(with-silent-modifications
(indent-rigidly (point-min) (point-max) (- indent)))
(+format/buffer)
(with-silent-modifications
;; Then restore it afterwards, without affecting new indentation
(indent-rigidly (point-min) (point-max)
(max 0 (- indent
(save-excursion
(goto-char beg)
(skip-chars-forward " \t\n")
(current-column)))))))))
;;;###autoload ;;;###autoload
(defun +format/region-or-buffer (beg end) (defun +format/region-or-buffer (beg end)