diff --git a/blacken.el b/blacken.el index b5fabfd..83a9092 100644 --- a/blacken.el +++ b/blacken.el @@ -143,6 +143,30 @@ Show black output, if black exit abnormally and DISPLAY is t." (when display (pop-to-buffer errbuf)))))) +;;;###autoload +(defun blacken-region (beg end) + "Try to blacken the current region (between BEG and END)." + (interactive (if (use-region-p) + (list (region-beginning) (region-end)) + (list nil nil))) + (let* ((content (buffer-substring-no-properties beg end)) + (indentation (with-temp-buffer + (insert content) + (goto-char (point-min)) + (back-to-indentation) + (- (point) 1))) + (blackened (with-temp-buffer + (insert content) + (dotimes (i indentation) + (indent-rigidly-left (point-min) (point-max))) + (blacken-buffer) + (dotimes (i indentation) + (indent-rigidly-right (point-min) (point-max))) + (buffer-string)))) + (with-current-buffer (current-buffer) + (delete-region beg end) + (insert blackened)))) + ;;;###autoload (define-minor-mode blacken-mode "Automatically run black before saving."