irongit

A Neovim plugin enabling you to solve LeetCode problems.

93 lines2.6 KBLua
1local Object = require("nui.object")
2local u = require("leetcode.parser.utils")
3
4local log = require("leetcode.logger")
5
6---@class lc.Normalizer
7local Normalizer = Object("LeetNormalizer")
8
9function Normalizer:cleanup() --
10 self.text = self
11 .text --
12 :gsub("​", "")
13 :gsub("\r\n", "\n")
14 :gsub("<br%s*/>", "\n")
15 :gsub("<meta[^>]*/>", "")
16 :gsub("&nbsp;", " ")
17 -- :gsub("<(/?)b([^>]*)>", "<%1strong%2>")
18 :gsub("<(/?)b>", "<%1strong>")
19 -- :gsub("&#?%w+;", function(e) --
20 -- return vim.tbl_keys({})
21 -- end)
22
23 -- for e, char in pairs(u.entities) do
24 -- self.text = self.text:gsub(e, char)
25 -- end
26end
27
28function Normalizer:fix_indent()
29 self.text = self
30 .text --
31 :gsub("(\n+)(\t+)", "%1")
32 :gsub("<(/?li)>\n*", "<%1>\n\n")
33 :gsub("\n*(<ul[^>]*>)\n*", "\n\n%1\n")
34 :gsub("\n*(<ol[^>]*>)\n*", "\n\n%1\n")
35 :gsub("\n*(<pre[^>]*>)", "\n\n%1\n")
36 :gsub("\n*(<img[^>]*/?>)\n*", "\n\n%1\n\n")
37end
38
39function Normalizer:tags() --
40 self.text = self
41 .text --
42 :gsub("<strong>(Input:?%s*)</strong>", "<input>%1</input>")
43 :gsub("<strong>(Output:?%s*)</strong>", "<output>%1</output>")
44 :gsub("<strong>(Explanation:?%s*)</strong>", "<explanation>%1</explanation>")
45 :gsub("<strong>(Note:?%s*)</strong>", "<explanation>%1</explanation>")
46 :gsub("<strong>(Follow-up:?%s*)</strong>", "<followup>%1</followup>")
47 :gsub("<strong>(Follow up:?%s*)</strong>", "<followup>%1</followup>")
48 :gsub(
49 "\n*<p>%s*<strong[^>]*>(Example%s*%d*:?)%s*</strong>%s*</p>\n*",
50 "\n\n<example>󰛨 %1</example>\n\n"
51 )
52 :gsub(
53 "\n*<p>%s*<strong[^>]*>(Constraints:?)%s*</strong>%s*</p>\n*",
54 "\n\n<constraints> %1</constraints>\n\n"
55 )
56end
57
58function Normalizer:entities()
59 self.text = self
60 .text --
61 :gsub("\n*<p>%s*</p>\n*", "&lcpad;")
62 :gsub("\n*<p> *</p>\n*", "&lcpad;")
63 :gsub("<([^>]+)>(%s*)</%1>", "%2")
64 :gsub("\n", "&lcnl;")
65 :gsub("\t", "&lctab;")
66 :gsub("%s", "&nbsp;")
67 :gsub("<[^>]+>", function(match)
68 return match:gsub("&nbsp;", " ")
69 end)
70end
71
72---@param text string
73function Normalizer:init(text) --
74 log.debug(text)
75
76 self.text = text
77 self:cleanup()
78 self:fix_indent()
79 self:tags()
80 self:entities()
81
82 log.debug(self.text:gsub("&lcnl;", "\n"), false)
83end
84
85---@type fun(text: string): lc.Normalizer
86local LeetNormalizer = Normalizer
87
88---@param text string
89function Normalizer:norm(text)
90 return LeetNormalizer(text).text
91end
92
93return LeetNormalizer