Plugin

Unindent

Trims leading indentation from codeblocks

Chat Utility
index.ts
Download

Source

src/plugins/unindent/index.ts
1import { MessageObject } from "@api/MessageEvents";
2import { Devs } from "@utils/constants";
3import definePlugin from "@utils/types";
4
5export default definePlugin({
6 name: "Unindent",
7 description: "Trims leading indentation from codeblocks",
8 tags: ["Chat", "Utility"],
9 authors: [Devs.Ven],
10
11 patches: [
12 {
13 find: "inQuote:",
14 replacement: {
15 match: /,content:([^,]+),inQuote/,
16 replace: (_, content) => `,content:$self.unindent(${content}),inQuote`
17 }
18 }
19 ],
20
21 unindent(str: string) {
22 // Users cannot send tabs, they get converted to spaces. However, a bot may send tabs, so convert them to 4 spaces first
23 str = str.replace(/\t/g, " ");
24 const minIndent = str.match(/^ *(?=\S)/gm)
25 ?.reduce((prev, curr) => Math.min(prev, curr.length), Infinity) ?? 0;
26
27 if (!minIndent) return str;
28 return str.replace(new RegExp(`^ {${minIndent}}`, "gm"), "");
29 },
30
31 unindentMsg(msg: MessageObject) {
32 msg.content = msg.content.replace(/```(.|\n)*?```/g, m => {
33 const lines = m.split("\n");
34 if (lines.length < 2) return m; class="ts-cmt">// Do not affect inline codeblocks
35 let suffix = "";
36 if (lines[lines.length - 1] === "```") suffix = lines.pop()!;
37 return `${lines[0]}\n${this.unindent(lines.slice(1).join("\n"))}\n${suffix}`;
38 });
39 },
40
41 onBeforeMessageSend(_, msg) {
42 return this.unindentMsg(msg);
43 },
44
45 onBeforeMessageEdit(_cid, _mid, msg) {
46 return this.unindentMsg(msg);
47 }
48});
49