niszetの日記

細かい情報を載せていくブログ

(Pandoc) docx -> md への逆変換のメモ(4回目)

コード周りは一旦これでおしまい。

さて、前回はテンプレートファイルに"Source Code R"のようなスタイルを追加し、CodeBlockはその外側にこのスタイルを持ったDivを配置することで、生成されたdocxの見た目に影響なく、元となった言語情報を保存することをしました。

今度はdocxからmdへ変換する対応です。

これは、Div要素が対応するカスタムスタイルを持っていた場合に、その子要素であるCodeBlockに対して、class情報を与えるということで対応できます。

あれ?Codeじゃないのか?という感じですが、変換した結果わかったのですが、Para+Codeはどこかのタイミングで最適化されてCodeBlockとなります。

この最適化が発生するタイミングによっては今回のこの方法がうまくいかない可能性もあるのですが、とりあえず動いているのでヨシ!として進めます。

コードはこんな感じになります。

function Div(e)
  for k, v in pairs(e.attributes) do
    if k == "custom-style" then
      if string.match(v, "Source Code") then
        local sclang = text.lower(string.gsub(string.gsub(v, "Source Code", ""), " ", ""))
          for k2, v2 in pairs(e.content) do
            if v2.tag == "CodeBlock" then
              if sclang ~= "" then
                v2.classes[1] = sclang
              end
              return(v2)
            end
          end
      end
    end
  end
  return(e)
end

マッチしないDivはそのまま返していますが、上記の条件にマッチした場合はDivを取り払っています。また、素のSource Codeの場合はclassを与えずにそのままCodeBlockを返しています(Divは削除)

これに、下記のコードを実行すれば、

pandoc word.docx -f docx+styles -t markdown+backtick_code_blocks -o word_rev.md -s --atx-headers --wrap=none --extract-media=hoge -L div.lua

結果は、

---
author: niszet
date: 2020/5/20
title: word
---

## R Markdown

::: {custom-style="First Paragraph"}
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see [[http://rmarkdown.rstudio.com]{custom-style="Hyperlink"}](http://rmarkdown.rstudio.com).
:::

::: {custom-style="Body Text"}
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
:::

summary(cars)

    ##      speed           dist       
    ##  Min.   : 4.0   Min.   :  2.00  
    ##  1st Qu.:12.0   1st Qu.: 26.00  
    ##  Median :15.0   Median : 36.00  
    ##  Mean   :15.4   Mean   : 42.98  
    ##  3rd Qu.:19.0   3rd Qu.: 56.00  
    ##  Max.   :25.0   Max.   :120.00

## Including Plots

::: {custom-style="First Paragraph"}
You can also embed plots, for example:
:::

::: {custom-style="Body Text"}
![](hoge/media/rId23.png){width="5.0526312335958in" height="4.0421052055993in"}
:::

::: {custom-style="Body Text"}
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
:::

こんな感じです。割と良い感じではないでしょうか…?まぁ、Indented Code Blockはこのままがいいのか、空のclassかattributesをもたせてbacktickにするべきか?などがありますが…。

しかし、こうしてみるとカスタムスタイルを表示しない方が良いのでは?というサンプルになっていますね…。あるいは、不要なカスタムスタイルは同様にして消してしまうというのもありかもしれませんね。

さて、ひとまずこれでコードブロックに対するdocx -> mdの変換の対応はひとまず終わりです。もう少し込み入ったドキュメントじゃないと困りどころが出てこないかもしれませんね。

さて、画像ファイルの名前の対応をするか、表の対応をするか…。思いついたらやっていきます。