What I did eventually was write a python script:
#!/usr/bin/env python3
"""
script for autoindenting single quoted strings.
usuage: provide as stdin e.g.:
" this is ' a very long line that is too long for the pep8 rules and it also contains a single quote, and the initial indent is included in stdin"
this will output:
" this is ' a very long line that is too long for the pep8 rules and "
'it also contains a single quote, and the initial indent is included '
'in stdin'
with the correct linelength and indentation.
"""
import sys
import re
import pprint
def main():
""" get input from stdin and print the reformatted string """
original = sys.stdin.read()
# parse stdin as code so you get a string that python can format
exec('global executed_string; executed_string = ({})'.format(original))
# determine initial indent
indent = re.match('^ +', original)
if indent:
indent = indent.group(0)
else:
indent = ''
pp = pprint.PrettyPrinter(width=79-len(indent))
text = pp.pformat(executed_string)
# remove () that is used to paste the single quoted strings together
text = re.sub(r'(^\()|(\)$)', '', text)
# add the proper indentation for the first line
text = re.sub(r'^', indent), text)
# add the proper indentation for the subsequent lines (pformat add a space
# at the beginning of each line)
text = re.sub(r'\n ', '\n{}'.format(indent), text)
# remove trailing \n
text = re.sub(r'\n$', '', text)
print(text)
if __name__ == '__main__':
main()
And assigned this to an emacs function (http://ergoemacs.org/emacs/elisp_perl_wrapper.html). It may look a bit hacky, but it does what I want it to do. You need to be careful to also select your initial indent in emacs, before you run the script, so it can determine the initial indent. Maybe there's a better way to do that, but for now, this works for me.
Note: because I'm using exec, this might actually give a uge mess if you provide anything other than a string. I might look into doing something about that, but for now, use with care.
M-q
inside long strings does it wrong (it inserts linebreak and doesn't even indent the string on the next line). – wvxvw Nov 28 '17 at 8:39python-fill-string
automatically assumes that it is dealing with docstrings, and it isn't the right tool to accomplish this. – wvxvw Nov 28 '17 at 9:02