Skip to content

Instantly share code, notes, and snippets.

@mvernacc
Last active June 2, 2024 20:18
Show Gist options
  • Save mvernacc/86188a331fed126c0cb8e1c8727ffdcd to your computer and use it in GitHub Desktop.
Save mvernacc/86188a331fed126c0cb8e1c8727ffdcd to your computer and use it in GitHub Desktop.
This script process a latex document to remove certain blocks, but keep the text within them.
r"""This script process a latex document to remove certain blocks,
but keep the text within them.
This is useful for preparing paper revisions for the AIAA journals,
which ask for both:
- a pdf of the revised paper with the revisions colored, and
- a "clean" latex file of the revised paper, without the coloring blocks.
Thus, the author can create a latex file with the revised passages wrapped in
`\textcolor{blue}{...}` blocks, and then run
```
python latex_remove_blocks.py in.tex "\textcolor{blue}" out.tex
```
to create a copy of the file with the blue coloring removed.
Copyright 2024 Matthew Vernacchia
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the “Software”), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
import sys
def strip_blocks(text: str, block_prefix: str) -> str:
r"""Strip blocks from a string of text, but retain the contents of the blocks.
Blocks are made of a prefix, an open bracket "{", contents, and a close bracket "}".
For example, with block_prefix "\textcolor{blue}", the text
"
This is an example of \textcolor{blue}{some blue text} in a document.
Here is another \textcolor{blue}{\emph{example} with nested braces} of blue text.
"
becomes
"
This is an example of some blue text in a document.
Here is another \emph{example} with nested braces of blue text.
"
"""
new = ""
selection_start = 0
bracket_depth = 0
# In the loop below, `block_start_depth` will be:
# If the current index *is not* inside a block that starts with the prefix: None.
# If the current index *is* inside a block that starts with the prefix: an integer,
# the bracket depth at which the block started.
block_start_depth: int | None = None
i = 0
while i < len(text):
if block_start_depth is None and text[i:i + len(block_prefix)] == block_prefix:
# Found the start of a block.
new += text[selection_start : i]
selection_start = i + len(block_prefix) + 1
i += len(block_prefix) - 1
block_start_depth = bracket_depth
elif text[i] == "{":
bracket_depth += 1
elif text[i] == "}":
bracket_depth -= 1
if block_start_depth is not None and bracket_depth == block_start_depth:
# Found the end of a block.
new += text[selection_start : i]
selection_start = i + 1
block_start_depth = None
i += 1
new += text[selection_start : i]
return new
def test():
before = r"""
This is an example of \textcolor{blue}{some blue text} in a document.
Here is another \textcolor{blue}{\emph{example} with nested braces} of blue text.
"""
print("Before:\n" + before)
after = strip_blocks(before, r"\textcolor{blue}")
print("After:\n" + after)
assert after == r"""
This is an example of some blue text in a document.
Here is another \emph{example} with nested braces of blue text.
"""
print("----\n")
before = r"""
\usepackage[utf8]{inputenc}
\usepackage{textcomp}
\usepackage{dirtytalk}
\usepackage{graphicx}
"""
print("Before:\n" + before)
after = strip_blocks(before, r"\textcolor{blue}")
print("After:\n" + after)
assert after == before
print("----\n")
if "--test" in sys.argv:
test()
print("Tests passed")
sys.exit(0)
if len(sys.argv) != 4 or "-h" in sys.argv or "--help" in sys.argv:
print("Remove blocks from a latex document, but keep their contents.\nUsage:")
print(f"python {sys.argv[0]} IN_FILE BLOCK_PREFIX OUT_FILE")
sys.exit(1)
_, in_file, block_prefix, out_file = sys.argv
with open(in_file) as f:
text = f.read()
new_text = strip_blocks(text, block_prefix)
with open(out_file, "w") as f:
f.write(new_text)
print(f"Wrote results to {out_file}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment