Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Emacs fill mode for Python that doesn't break quoted strings causing errors

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?

like image 561
Bryce Thomas Avatar asked May 20 '14 09:05

Bryce Thomas


1 Answers

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)

'''

like image 136
Michael Bacon Avatar answered Oct 16 '22 14:10

Michael Bacon