Skip to content

Instantly share code, notes, and snippets.

@hirokiky
Last active April 19, 2019 13:39
Show Gist options
  • Save hirokiky/56c95196a443ec7194adfcb4d84db63b to your computer and use it in GitHub Desktop.
Save hirokiky/56c95196a443ec7194adfcb4d84db63b to your computer and use it in GitHub Desktop.
A CodeMirror command to delete 4-space indent or charactor before.
/**
* > if foo:
* > | <= The cursor is here and hit delCharOrIndent command, it willbe
* > | <= here
*
* This command will delete at most 4 spaces before, if text before charactor is all spaces.
* If not on the case, this command will delete charactor as usual.
*/
(function(mod) {
if (typeof exports == "object" && typeof module == "object") // CommonJS
mod(require("codemirror/lib/codemirror"));
else if (typeof define == "function" && define.amd) // AMD
define(["codemirror/lib/codemirror"], mod);
else // Plain browser env
mod(CodeMirror);
})(function(CodeMirror) {
"use strict";
var SPACES_REGEXP = /^( +$)/;
CodeMirror.commands.delCharOrIndent = function(cm) {
// Dedening 4-space indents or deleting char before.
// Getting from the top of line to the cursor
var c = cm.getCursor();
var lineText = cm.getRange({line: c.line, ch: 0}, {line: c.line, ch: c.ch});
// Detecting whether the lineText contains only spaces.
var m = SPACES_REGEXP.exec(lineText);
if (m) {
// If only spaces, deleting at most 4 spaces.
var numDelete = m[1].length < 4 ? m[1].length : 4;
return cm.replaceRange('', {line: c.line, ch: 0}, {line: c.line, ch: numDelete});
} else {
return CodeMirror.commands.delCharBefore(cm);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment