我设法通过修改标签来jekyll-katex
解决错误code
(内联,使用单个波浪号)和pre code
(使用缩进或3个波浪号制作的块):
# frozen_string_literal: true
require 'jekyll'
require 'jekyll-katex/configuration'
require 'jekyll-katex/katex_js'
require 'nokogiri'
module Jekyll
module Tags
# Defines the custom Liquid tag for compile-time rendering of KaTeX math.
# This differs from the katex tag in that it allows use of `$` and `$$` fencing to mark math mode blocks similar to
# standard latex.
# {% katexmm %}
# This is a mixed environment where you can write text as normal but fence off latex math using `$`. Escape
# using `\$`. For example.
# $latex math with \$$
# $$display mode latex$$
# {% endkatexmm %}
class KatexMathModeFixed < Liquid::Block
LOG_TOPIC = 'KatexMathModeFixed:'
KATEX ||= Jekyll::Katex::KATEX_JS
LATEX_TOKEN_PATTERN = /(?<!\\)([$]{2}|[$]{1})(.+?)(?<!\\)\1/m
def initialize(tag_name, markup, tokens)
super
@markup = markup
@tokens = tokens
@display_mode_rendering = Jekyll::Katex::Configuration.global_rendering_options.merge(displayMode: true)
@inline_mode_rendering = Jekyll::Katex::Configuration.global_rendering_options.merge(displayMode: false)
end
def render(context)
enclosed_block = super
fixed_block = fix_code(enclosed_block)
rendered_str = fixed_block.to_s.gsub(LATEX_TOKEN_PATTERN) do |match|
display_mode = match.to_s.start_with? '$$'
rendering_options = display_mode ? @display_mode_rendering : @inline_mode_rendering
Jekyll.logger.debug LOG_TOPIC, "Rendering matched block - #{match}"
KATEX.call('katex.renderToString', Regexp.last_match(2), rendering_options)
end
# KaTeX should fix escaped `$` within fenced blocks, this addresses instances outside of math mode
rendered_str.to_s.gsub(/\\[$]/, '$').to_s
end
def fix_code(input)
updated = false
html = Nokogiri::HTML.fragment(input)
Jekyll.logger.debug LOG_TOPIC, "Fixing - #{input}"
html.css("code, code span").each do |c|
if c.css('*').empty? && c.content['$']
updated = true
Jekyll.logger.debug LOG_TOPIC, "current tag - #{c}"
content = c.content
content['$'] = '\$'
c.content = content
Jekyll.logger.debug LOG_TOPIC, "current tag now - #{c}/#{content}"
end
end
output = html.to_s
Jekyll.logger.debug LOG_TOPIC, "Fixed - #{output}"
if updated then html.to_s else input end
end
end
end
end
Liquid::Template.register_tag('katexmmx', Jekyll::Tags::KatexMathModeFixed)
它可以安装在_plugins
目录中。
问题是,这仍然是错误的 - 默认情况下 kramdown 仍然尝试使用 mathjax 引擎并生成<script type="math/tex">
,因此必须进行更改。当我研究如何做时,我发现 kramdown 也支持math_engine: katex
- 我只需要添加字体和 CSS,然后jekyll-katex
就完全过时了(以及我的解决方法,如果有人好奇,我会留在这里)。