Skip to content

Instantly share code, notes, and snippets.

@choxi
Last active April 15, 2023 18:58
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save choxi/6fa98f7b203bf2dfdcfa to your computer and use it in GitHub Desktop.
Save choxi/6fa98f7b203bf2dfdcfa to your computer and use it in GitHub Desktop.
# This marked.js extension takes a modified code fence syntax that looks like:
#
# ```ruby(app/controllers/application_controller.rb)
# class ApplicationController < ActionController
# + def new
# - def old
# end
# end
# ```
#
# and should produce code snippets in HTML that look like:
#
# <div class=‘snippet’>
# <div class='file-path’> app/controllers/application_controller.rb </div>
# <pre>
# <code>
# <div class=‘line’>class ApplicationController < ActionController</div>
# <div class=‘line addition’>def new</div>
# <div class=‘line subtraction’>def old</div>
# <div class=‘line’>end</div>
# </code>
# </pre>
# </div>
renderer = new marked.Renderer()
# This is copied from marked.js, because it doesn't make the function accessible outside of the file's scope:
# https://github.com/chjj/marked/blob/master/lib/marked.js#L1076
escapeHTML = (html, encode) ->
html.replace((if not encode then /&(?!#?\w+;)/g else /&/g), "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace /'/g, "&#39;"
renderer.code = (code, language) ->
filePathRegex = /\(([^)]+)\)/
if language? && language.match(filePathRegex)?
filePath = language.match(filePathRegex)[1]
language = language.replace(filePathRegex, "")
renderedLines = []
lines = escapeHTML(code, true).split("\n")
for line in lines
if line[0] == "+"
renderedLines.push("<span class='line addition'>#{line.replace('+', ' ')}</span>")
else if line[0] == "-"
renderedLines.push("<span class='line subtraction'>#{line.replace('-', ' ')}</span>")
else
renderedLines.push("<span class='line'>#{line}</span>")
if filePath?
"<div class='snippet'><div class='file-bar'>#{filePath}</div><pre><code class='lang-#{language}'>#{renderedLines.join("\n")}</code></pre></div>"
else
"<div class='snippet'><pre><code class='lang-#{language}'>#{renderedLines.join("\n")}</code></pre></div>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment