This commit is contained in:
Yessiest 2022-11-30 12:16:45 +04:00
commit e3ff2331ad
3 changed files with 123 additions and 0 deletions

22
.solargraph.yml Normal file
View File

@ -0,0 +1,22 @@
---
include:
- "**/*.rb"
exclude:
- spec/**/*
- test/**/*
- vendor/**/*
- ".bundle/**/*"
require: ["minitest"]
domains: []
reporters:
- rubocop
- require_not_found
formatter:
rubocop:
cops: safe
except: []
only: []
extra_args: []
require_paths: []
plugins: []
max_files: 5000

94
markdown.rb Normal file
View File

@ -0,0 +1,94 @@
## Filter-based Markdown translator.
module Markdown
## Translator for linear tags in Markdown.
# A linear tag is any tag that starts anywhere on the line, and closes on the same exact line.
class LinearTagTranslator
def initialize(text)
@input = text
end
def escape(text)
text.sub /([*`~_!\[])/,"\\\1"
end
def to_html
@input
# Newline
.sub /\s{2}[\n\r]/,"<br/>"
# Inline code (discord style)
.sub /(?<!\\)``(.*?[^\\])``/, { |code|
"<code>#{self.escape code}</code>"
}
# Inline code (Markdown style)
.sub /(?<!\\)`(.*?[^\\])`/, { |code|
"<code>#{self.escape code}</code>"
}
# Bold-italics
.sub /(?<!\\)\*\*\*(.*?[^\\])\*\*\*/,"<i><b>\1</b></i>"
# Bold
.sub /(?<!\\)\*\*(.*?[^\\])\*\*/,"<b>\1</b>"
# Italics
.sub /(?<!\\)\*(.*?[^\\])\*/,"<i>\1</i>"
# Strikethrough
.sub /(?<!\\)~~(.*?[^\\])~~/,"<s>\1</s>"
# Underline
.sub /(?<!\\)__(.*?[^\\])__/,"<span style=\"text-decoration: underline\">\1</span>"
# Image
.sub /(?<!\\)!\[(.*)\]\((.*)\)/,"<img src=\"\2\" alt=\"\1\" />"
# Link
.sub /(?<!\\)\[(.*)\]\((.*)\)/,"<a href=\"\2\">\1</a>"
end
end
## Translator for linear leftmost tags.
# Leftmost linear tags open on the leftmost end of the string, and close once the line ends. These tags do not need to be explicitly closed.
class LeftmostTagTranslator
def initalize(text)
@input = text
end
def to_html
# Headers
@input.sub(/(?<!\\)(\#{1,4})([^\n\r]*)/) { |level,content|
"<h#{level.length}>"+content+"</h#{level.length}>"
}
end
end
## Translator for code blocks in Markdown.
# First in terms of precedence.
class CodeBlocksTranslator
def initialize(text
end
## Translator for quotes in Markdown.
# These deserve their own place in hell.
class QuoteTranslator
def initialize(text, level: 0)
if text.is_a? Array then
@lines = text
elsif text.is_a? String then
@lines = text.split("\n\n")
end
end
def to_html
stack = []
range = []
state = false
@lines.each_with_index { |x,index|
if x.match(/^\s{0,1}>/) and state == false then
range.append index
state = true
end
if (not x.match /^\s{0,1}>/) and state == true then
range.append index-1
state = false
stack.append(range[0]..range[1])
range = []
end
}
range.each { |r|
@lines[r] = QuoteTranslator.new(@lines[r]).to_html
}
@lines = @lines.map { |x|
(x.sub /^\s{0,1}>/,"")
}
end
end
end

7
test.rb Normal file
View File

@ -0,0 +1,7 @@
require "minitest"
require "markdown"
class LinearParsingTest << Minitest::Test
def setup
@lparser =