jQuery.fn.getSelectionRange = (el)->
element = if el? then $(el)[0] else document.activeElement
selection = rangy.getNativeSelection()
# If a range is selected
if selection.type == 'Range'
rangy_selection = rangy.saveSelection()
reg = /<span .*?class="(.*?rangySelectionBoundary.*?)">(.*?)<\/span>/gi
start = reg.exec(element.innerHTML)
end = reg.exec(element.innerHTML)
rangy.removeMarkers(rangy_selection)
return { start: start.index, end: end.index - start[0].length}
else if selection.type == 'Caret'
# If caret is inside a li tag
if $(selection.baseNode).parents("li").length > 0
li_el = $(selection.baseNode).parents("li")[0]
$(li_el).wrap($("<span />").addClass("rangySelectionBoundary"))
length = $(li_el).parents("span.rangySelectionBoundary:first")[0].innerHTML.length
reg = /<span .*?class="(.*?rangySelectionBoundary.*?)">(.*?)<\/span>/gi
start = reg.exec(element.innerHTML)
$(li_el).parents('span.rangySelectionBoundary').contents().unwrap()
return { start: start.index, end: start.index + length}
else
document.execCommand 'formatBlock', null, '<h1>'
h1 = $(element).find('h1')[0]
length = h1.innerHTML.length
reg = /<h1>.*<\/h1>/gi
start = reg.exec(element.innerHTML)
$("<br>").insertAfter(h1)
$(h1).contents().unwrap()
return { start: start.index, end: start.index + length}
This solved my problem.