Emacs 代碼块导出复用

在寫博客時,有時我需要顯示代碼,同時把代碼导出成 HTML,放在頁面裡用。例如在 一些關於連結的建議::進階樣式 裡,我要介紹外部連結的樣式,同時要將樣式應用在頁面上,原來我會這麼做:

一個代碼块 (#+begin_src css) 用於顯示代碼:

#+begin_src css
  a[href^='http']:not([href^='http://taxodium.ink']):not([href^='https://taxodium.ink']) {
    &::after {
      /* 省略 */
    }
  }
#+end_src

一個导出块 (#+begin_export html),複製和代碼块相同的內容,把它导出到 HTML:

#+begin_export html
<style>
@scope {
  a[href^='http']:not([href^='http://taxodium.ink']):not([href^='https://taxodium.ink']) {
    &::after {
      /* 省略 */
    }
  }
}
<style>
#+end_export

但修改時就要改兩個地方,煩得很。那有沒有辦法可以复用代碼呢?當然是有的。

在 Org Mode 裡可以利用 noweb 去引用代碼块,給被引用的代碼块一個名字 (#+name: some-name),在引用的代碼块上設置 :noweb yes ,就可以用 <<some-name>> 就引用代碼块了。

於是上面的重复代碼就可以變成這樣:

1.定義被引用的代碼块并命名

#+name: css-external-link
#+begin_src css
  a[href^='http']:not([href^='http://taxodium.ink']):not([href^='https://taxodium.ink']) {
    &::after {
      /* 省略 */
    }
  }
#+end_src

2.在另一個代碼块上引用

#+begin_src shell :noweb yes :exports results :results output html
  cat <<'CSS_EOF'
  <style>
    @scope {
      <<css-external-link>>
    }
  </style>
  CSS_EOF
#+end_src
  • 在代碼块上開啟 noweb,即 :noweb yes ,然後就可以用 <<css-external-link>> 引用名字為 css-external-link 的代碼块。
  • 由於最終希望將代碼导出成 HTML 嵌在頁面中,需要設置 :exports results 1,這樣代碼的 执行結果 才會导出到頁面裡。
  • :results output html 2,其中 output 指定代碼以脚本運行,并把標準輸出作為結果返回;html 會把結果用 BEGIN_EXPORT html 包裹。
  • 代碼中的 'CSS_EOF' 是 heredoc,用來輸入多行字符串用的。開頭的 'CSS_EOF' 標記起始,最後單獨一行的 CSS_EOF 標記結束,中間的多行是實際輸入的字符。

最終就會變成這樣:

#+begin_export html
<style>
@scope {
  a[href^='http']:not([href^='http://taxodium.ink']):not([href^='https://taxodium.ink']) {
    &::after {
      /* 省略 */
    }
  }
}
<style>
#+end_export

這樣就不用寫重复代碼啦 (ノ>ω<)ノ


感謝你的閱讀和訂閱,有什麼想法歡迎 郵件 跟我交流,祝好 :)

純文本版本 原始 org 文件