My mother uses LyX (and thus, LaTeX) to layout her books. She doesn’t need much help, but does almost everything herself. Except she was lacking an editor which could replace the quotation marks appropriately, because they are handled somewhat special in LyX (you need an editor which can replace by multiline text, such as VIM).

So every now and then, mostly when she’s started layouting a new book, she’ll ask me to fix the quotation marks in a lyx file for her.

I decided to write a small python script for it, since she has python installed on her box anyway (also on Windows, although she also has Linux on it).

Maybe someone else has the same problems, so here you go:

#!/usr/bin/python
import re, sys
 
# Use full regexp power to detect as many " properly as possible...
# Note that this is a lot more sophisticated than just \b" and "\b
# and will be able to handle all the 'something ...", said foo' cases, too!
# But yeah, you can do even more, and maybe separate it into more regexps...
qrp1 = re.compile(r'(^\s*|\b[:]?\s+[.:,;?!\-\(]*)"(\b)', re.M)
qrp2 = re.compile(r'(\b[.:,;?!\-\)]*|\b \.\.\.)"([.:,;?!\-\)]*(\s+\b|\s*$))', re.M)
 
# These are for >>-style quotes, german bracketing. If you want other
# quotes, adjust to your style yourself (hint: look at your .lyx file)
q1 = r"""
\\begin_inset Quotes ald
\\end_inset
"""
q2 = r"""
\\begin_inset Quotes ard
\\end_inset
"""
 
# Iterate over all input files...
for name in sys.argv[1:]:
        # Load input file
        fi = file(name, "r")
        data = fi.read()
        fi.close()
        # Replace quotes
        data = qrp1.sub("\\1"+q1+"\\2", data)
        data = qrp2.sub("\\1"+q2+"\\2", data)
        # Write output file with new name
        newname = name + ".quotes.lyx"
        fi2 = file(newname, "w")
        fi2.write(data)
        fi2.close()