Skip to content

Commit

Permalink
Merge pull request #4 from pace-gene/fix/reset-view-after-buffer-format
Browse files Browse the repository at this point in the history
FIX: Preserve point and view when reformatting buffer
  • Loading branch information
christophermadsen authored Sep 11, 2024
2 parents 4739e87 + 467c54f commit 7bf9650
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions lazy-ruff.el
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
;; This package provides Emacs commands to format and lint Python code using
;; the external 'ruff' tool. It offers functions to format the entire buffer,
;; specific regions, or Org mode source blocks.
;;
;;
;; Prerequisites:
;; - The 'ruff' command-line tool must be installed and available in your
;; system's PATH. Please refer to the 'ruff' documentation at:
Expand Down Expand Up @@ -134,14 +134,20 @@ Ensures cursor position is maintained. Requires `ruff` in system's PATH."
(interactive)
(unless (derived-mode-p 'python-mode 'python-base-mode)
(user-error "Only python buffers can be linted with ruff"))
(let ((temp-file (make-temp-file "ruff-tmp" nil ".py")))
(let ((temp-file (make-temp-file "ruff-tmp" nil ".py"))
(old-point (point))
(active-window (frame-selected-window))
(old-window-start (window-start))) ;;; Save point
;; Write buffer to temporary file, format it, and replace buffer contents.
(write-region nil nil temp-file)
(lazy-ruff-run-commands temp-file (eq lazy-ruff-only-format-buffer t) (eq lazy-ruff-only-check-buffer t))
(erase-buffer)
(insert-file-contents temp-file)
;; Clean up temporary file.
(delete-file temp-file)))
(delete-file temp-file)
;; Restore point and window
(goto-char old-point)
(set-window-start active-window old-window-start)))

;;;###autoload
(defun lazy-ruff-lint-format-region ()
Expand All @@ -160,7 +166,7 @@ Ensures cursor position is maintained. Requires `ruff` in system's PATH."
(insert-file-contents temp-file))
(delete-region start end)
(insert-buffer-substring temp-buffer)

;; Cleanup actions.
(delete-file temp-file)
(kill-buffer temp-buffer))
Expand Down

0 comments on commit 7bf9650

Please sign in to comment.