class CodeButton extends Button
name: 'code'
icon: 'code'
htmlTag: 'pre'
disableTag: 'ul, ol, table'
_init: ->
super()
@editor.on 'decorate', (e, $el) =>
$el.find('pre').each (i, pre) =>
@decorate $(pre)
@editor.on 'undecorate', (e, $el) =>
$el.find('pre').each (i, pre) =>
@undecorate $(pre)
render: (args...) ->
super args...
@popover = new CodePopover
button: @
_checkMode: ->
range = @editor.selection.range()
if ($blockNodes = $(range.cloneContents()).find(@editor.util.blockNodes.join(','))) > 0 or
(range.collapsed and @editor.selection.startNodes().filter('code').length == 0)
@inlineMode = false
@htmlTag = 'pre'
else
@inlineMode = true
@htmlTag = 'code'
_status: ->
@_checkMode()
super()
return if @inlineMode
if @active
@popover.show(@node)
else
@popover.hide()
decorate: ($pre) ->
$code = $pre.find('> code')
if $code.length > 0
lang = $code.attr('class')?.match(/lang-(\S+)/)?[1]
$code.contents().unwrap()
$pre.attr('data-lang', lang) if lang
undecorate: ($pre) ->
lang = $pre.attr('data-lang')
$code = $('')
$code.addClass('lang-' + lang) if lang and lang != -1
$pre.wrapInner($code)
.removeAttr('data-lang')
command: ->
if @inlineMode
@_inlineCommand()
else
@_blockCommand()
_blockCommand: ->
$rootNodes = @editor.selection.rootNodes()
nodeCache = []
resultNodes = []
clearCache = =>
return unless nodeCache.length > 0
$pre = $("<#{@htmlTag}/>")
.insertBefore(nodeCache[0])
.text(@editor.formatter.clearHtml(nodeCache))
resultNodes.push $pre[0]
nodeCache.length = 0
$rootNodes.each (i, node) =>
$node = $ node
if $node.is @htmlTag
clearCache()
$p = $('