Skip to content

Instantly share code, notes, and snippets.

@colelawrence
Last active August 29, 2015 14:02
Show Gist options
  • Save colelawrence/b19321cbe81c1ba57ddf to your computer and use it in GitHub Desktop.
Save colelawrence/b19321cbe81c1ba57ddf to your computer and use it in GitHub Desktop.
CodeMirror 4 use spaces instead of tabs
cm_config = {}
cm_config['extraKeys'] = {
"Tab": checkToUseSpacesInsteadofTabs
}
CodeMirror($(".code")[0], cm_config)
checkToUseSpacesInsteadofTabs = (cm) ->
if(cm.getOption("indentWithTabs"))
return CodeMirror.Pass
indentUnit = cm.getOption("indentUnit")
getYoSpaceCount = (head) ->
# Use preceding to determine what room is taken by tabs
preceding = cm.getRange {line:head.line, ch:0}, head
tabCount = 0
tabreg = /\t/g
while(tabreg.exec preceding)
tabCount++
return indentUnit - (head.ch + tabCount*(indentUnit - 1)) % indentUnit
makeYoSpaces = (spaceCount) ->
spaces = ""
for [1..spaceCount]
spaces += " "
return spaces
putYoSpacesHere = (range) ->
{anchor, head} = range
if anchor.line isnt head.line or anchor.ch isnt head.ch
for line in [anchor.line..head.line]
curLine = cm.getLine(line)
curPos = {line, ch:0}
cm.replaceRange makeYoSpaces(indentUnit), curPos, curPos
#anchor.ch += indentUnit
#head.ch += indentUnit
else
cm.replaceRange makeYoSpaces(getYoSpaceCount(head)), anchor, head
cm.doc.sel.ranges.forEach putYoSpacesHere
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment