Created
May 11, 2011 13:26
-
-
Save dennishall/966445 to your computer and use it in GitHub Desktop.
Strip Trailing Whitespace (Macro for Komodo Edit)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// also available at http://jsfiddle.net/dennishall/UydZn/ | |
var previousIndentation = ''; | |
var indent = " "; | |
/** | |
* Standard setup for a method | |
* | |
* @param Function callback The content of the script | |
*/ | |
function execScript ( callback ){ | |
if ( !komodo.view ) | |
return; | |
komodo.view.setFocus(); | |
ko.views.manager.currentView.scimoz.beginUndoAction(); | |
try { | |
callback(); | |
} | |
finally { | |
ko.views.manager.currentView.scimoz.endUndoAction(); | |
} | |
} | |
/** | |
* Applies a callback to the entire document | |
* | |
* @param Function callback The callback to apply | |
*/ | |
function applyToDocument ( callback ) { | |
var view = ko.views.manager.currentView; | |
// grab the current position of the cursor | |
var pos = view.scimoz.currentPos; | |
var line = view.scimoz.lineFromPosition( pos ); | |
var col = view.scimoz.getColumn( pos ); | |
// Apply the fix | |
view.document.buffer = callback( view.document.buffer ); | |
// Find the best place to put the cursor | |
var startOfLine = view.scimoz.positionFromLine(line); | |
view.scimoz.gotoPos( | |
// If the line they were on has been deleted... | |
startOfLine == -1 | |
? view.document.bufferLength | |
: Math.min( | |
view.scimoz.getLineEndPosition(line), | |
view.scimoz.positionFromLine(line) + col | |
) | |
); | |
} | |
// The actual script that cleans up the white space | |
execScript( function() { | |
applyToDocument( function (text) { | |
var lines = text.split("\n"); | |
for(var i=0, l=lines.length; i<l; i++){ | |
var line = lines[i]; | |
if(line.length && !/^\s+$/.test(line)){ | |
previousIndentation = (/^[\t ]+.*$/.test(line) ? line.replace(/^([\t ]+).*$/, '$1') : '') + (line[line.length-1] == '{' ? indent : ''); | |
lines[i] = line.replace(/(\S)[\t ]+$/mg, '$1'); | |
} else { | |
lines[i] = previousIndentation; | |
} | |
if(line == ""){ | |
lines[i] = previousIndentation; | |
} | |
} | |
return lines.join("\n"); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment