wbolster / emacs-python-black

Emacs package to reformat Python using black-macchiato
BSD 3-Clause "New" or "Revised" License
95 stars 11 forks source link

python-black-org-mode-block: Lines starting with `,*` and `,#+` are not unescaped #17

Closed nick4f42 closed 3 months ago

nick4f42 commented 3 months ago

Formatting the following code block with python-black-org-mode-block fails:

#+begin_src python
x = (
    1,
    ,*(2, 3, 4),
)
#+end_src
wbolster commented 3 months ago

the double comma seems a syntax error, no?

nick4f42 commented 3 months ago

Technically not including that comma would be invalid Org markup, see the second paragraph in (org) Literal Examples. It says "starting with", but it actually allows preceding whitespace if you check the implementation of org-escape-code-in-region. Org inserts the commas when you edit the code block with org-edit-special, and removes them when you execute the code.

Here's a possible fix for this line that also preserves the buffer modification flag if nothing changes.

(let* ((contents (buffer-substring-no-properties beg end))
       (modified (buffer-modified-p))
       (end (copy-marker end)))
  (unwind-protect
      (progn
    (atomic-change-group
      (org-unescape-code-in-region beg end)
      (python-black-region beg (- end 1) display-errors)
      (org-escape-code-in-region beg end))
    (when (equal contents (buffer-substring-no-properties beg end))
      (restore-buffer-modified-p modified)))
    (set-marker end nil)))

Although maybe at that point it's best to just use a temporary buffer?

wbolster commented 3 months ago

thanks for the explanation – i do not use org-mode myself so wasn't sure about its intricacies.

your last suggestion seems a reasonable improvement. i'll happily merge a pull request with that change (hint hint 🙃).