- documentclass_re = re.compile("(\\\\documentclass\[)(1[012]pt,?)(.+)")
- usepackage_re = re.compile("\\\\usepackage")
- userpreamble_re = re.compile("User specified LaTeX commands")
- enduserpreamble_re = re.compile("\\\\makeatother")
- begindoc_re = re.compile("\\\\begin\{document\}")
-
- tmp = mkstemp()
-
- in_doc_body = 0
- in_user_preamble = 0
- usepkg = 0
- changed = 0
- for line in open(latex_file, 'r').readlines():
- if in_doc_body:
- if changed:
- tmp.write(line)
- continue
- else:
- break
-
- if begindoc_re.match(line) != None:
- in_doc_body = 1
-
- if not pdf_output and not usepkg:
- if userpreamble_re.search(line) != None:
- in_user_preamble = 1
- elif enduserpreamble_re.search(line) != None:
- in_user_preamble = 0
- if usepackage_re.match(line) != None and in_user_preamble:
- usepkg = 1
- changed = 1
- tmp.write("\\def\\t@a{microtype}\n")
- tmp.write("\\let\\oldusepkg\\usepackage\n")
- tmp.write("\\def\\usepackage{\\@ifnextchar[\\@usepkg{\\@usepkg[]}}\n")
- tmp.write("\\def\@usepkg[#1]#2{\\def\\t@b{#2}")
- tmp.write("\\ifx\\t@a\\t@b\\else\\oldusepkg[#1]{#2}\\fi}\n")
- tmp.write(line)
- continue
-
- match = documentclass_re.match(line)
- if match == None:
- tmp.write(line)
- continue
-
- changed = 1
- tmp.write("%s%s\n" % (match.group(1), match.group(3)))
+ # python 2 does not allow to declare a string as raw byte so we double
+ # the backslashes and remove the r preffix
+ def_re = re.compile(b"(\\\\newcommandx|\\\\global\\\\long\\\\def)"
+ b"(\\\\[a-zA-Z]+)")
+
+ tmp = tempfile.TemporaryFile()
+
+ changed = False
+ macros = []
+ for line in open(latex_file, 'rb').readlines():
+ if not pdf_output and line.startswith(b"\\documentclass"):
+ changed = True
+ line += b"\\PassOptionsToPackage{draft}{microtype}\n"
+ else:
+ match = def_re.match(line)
+ if match != None:
+ macroname = match.group(2)
+ if macroname in macros:
+ definecmd = match.group(1)
+ if definecmd == b"\\newcommandx":
+ changed = True
+ line = line.replace(definecmd, b"\\renewcommandx")
+ else:
+ macros.append(macroname)
+ tmp.write(line)