LiYanan2004 / MarkdownView

Rendering Markdown text natively in SwiftUI.
https://liyanan2004.github.io/MarkdownView/documentation/markdownview/
MIT License
193 stars 18 forks source link

Latex with standard $$ #27

Closed AugustDev closed 9 months ago

AugustDev commented 9 months ago

The feature you want to get in MarkdownView I understand that latex is already possible using @latex, however if would be much more useful if one could write usual dollar sign notation such as

# headline

list 
- one
- two

$e^{-x}$

Describe that feature in detail Do not require @latex and instead parse latex blocks as well as markdown.

Is that possible right now with some modifications?

LiYanan2004 commented 9 months ago

NO. That is not contained in CommonMark so it can not parse this kind of text. That’s why @latex comes in.

aheze commented 3 months ago

In my fork I have a hack: add code backticks `` around the latex. Then I extract the LaTeX and render it.

https://github.com/aheze/MarkdownView

extension Renderer {
    mutating func visitInlineCode(_ inlineCode: InlineCode) -> Result {
        let latexString: String? = {
            if inlineCode.code.hasPrefix("$$") && inlineCode.code.hasSuffix("$$") {
                return String(inlineCode.code.dropFirst(2).dropLast(2))
            }

            if inlineCode.code.hasPrefix("$") && inlineCode.code.hasSuffix("$") {
                return String(inlineCode.code.dropFirst().dropLast())
            }

            if inlineCode.code.hasPrefix(#"\("#) && inlineCode.code.hasSuffix(#"\)"#) {
                return String(inlineCode.code.dropFirst(2).dropLast(2))
            }

            if inlineCode.code.hasPrefix(#"\["#) && inlineCode.code.hasSuffix(#"\]"#) {
                return String(inlineCode.code.dropFirst(2).dropLast(2))
            }

            return nil
        }()

        if let latexString {
            let svgImageScale = configuration.svgImageScale * configuration.svgImageScaleMultiplier

            do {
                let image = try LatexRenderer.renderImage(
                    latexString: latexString,
                    svgImageScale: svgImageScale
                )
                .renderingMode(.template)

                return Result(SwiftUI.Text(image).foregroundColor(.primary))
            } catch {
                print("Inline LaTeX error: \(error)")
            }
        }

    // ...
}