Skip to content

Instantly share code, notes, and snippets.

@chunned
Created March 24, 2022 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chunned/16208212c2cea3d0e6291868b39a7bd6 to your computer and use it in GitHub Desktop.
Save chunned/16208212c2cea3d0e6291868b39a7bd6 to your computer and use it in GitHub Desktop.
Turns a normal LaTeX environment into an align environment.

Description

This script looks for Markdown files in a specified directory, and converts a normal LaTeX environment:

$$
...
$$

to an align environment:

$$\begin{align}
...
\end{align}$$

Note that you can change 'align' on lines 25 and 28 to another type of environment.

Note

  • This will overwrite the file contents, so make a backup copy of your files before you run it
  • Before you run the script, open it in a text editor (i.e. Notepad) and change line 3 to your target folder
  • This won't touch files in subdirectories. You will have to change line 3 again and re-run the program for any notes in other directories or subdirectories
import os
# MUST SET YOUR DIRECTORY ON THE FOLLOWING LINE - i.e. "C:\\Users\\User1\\Documents"
DIRECTORY = ""
def getFileNames():
filelist = [] # List of files that we will work on is stored here
files = os.listdir(DIRECTORY) # Contains a list of all files in the directory
for i in files:
# Find all .md files, store names in filelist:
if i.endswith(".md"):
filelist.append(i)
return filelist
def insert(textfiles):
for i in textfiles:
print(f'Opening {i}')
with open(i, "r") as file:
content = file.readlines()
# Read file contents as a list, each line is a new element
print(f'Original content: {content}')
for x in range(0, len(content)):
if content[x] == '$$\n':
content[x] = "$$\\begin{align}\n"
for y in range(x+1, len(content)):
if content[y] == '$$' or content[y] == '$$\n':
content[y] = "\\end{align}$$\n"
x = y
break
print(f'Updated content: {content}')
print(f'Writing to {i}')
with open(i, "w") as file:
for x in content:
file.write(x)
print('-'*50)
textfiles = getFileNames()
insert(textfiles)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment