Skip to content

Instantly share code, notes, and snippets.

@genmeblog
Last active January 22, 2021 18:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save genmeblog/14a03bf7ee67f3435376e482e3981759 to your computer and use it in GitHub Desktop.
Save genmeblog/14a03bf7ee67f3435376e482e3981759 to your computer and use it in GitHub Desktop.
Clojure to markdown

Convert source code to Markdown using Marginalia parser

(ns mrgtst.core
  (:require [marginalia.parser :as p]
            [clojure.string :as str]))

Create code block from given string s

(defn- code-block
  [s]
  (str "\n```clojure\n" s "\n```\n\n"))

Save markdown built from clojure source

(defn save-md
  [filename]
  (let [target (str (second (re-find #"(.*)\.(\w+)$" filename)) ".md")]
    (spit target "")
    (doseq [{:keys [docstring raw form type] :as all} (p/parse-file filename)]
      (spit target
            (condp = type
              :code (str docstring (code-block raw))
              :comment (if (str/starts-with? raw "=>")
                         (str "Result:" (code-block raw))
                         (str raw "\n\n")))
            :append true))))

Saving md for this file

(save-md "src/mrgtst/core.clj")

Other stuff

Let's define some functions,

Sum two numbers a and b

(defn sum
  [a b]
  (+ a b))

let's check the reuslt

(sum 12 -22)

Result:

=> -10

Table

First Header Second Header
Content from cell 1 Content from cell 2
Content in the first column Content in the second column
;; # Convert source code to Markdown using Marginalia parser
;;
(ns mrgtst.core
(:require [marginalia.parser :as p]
[clojure.string :as str]))
(defn- code-block
"Create code block from given string `s`"
[s]
(str "\n```clojure\n" s "\n```\n\n"))
(defn save-md
"Save markdown built from clojure source"
[filename]
(let [target (str (second (re-find #"(.*)\.(\w+)$" filename)) ".md")]
(spit target "")
(doseq [{:keys [docstring raw form type] :as all} (p/parse-file filename)]
(spit target
(condp = type
:code (str docstring (code-block raw))
:comment (if (str/starts-with? raw "=>")
(str "Result:" (code-block raw))
(str raw "\n\n")))
:append true))))
;; Saving md for this file
(save-md "src/mrgtst/core.clj")
;; ## Other stuff
;;
;; Let's define some functions.
(defn sum
"Sum two numbers `a` and `b`"
[a b]
(+ a b))
;; let's check the reuslt
(sum 12 -22)
;; => -10
;; ## Table
;; First Header | Second Header
;; ------------ | -------------
;; Content from cell 1 | Content from cell 2
;; Content in the first column | Content in the second column
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment