0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

RMarkdownの数式をgitlabで表示できるよう変換する

0
Last updated at Posted at 2020-09-01

概要

RMarkdownをmarkdownに変換した時、gitlabでも数式を表示させたい。

lua-filterを使います。

本文

gitlabではRMarkdownは直接レンダリングされませんので、一旦md_documentでGLFM ( Gitlab flavored markdown) に変換しないとなりません。

フロントマターに

output: 
    md_document:
        variant: gfm

と書いておけばknitした時に.mdファイルが生成されますが、この時数式の部分がインラインの
$...$\(...\)に、
別行立ての

$$
...
$$

\[
...
\]

に変換されてしまいます。

Gitlabでは数式を表示するときに、インラインでは$`...`$
別行立てでは

```math 
...
``` # end of math block 

という書式で表すことになっているので、さらに変換してあげないとなりません。

knitrだかrmarkdown::render、あるいはpandocの拡張でなんとか出来ると良いのですが、そこはやり方がわからなかったので、

lua-filterで変換

function Math(el)
    if el.mathtype == "InlineMath" then
        return {pandoc.RawInline("html","$`"), pandoc.RawInline("html",el.text), pandoc.RawInline("html","`$")}
    else
        return {pandoc.RawInline("html","```math"), pandoc.RawInline("html",el.text),pandoc.RawInline("html","```")}
    end
end

をgitlab-md.luaという名称で保存して、

output:
    md_document:
        variant: gfm
        pandoc_args: ["--lua-filter","./gitlab-md.lua"]

とすると、Gitlab書式で数式部が変換されたmarkdown書類が生成されます。

VSCodeで置換(力ずく)

output:
    md_document:
        variant: gfm

だけで生成されたmarkdownファイルを
VSCodeのreplace rules拡張を使って、文字列の置換で対応する方法です。

replace rulesの置換ルール設定は以下。

"replacerules.rules": {
    "Replace inline math to gitlab": {
        "find": "\\\\\\((.*)\\\\\\)",
        "replace": "$$`$1`$$"
    },
    "Replace math fencing start to gitlab": {
        "find": "\\[",
        "replace": "```math",
        "literal": true
    },
    "Replace math fencing end to gitlab" : {
        "find": "\\]",
        "replace": "```",
        "literal": true
    }
},
"replacerules.rulesets": {
    "Replace math gitlab": {
        "rules":[
            "Replace inline math to gitlab",
            "Replace math fencing start to gitlab",
            "Replace math fencing end to gitlab"
        ]
    }
}

Ctrl-Shift-Pからreplace rule: run ruleset...で"replace math gitlab"を呼び出せば、数式部分を一気にgitlab対応に変換できます。

他力本願

md_documentのvariantにgitlabとでも入力すると自動的に全部正しく変換してくれるのが一番良いのですが、ちょっと手が出ないので猛者の誰かがやってくれるのを願いつつ。

lua-filterの書き方がなかなかわからなかったのですが、上記の通り数式だけならなんとかなりました。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?