summaryrefslogtreecommitdiff
path: root/lib/banzai
diff options
context:
space:
mode:
authorSean McGivern <sean@mcgivern.me.uk>2016-12-15 14:11:38 +0000
committerSean McGivern <sean@mcgivern.me.uk>2016-12-15 14:11:38 +0000
commit4d1f5837125ffbe363897c8b222536e3e6db8fa5 (patch)
tree231cbd8672324cf0aeae0db291c948adefcfa9fd /lib/banzai
parentecfa8655de37a84007a72c274b5f9662c02499ef (diff)
parent2d170a20dc4cd3423ac7994c797cae8fbed263ba (diff)
downloadgitlab-ce-4d1f5837125ffbe363897c8b222536e3e6db8fa5.tar.gz
Merge branch 'katex-math' into 'master'
Render math in Asciidoc and Markdown with KaTeX using code blocks Closes #13690 and #13180 See merge request !8003
Diffstat (limited to 'lib/banzai')
-rw-r--r--lib/banzai/filter/math_filter.rb51
-rw-r--r--lib/banzai/pipeline/gfm_pipeline.rb1
2 files changed, 52 insertions, 0 deletions
diff --git a/lib/banzai/filter/math_filter.rb b/lib/banzai/filter/math_filter.rb
new file mode 100644
index 00000000000..cb037f89337
--- /dev/null
+++ b/lib/banzai/filter/math_filter.rb
@@ -0,0 +1,51 @@
+require 'uri'
+
+module Banzai
+ module Filter
+ # HTML filter that adds class="code math" and removes the dollar sign in $`2+2`$.
+ #
+ class MathFilter < HTML::Pipeline::Filter
+ # This picks out <code>...</code>.
+ INLINE_MATH = 'descendant-or-self::code'.freeze
+
+ # Pick out a code block which is declared math
+ DISPLAY_MATH = "descendant-or-self::pre[contains(@class, 'math') and contains(@class, 'code')]".freeze
+
+ # Attribute indicating inline or display math.
+ STYLE_ATTRIBUTE = 'data-math-style'.freeze
+
+ # Class used for tagging elements that should be rendered
+ TAG_CLASS = 'js-render-math'.freeze
+
+ INLINE_CLASSES = "code math #{TAG_CLASS}".freeze
+
+ DOLLAR_SIGN = '$'.freeze
+
+ def call
+ doc.xpath(INLINE_MATH).each do |code|
+ closing = code.next
+ opening = code.previous
+
+ # We need a sibling before and after.
+ # They should end and start with $ respectively.
+ if closing && opening &&
+ closing.content.first == DOLLAR_SIGN &&
+ opening.content.last == DOLLAR_SIGN
+
+ code[:class] = INLINE_CLASSES
+ code[STYLE_ATTRIBUTE] = 'inline'
+ closing.content = closing.content[1..-1]
+ opening.content = opening.content[0..-2]
+ end
+ end
+
+ doc.xpath(DISPLAY_MATH).each do |el|
+ el[STYLE_ATTRIBUTE] = 'display'
+ el[:class] += " #{TAG_CLASS}"
+ end
+
+ doc
+ end
+ end
+ end
+end
diff --git a/lib/banzai/pipeline/gfm_pipeline.rb b/lib/banzai/pipeline/gfm_pipeline.rb
index 5da2d0b008c..5a1f873496c 100644
--- a/lib/banzai/pipeline/gfm_pipeline.rb
+++ b/lib/banzai/pipeline/gfm_pipeline.rb
@@ -6,6 +6,7 @@ module Banzai
Filter::SyntaxHighlightFilter,
Filter::SanitizationFilter,
+ Filter::MathFilter,
Filter::UploadLinkFilter,
Filter::VideoLinkFilter,
Filter::ImageLinkFilter,