Skip to content

Instantly share code, notes, and snippets.

@pedroaxl
Last active December 30, 2015 19:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedroaxl/7871887 to your computer and use it in GitHub Desktop.
Save pedroaxl/7871887 to your computer and use it in GitHub Desktop.
SirTrevor h1, h2 and h3 formatters. The code isn't 100%, the regular expressions for toHTML methods are a little buggy, but I am working on it.
# Our base formatters
(->
checkElementActive = () ->
selection = window.getSelection()
node = undefined
node = selection.getRangeAt(0).startContainer.parentNode if selection.rangeCount > 0
node and node.nodeName is this.title.toUpperCase()
formatBlockOnClick = () ->
elem = if this.isActive() then '<div>' else this.param
document.execCommand('formatBlock', false, elem)
# http://stackoverflow.com/questions/10810940/javascript-document-execcommand-remove-formatblock-formatting
H1 = SirTrevor.Formatter.extend(
title: "h1"
cmd: "formatBlock"
keyCode: 49
text: "h1"
param: '<h1>'
isActive: checkElementActive
onClick: formatBlockOnClick
toMarkdown: (content, type) ->
content.replace(/<br>/,"\n").replace(/<h1.*?>(?:\s*)(.*?)(\s*)?<\/h1>/i, "#$1\n ")
toHTML: (markdown, type) ->
markdown.replace(/^\w*\s*\t*#\s*([^#]*)\s*$/, "<h1>$1</h1>\n")
)
H2 = SirTrevor.Formatter.extend(
title: "h2"
cmd: "formatBlock"
keyCode: 451
text: "h2"
param: '<h2>'
isActive: checkElementActive
onClick: formatBlockOnClick
toMarkdown: (content, type) ->
content.replace(/<br\/?>/,"\n").replace(/<h2.*?>(?:\s*)(.*?)(\s*)?<\/h2>/i, "##$1\n ")
toHTML: (markdown, type) ->
markdown.replace(/^\w*\s*\t*##\s*([^#]*)\s*$/, "<h2>$1</h2>\n")
)
H3 = SirTrevor.Formatter.extend(
title: "h3"
cmd: "formatBlock"
keyCode: 51
text: "h3"
param: '<h3>'
isActive: checkElementActive
onClick: formatBlockOnClick
toMarkdown: (content, type) ->
content.replace(/<br>/,"\n").replace(/<h3.*?>(?:\s*)(.*?)(\s*)?<\/h3>/i, "###$1\n ")
toHTML: (markdown, type) ->
markdown.replace(/^\w*\s*\t*###\s*([^#]*)\s*$/, "<h3>$1</h3>\n")
)
#
# Create our formatters and add a static reference to them
#
SirTrevor.Formatters.H1 = new H1()
SirTrevor.Formatters.H2 = new H2()
SirTrevor.Formatters.H3 = new H3()
)()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment