Skip to content

Commit

Permalink
transforms, claytext: lift out Transforms::INLINE
Browse files Browse the repository at this point in the history
  • Loading branch information
artagnon committed Jul 5, 2024
1 parent 0efb2ae commit 26ab15e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 17 deletions.
26 changes: 9 additions & 17 deletions lib/clayoven/claytext.rb
Original file line number Diff line number Diff line change
Expand Up @@ -79,19 +79,11 @@ def self.line_transforms!(paragraphs)
end
end

# We only HTML escape very few things, for simplicity
HTMLESCAPE_RULES = { "&" => "&amp;", "<" => "&lt;", ">" => "&gt;" }.freeze

# Insert <{mark, strong, em, a, br}> into the paragraph after escaping HTML
# Perform the transforms in Clayoven::Claytext::Transforms::INLINE on
# Paragraph entries in-place
def self.inline_transforms!(paragraphs)
paragraphs.each do |p|
p.replace p
.gsub(/[<>&]/, HTMLESCAPE_RULES)
.gsub(/`([^`]+)`/, '<mark>\1</mark>')
.gsub(/!\{([^\}]+)\}/, '<strong>\1</strong>')
.gsub(/!_\{([^\}]+)\}/, '<em>\1</em>')
.gsub(/\[([^\[\]]+)\]\(([^)]+)\)/, '<a href="\2">\1</a>')
.gsub("\u{23CE}", "<br>")
Transforms::INLINE.each do |regex, replacement|
paragraphs.each { |p| p.gsub! regex, replacement }
end
end

Expand All @@ -110,11 +102,11 @@ def self.process(body)
line_transforms! (paragraphs.filter { |p| p.type == :plain })

# Finally, do inline transforms on paragraphs untouched by the fenced transforms
inline_transforms! (
paragraphs.reject { |p|
%i[codeblock images mathjax].count(p.type).positive?
}
)
filtered_paragraphs =
paragraphs.reject do |p|
%i[codeblock images mathjax].count(p.type).positive?
end
inline_transforms! filtered_paragraphs

# Result: paragraphs
paragraphs
Expand Down
15 changes: 15 additions & 0 deletions lib/clayoven/transforms.rb
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,19 @@ module Clayoven::Claytext::Transforms
p.replace ["$$", XYMATRIX_START, p.to_s, XYMATRIX_END, "$$"].join("\n")
end
}.freeze

# Inline transforms
#
# Regex replacements for HTML escape, <{mark, strong, em, a, br}>.
# We only HTML escape very few things, for simplicity
INLINE = {
"&" => "&amp;",
"<" => "&lt;",
">" => "&gt;",
/`([^`]+)`/ => '<mark>\1</mark>',
/!\{([^\}]+)\}/ => '<strong>\1</strong>',
/!_\{([^\}]+)\}/ => '<em>\1</em>',
/\[([^\[\]]+)\]\(([^)]+)\)/ => '<a href="\2">\1</a>',
"\u{23CE}" => "<br>"
}.freeze
end

0 comments on commit 26ab15e

Please sign in to comment.