aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGravatar Shakya Majumdar <[email protected]>2021-04-09 11:56:02 +0530
committerGravatar Shakya Majumdar <[email protected]>2021-04-09 11:56:02 +0530
commit3e09dd8500d91486a2a3c776cb213d61204f3c61 (patch)
tree8bc8e75d30cd629344fbdcbb697cc61a4611eecb
parentAdd latex cog (diff)
add markdown support
-rw-r--r--bot/exts/evergreen/latex.py24
1 files changed, 22 insertions, 2 deletions
diff --git a/bot/exts/evergreen/latex.py b/bot/exts/evergreen/latex.py
index 79b50ccd..1f9de163 100644
--- a/bot/exts/evergreen/latex.py
+++ b/bot/exts/evergreen/latex.py
@@ -1,3 +1,4 @@
+import re
from io import BytesIO
from typing import Union
@@ -16,6 +17,16 @@ plt.rcParams.update(
}
)
+FORMATTED_CODE_REGEX = re.compile(
+ r"(?P<delim>(?P<block>```)|``?)" # code delimiter: 1-3 backticks; (?P=block) only matches if it's a block
+ r"(?(block)(?:(?P<lang>[a-z]+)\n)?)" # if we're in a block, match optional language (only letters plus newline)
+ r"(?:[ \t]*\n)*" # any blank (empty or tabs/spaces only) lines before the code
+ r"(?P<code>.*?)" # extract all code inside the markup
+ r"\s*" # any more whitespace before the end of the code markup
+ r"(?P=delim)", # match the exact same delimiter from the start again
+ re.DOTALL | re.IGNORECASE, # "." also matches newlines, case insensitive
+)
+
class Latex(commands.Cog):
"""Renders latex."""
@@ -26,7 +37,6 @@ class Latex(commands.Cog):
@staticmethod
def _render(text: str) -> Union[BytesIO, str]:
"""Return the rendered image if latex compiles without errors, otherwise return the error message."""
- text = text.replace(r"\\", "$\n$") # matplotlib uses \n for newlines, not \\
fig = plt.figure()
try:
@@ -40,16 +50,26 @@ class Latex(commands.Cog):
except ValueError as e:
return str(e)
+ @staticmethod
+ def _prepare_input(text: str) -> str:
+ text = text.replace(r"\\", "$\n$") # matplotlib uses \n for newlines, not \\
+
+ if match := FORMATTED_CODE_REGEX.match(text):
+ return match.group("code")
+ else:
+ return text
+
@commands.command()
async def latex(self, ctx: commands.Context, *, text: str) -> None:
"""Renders the text in latex and sends the image."""
+ text = self._prepare_input(text)
async with ctx.typing():
image = self._render(text)
if isinstance(image, BytesIO):
await ctx.send(file=discord.File(image, "latex.png"))
else:
- await ctx.send(image)
+ await ctx.send("```" + image + "```")
def setup(bot: commands.Bot) -> None: