Skip to content

Commit

Permalink
Add cell auto formatter
Browse files Browse the repository at this point in the history
  • Loading branch information
ElleNajt committed Feb 5, 2025
1 parent 452de87 commit 337d3ac
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Readme.org
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,13 @@ default. The default can be changed with ~(setq
ob-python-extras/transparent-images t)~. This default, in turn, can be
overridden at the org-src-block level with =:transparent nil= or =:transparent
t=.
** Autoformatter

Auto formats source blocks using black. Configurable with

#+begin_src elisp
(setq ob-python-extras/auto-format t)
#+end_src

* Examples:
[[file:tests/babel-formatting.org][See this org file for examples of the different functionality and configurations.]]
Expand Down
38 changes: 38 additions & 0 deletions ob-python-extras.el
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,44 @@ In regular org-mode, tries to view image or executes normal C-c C-c."
(let* ((this-file (locate-library "ob-python-extras"))
(this-dir (file-name-directory this-file)))
(load (expand-file-name "ob-python-extras-alerts" this-dir))))
;;; Auto formatting

;; TODO Get this to work in emacs batch
;; TODO Add ruff

(when (condition-case nil
(require 'python-black nil t)
(error nil))

(defvar ob-python-extras/auto-format t
"When non-nil, automatically format Python source blocks after execution.")

(defun ob-python-extras--format-src-block ()
"Format the current org babel Python source block using python-black.
Creates a temporary buffer, sets python-mode, applies formatting, and copies back."
(interactive)

(when ob-python-extras/auto-format
(let* ((element (org-element-at-point))
(language (org-element-property :language element))
(orig-code (org-element-property :value element))
(point-pos (point)))
;; save excursion isn't sufficient to save the position
(when (string= language "python")
(let ((formatted-code
(with-temp-buffer
(insert orig-code)
(python-mode)
(python-black-buffer)
(buffer-string))))
(save-excursion
(goto-char (org-element-property :begin element))
(org-babel-update-block-body formatted-code))
(goto-char point-pos)
)))))

(add-hook 'org-babel-after-execute-hook 'ob-python-extras--format-src-block))

(provide 'ob-python-extras)
;;; ob-python-extras.el ends here

0 comments on commit 337d3ac

Please sign in to comment.