I'm writing a Python script in Emacs and have activated Auto-Fill minor mode with M-x auto-fill-mode
. An issue I always seem to come across is that this fill mode tends to break quoted strings across multiple lines without making any compensating adjustments, resulting in an error when the script is run.
For example:
print 'the quick brown fox jumped over the lazy dog and
then did something else'
which results in SyntaxError: EOL while scanning string literal
when run.
Is there a fill mode in Emacs that is Python "string literal aware" and automatically makes for example one of the line continuation/related adjustments discussed in Python style - line continuation with strings?, rather than naively splitting the string inducing an error?
EDIT I've disabled this myself because it was causing Emacs to eat lots of processor time on certain documents. I just live with the bad fill mode -- would love if something would properly do this correctly:
some_list.append("This is a very long string which I would like to "
"break in a sensible way")
/EDIT
I've been beating my head against this same problem for a while now, and finally found this solution.
This seems to work for me. Unfortunately I think this turns off filling for any quoted strings in all modes, not just Python. I'm sure someone with stronger elisp-fu than me can come up with a modification that restricts it to python-mode, but this is a better solution that that proposed above, IMO.
This solution taken from this related answer -- go give this answer some upvote love if you like it.
(defun odd-number-of-single-quotes-this-paragraph-so-far ()
(oddp (how-many "'" (save-excursion (backward-paragraph) (point)) (point))))
(defun odd-number-of-double-quotes-this-paragraph-so-far ()
(oddp (how-many "\"" (save-excursion (backward-paragraph) (point)) (point))))
(add-to-list 'fill-nobreak-predicate
'odd-number-of-single-quotes-this-paragraph-so-far)
(add-to-list 'fill-nobreak-predicate
'odd-number-of-double-quotes-this-paragraph-so-far)
'''
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With