Merge pull request #1345 from ajaxorg/toggleComment

Toggle comments
This commit is contained in:
Ruben Daniels 2013-04-18 08:48:08 -07:00
commit 076eeb8cab
9 changed files with 223 additions and 70 deletions

View file

@ -342,6 +342,11 @@ exports.commands = [{
bindKey: bindKey("Ctrl-/", "Command-/"), bindKey: bindKey("Ctrl-/", "Command-/"),
exec: function(editor) { editor.toggleCommentLines(); }, exec: function(editor) { editor.toggleCommentLines(); },
multiSelectAction: "forEachLine" multiSelectAction: "forEachLine"
}, {
name: "toggleBlockComment",
bindKey: bindKey("Ctrl-Shift-/", "Command-Shift-/"),
exec: function(editor) { editor.toggleBlockComment(); },
multiSelectAction: "forEach"
}, { }, {
name: "modifyNumberUp", name: "modifyNumberUp",
bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"), bindKey: bindKey("Ctrl-Shift-Up", "Alt-Shift-Up"),

View file

@ -1272,7 +1272,6 @@ var Editor = function(renderer, session) {
}; };
/** /**
*
* Given the currently selected range, this function either comments all the lines, or uncomments all of them. * Given the currently selected range, this function either comments all the lines, or uncomments all of them.
**/ **/
this.toggleCommentLines = function() { this.toggleCommentLines = function() {
@ -1281,6 +1280,13 @@ var Editor = function(renderer, session) {
this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last); this.session.getMode().toggleCommentLines(state, this.session, rows.first, rows.last);
}; };
this.toggleBlockComment = function() {
var cursor = this.getCursorPosition();
var state = this.session.getState(cursor.row);
var range = this.getSelectionRange();
this.session.getMode().toggleBlockComment(state, this.session, range, cursor);
};
/** /**
* Works like [[EditSession.getTokenAt]], except it returns a number. * Works like [[EditSession.getTokenAt]], except it returns a number.
* @returns {Number} * @returns {Number}
@ -1449,7 +1455,6 @@ var Editor = function(renderer, session) {
}); });
}; };
/** /**
* Executes a specific function, which can be anything that manipulates selected lines, such as copying them, duplicating them, or shifting them. * Executes a specific function, which can be anything that manipulates selected lines, such as copying them, duplicating them, or shifting them.
* @param {Function} mover A method to call on each selected row * @param {Function} mover A method to call on each selected row

View file

@ -51,7 +51,7 @@ AceEmmetEditor.prototype = {
setupContext: function(editor) { setupContext: function(editor) {
this.ace = editor; this.ace = editor;
this.indentation = editor.session.getTabString(); this.indentation = editor.session.getTabString();
emmet.require('resources').setVariable('indentation', this.indentation); emmet.require("resources").setVariable("indentation", this.indentation);
this.$syntax = null; this.$syntax = null;
this.$syntax = this.getSyntax(); this.$syntax = this.getSyntax();
}, },
@ -164,7 +164,7 @@ AceEmmetEditor.prototype = {
end = start == null ? content.length : start; end = start == null ? content.length : start;
if (start == null) if (start == null)
start = 0; start = 0;
var utils = emmet.require('utils'); var utils = emmet.require("utils");
// indent new value // indent new value
if (!noIndent) { if (!noIndent) {
@ -172,7 +172,7 @@ AceEmmetEditor.prototype = {
} }
// find new caret position // find new caret position
var tabstopData = emmet.require('tabStops').extract(value, { var tabstopData = emmet.require("tabStops").extract(value, {
escape: function(ch) { escape: function(ch) {
return ch; return ch;
} }
@ -218,7 +218,7 @@ AceEmmetEditor.prototype = {
if (this.$syntax) if (this.$syntax)
return this.$syntax; return this.$syntax;
var syntax = this.ace.session.$modeId.split("/").pop(); var syntax = this.ace.session.$modeId.split("/").pop();
if (syntax == 'html' || syntax == "php") { if (syntax == "html" || syntax == "php") {
var cursor = this.ace.getCursorPosition(); var cursor = this.ace.getCursorPosition();
var state = this.ace.session.getState(cursor.row); var state = this.ace.session.getState(cursor.row);
if (typeof state != "string") if (typeof state != "string")
@ -240,18 +240,18 @@ AceEmmetEditor.prototype = {
*/ */
getProfileName: function() { getProfileName: function() {
switch(this.getSyntax()) { switch(this.getSyntax()) {
case 'css': return css; case "css": return "css";
case 'xml': case "xml":
case 'xsl': case "xsl":
return 'xml'; return "xml";
case 'html': case "html":
var profile = emmet.require('resources').getVariable('profile'); var profile = emmet.require("resources").getVariable("profile");
// no forced profile, guess from content html or xhtml? // no forced profile, guess from content html or xhtml?
if (!profile) if (!profile)
profile = this.ace.session.getLines(0,2).join("").search(/<!DOCTYPE[^>]+XHTML/i) != -1 ? 'xhtml': 'html'; profile = this.ace.session.getLines(0,2).join("").search(/<!DOCTYPE[^>]+XHTML/i) != -1 ? "xhtml": "html";
return profile; return profile;
} }
return 'xhtml'; return "xhtml";
}, },
/** /**
@ -279,7 +279,7 @@ AceEmmetEditor.prototype = {
* @since 0.65 * @since 0.65
*/ */
getFilePath: function() { getFilePath: function() {
return ''; return "";
} }
}; };
@ -291,7 +291,7 @@ var keymap = {
matching_pair: {"mac": "ctrl+alt+j", "win": "alt+j"}, matching_pair: {"mac": "ctrl+alt+j", "win": "alt+j"},
next_edit_point: "alt+right", next_edit_point: "alt+right",
prev_edit_point: "alt+left", prev_edit_point: "alt+left",
toggle_comment: {"mac": "command+shift+/", "win": "ctrl+shift+/"}, toggle_comment: {"mac": "command+/", "win": "ctrl+/"},
split_join_tag: {"mac": "shift+command+'", "win": "shift+ctrl+`"}, split_join_tag: {"mac": "shift+command+'", "win": "shift+ctrl+`"},
remove_tag: {"mac": "command+'", "win": "shift+ctrl+;"}, remove_tag: {"mac": "command+'", "win": "shift+ctrl+;"},
evaluate_math_expression: {"mac": "shift+command+y", "win": "shift+ctrl+y"}, evaluate_math_expression: {"mac": "shift+command+y", "win": "shift+ctrl+y"},
@ -318,12 +318,13 @@ function runEmmetCommand(editor) {
editorProxy.setupContext(editor); editorProxy.setupContext(editor);
if (editorProxy.getSyntax() == "php") if (editorProxy.getSyntax() == "php")
return false; return false;
var actions = emmet.require('actions') var actions = emmet.require("actions")
try { try {
var result = actions.run(this.name, editorProxy); var result = actions.run(this.name, editorProxy);
} catch(e) { } catch(e) {
editor._signal("changeStatus", typeof e == "string" ? e : e.message); editor._signal("changeStatus", typeof e == "string" ? e : e.message);
console.log(e);
} }
return result; return result;
} }

View file

@ -45,12 +45,12 @@ module.exports = {
this.mode = new ColdfusionMode(); this.mode = new ColdfusionMode();
}, },
"test: toggle comment lines should not do anything" : function() { "test: toggle comment lines" : function() {
var session = new EditSession([" abc", "cde", "fg"]); var session = new EditSession([" abc", " cde", "fg"]);
var range = new Range(0, 3, 1, 1); var range = new Range(0, 3, 1, 1);
var comment = this.mode.toggleCommentLines("start", session, 0, 1); var comment = this.mode.toggleCommentLines("start", session, 0, 1);
assert.equal([" abc", "cde", "fg"].join("\n"), session.toString()); assert.equal([" <!--abc-->", " <!--cde-->", "fg"].join("\n"), session.toString());
}, },
"test: next line indent should be the same as the current line indent" : function() { "test: next line indent should be the same as the current line indent" : function() {

View file

@ -47,11 +47,11 @@ module.exports = {
this.mode = new CssMode(); this.mode = new CssMode();
}, },
"test: toggle comment lines should not do anything" : function() { "test: toggle comment lines" : function() {
var session = new EditSession([" abc", "cde", "fg"].join("\n")); var session = new EditSession([" abc", "cde", "fg"].join("\n"));
var comment = this.mode.toggleCommentLines("start", session, 0, 1); var comment = this.mode.toggleCommentLines("start", session, 0, 1);
assert.equal([" abc", "cde", "fg"].join("\n"), session.toString()); assert.equal(["/* abc*/", "/*cde*/", "fg"].join("\n"), session.toString());
}, },

View file

@ -45,12 +45,12 @@ module.exports = {
this.mode = new HtmlMode(); this.mode = new HtmlMode();
}, },
"test: toggle comment lines should not do anything" : function() { "test: toggle comment lines" : function() {
var session = new EditSession([" abc", "cde", "fg"]); var session = new EditSession([" abc", "", "fg"]);
var range = new Range(0, 3, 1, 1); var range = new Range(0, 3, 1, 1);
var comment = this.mode.toggleCommentLines("start", session, 0, 1); var comment = this.mode.toggleCommentLines("start", session, 0, 1);
assert.equal([" abc", "cde", "fg"].join("\n"), session.toString()); assert.equal([" <!--abc-->", "", "fg"].join("\n"), session.toString());
}, },
"test: next line indent should be the same as the current line indent" : function() { "test: next line indent should be the same as the current line indent" : function() {

View file

@ -67,6 +67,33 @@ module.exports = {
this.mode.toggleCommentLines("start", session, 0, 1); this.mode.toggleCommentLines("start", session, 0, 1);
assert.equal([" abc", "cde", "fg"].join("\n"), session.toString()); assert.equal([" abc", "cde", "fg"].join("\n"), session.toString());
}, },
"test: toggle comment on all empty lines" : function() {
var session = new EditSession([" ", " ", " "]);
this.mode.toggleCommentLines("start", session, 0, 1);
assert.equal([" // ", " // ", " "].join("\n"), session.toString());
},
"test: toggle comment with empty lines" : function() {
var session = new EditSession([
" abc",
"",
" cde",
" fg"]);
var initial = session.toString();
this.mode.toggleCommentLines("start", session, 0, 3);
assert.equal([
" // abc",
"",
" // cde",
" // fg"].join("\n"),
session.toString()
);
this.mode.toggleCommentLines("start", session, 0, 3);
assert.equal(initial, session.toString());
},
"test: toggle comment lines twice should return the original text" : function() { "test: toggle comment lines twice should return the original text" : function() {
var session = new EditSession([" abc", "cde", "fg"]); var session = new EditSession([" abc", "cde", "fg"]);

View file

@ -3,7 +3,7 @@
* *
* Copyright (c) 2010, Ajax.org B.V. * Copyright (c) 2010, Ajax.org B.V.
* All rights reserved. * All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met: * modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright * * Redistributions of source code must retain the above copyright
@ -14,7 +14,7 @@
* * Neither the name of Ajax.org B.V. nor the * * Neither the name of Ajax.org B.V. nor the
* names of its contributors may be used to endorse or promote products * names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission. * derived from this software without specific prior written permission.
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
@ -36,6 +36,8 @@ var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
var Behaviour = require("./behaviour").Behaviour; var Behaviour = require("./behaviour").Behaviour;
var unicode = require("../unicode"); var unicode = require("../unicode");
var lang = require("../lib/lang"); var lang = require("../lib/lang");
var TokenIterator = require("../token_iterator").TokenIterator;
var Range = require("../range").Range;
var Mode = function() { var Mode = function() {
this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules()); this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules());
@ -50,7 +52,7 @@ var Mode = function() {
+ unicode.packages.Nd + unicode.packages.Nd
+ unicode.packages.Pc + "\\$_]+", "g" + unicode.packages.Pc + "\\$_]+", "g"
); );
this.nonTokenRe = new RegExp("^(?:[^" this.nonTokenRe = new RegExp("^(?:[^"
+ unicode.packages.L + unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Mn + unicode.packages.Mc
@ -62,46 +64,159 @@ var Mode = function() {
return this.$tokenizer; return this.$tokenizer;
}; };
this.lineCommentStart = "";
this.blockComment = "";
this.toggleCommentLines = function(state, session, startRow, endRow) { this.toggleCommentLines = function(state, session, startRow, endRow) {
var doc = session.doc; var doc = session.doc;
var regexpStart, lineCommentStart;
var ignoreBlankLines = true;
var shouldRemove = true;
var minIndent = Infinity;
if (!this.lineCommentStart) { if (!this.lineCommentStart) {
return false if (!this.blockComment)
} else if (Array.isArray(this.lineCommentStart)) { return false;
regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|"); var lineCommentStart = this.blockComment.start;
lineCommentStart = this.lineCommentStart[0]; var lineCommentEnd = this.blockComment.end;
var regexpStart = new RegExp("^(\\s*)(?:" + lang.escapeRegExp(lineCommentStart) + ")");
var regexpEnd = new RegExp("(?:" + lang.escapeRegExp(lineCommentEnd) + ")\\s*$");
var comment = function(line, i) {
if (testRemove(line, i))
return;
if (!ignoreBlankLines || /\S/.test(line)) {
doc.insertInLine({row: i, column: line.length}, lineCommentEnd);
doc.insertInLine({row: i, column: minIndent}, lineCommentStart);
}
};
var uncomment = function(line, i) {
var m;
if (m = line.match(regexpEnd))
doc.removeInLine(i, line.length - m[0].length, line.length);
if (m = line.match(regexpStart))
doc.removeInLine(i, m[1].length, m[0].length);
};
var testRemove = function(line, row) {
if (regexpStart.test(line))
return true;
var tokens = session.getTokens(row);
for (var i = 0; i < tokens.length; i++) {
if (tokens[i].type === 'comment')
return true;
}
};
} else { } else {
regexpStart = lang.escapeRegExp(this.lineCommentStart); if (Array.isArray(this.lineCommentStart)) {
lineCommentStart = this.lineCommentStart; var regexpStart = this.lineCommentStart.map(lang.escapeRegExp).join("|");
} var lineCommentStart = this.lineCommentStart[0] + " ";
regexpStart = new RegExp("^\\s*(?:" + regexpStart + ") ?"); } else {
var regexpStart = lang.escapeRegExp(this.lineCommentStart);
var lineCommentStart = this.lineCommentStart + " ";
}
regexpStart = new RegExp("^(\\s*)(?:" + regexpStart + ") ?");
var removeComment = true; var uncomment = function(line, i) {
var minSpace = Infinity;
var indentations = [];
for (var i = startRow; i <= endRow; i++) {
var line = doc.getLine(i);
var indent = line.search(/\S|$/);
indentations[i] = indent;
if (indent < minSpace)
minSpace = indent;
if (removeComment && !regexpStart.test(line))
removeComment = false;
}
if (removeComment) {
for (var i = startRow; i <= endRow; i++) {
var line = doc.getLine(i);
var m = line.match(regexpStart); var m = line.match(regexpStart);
doc.removeInLine(i, indentations[i], m[0].length); m && doc.removeInLine(i, m[1].length, m[0].length);
};
var comment = function(line, i) {
if (!ignoreBlankLines || /\S/.test(line))
doc.insertInLine({row: i, column: minIndent}, lineCommentStart);
};
var testRemove = function(line, i) {
return regexpStart.test(line);
};
}
function iter(fun) {
for (var i = startRow; i <= endRow; i++)
fun(doc.getLine(i), i);
}
var minEmptyLength = Infinity;
iter(function(line, i) {
var indent = line.search(/\S/);
if (indent !== -1) {
if (indent < minIndent)
minIndent = indent;
if (shouldRemove && !testRemove(line, i))
shouldRemove = false;
} else if (minEmptyLength > line.length) {
minEmptyLength = line.length;
}
});
if (minIndent == Infinity) {
minIndent = minEmptyLength;
ignoreBlankLines = false;
shouldRemove = false;
}
iter(shouldRemove ? uncomment : comment);
};
this.toggleBlockComment = function(state, session, range, cursor) {
var comment = this.blockComment;
if (!comment)
return;
if (!comment.start && comment[0])
comment = comment[0];
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
var sel = session.selection;
var initialRange = session.selection.toOrientedRange();
var startRow, colDiff;
if (token && /comment/.test(token.type)) {
var startRange, endRange;
while (token && /comment/.test(token.type)) {
var i = token.value.indexOf(comment.start);
if (i != -1) {
var row = iterator.getCurrentTokenRow();
var column = iterator.getCurrentTokenColumn() + i;
startRange = new Range(row, column, row, column + comment.start.length);
break
}
token = iterator.stepBackward();
};
var iterator = new TokenIterator(session, cursor.row, cursor.column);
var token = iterator.getCurrentToken();
while (token && /comment/.test(token.type)) {
var i = token.value.indexOf(comment.end);
if (i != -1) {
var row = iterator.getCurrentTokenRow();
var column = iterator.getCurrentTokenColumn() + i;
endRange = new Range(row, column, row, column + comment.end.length);
break;
}
token = iterator.stepForward();
}
if (endRange)
session.remove(endRange);
if (startRange) {
session.remove(startRange);
startRow = startRange.start.row;
colDiff = -comment.start.length
} }
} else { } else {
lineCommentStart += " "; colDiff = comment.start.length
for (var i = startRow; i <= endRow; i++) { startRow = range.start.row;
doc.insertInLine({row: i, column: minSpace}, lineCommentStart); session.insert(range.end, comment.end);
} session.insert(range.start, comment.start);
} }
// todo: selection should have ended up in the right place automatically!
if (initialRange.start.row == startRow)
initialRange.start.column += colDiff;
if (initialRange.end.row == startRow)
initialRange.end.column += colDiff;
session.selection.fromOrientedRange(initialRange);
}; };
this.getNextLineIndent = function(state, line, tab) { this.getNextLineIndent = function(state, line, tab) {
@ -118,7 +233,7 @@ var Mode = function() {
this.$getIndent = function(line) { this.$getIndent = function(line) {
return line.match(/^\s*/)[0]; return line.match(/^\s*/)[0];
}; };
this.createWorker = function(session) { this.createWorker = function(session) {
return null; return null;
}; };
@ -133,7 +248,7 @@ var Mode = function() {
this.$modes[this.$embeds[i]] = new mapping[this.$embeds[i]](); this.$modes[this.$embeds[i]] = new mapping[this.$embeds[i]]();
} }
} }
var delegations = ['toggleCommentLines', 'getNextLineIndent', 'checkOutdent', 'autoOutdent', 'transformAction']; var delegations = ['toggleCommentLines', 'getNextLineIndent', 'checkOutdent', 'autoOutdent', 'transformAction'];
for (var i = 0; i < delegations.length; i++) { for (var i = 0; i < delegations.length; i++) {
@ -145,14 +260,14 @@ var Mode = function() {
} }
} (this)); } (this));
} }
} };
this.$delegator = function(method, args, defaultHandler) { this.$delegator = function(method, args, defaultHandler) {
var state = args[0]; var state = args[0];
for (var i = 0; i < this.$embeds.length; i++) { for (var i = 0; i < this.$embeds.length; i++) {
if (!this.$modes[this.$embeds[i]]) continue; if (!this.$modes[this.$embeds[i]]) continue;
var split = state.split(this.$embeds[i]); var split = state.split(this.$embeds[i]);
if (!split[0] && split[1]) { if (!split[0] && split[1]) {
args[0] = split[1]; args[0] = split[1];
@ -163,7 +278,7 @@ var Mode = function() {
var ret = defaultHandler.apply(this, args); var ret = defaultHandler.apply(this, args);
return defaultHandler ? ret : undefined; return defaultHandler ? ret : undefined;
}; };
this.transformAction = function(state, action, editor, session, param) { this.transformAction = function(state, action, editor, session, param) {
if (this.$behaviour) { if (this.$behaviour) {
var behaviours = this.$behaviour.getBehaviours(); var behaviours = this.$behaviour.getBehaviours();
@ -176,8 +291,8 @@ var Mode = function() {
} }
} }
} }
} };
}).call(Mode.prototype); }).call(Mode.prototype);
exports.Mode = Mode; exports.Mode = Mode;

View file

@ -55,10 +55,10 @@ module.exports = {
}, },
"test: toggle comment lines should not do anything" : function() { "test: toggle comment lines should not do anything" : function() {
var session = new EditSession([" abc", "cde", "fg"]); var session = new EditSession([" abc", " cde", "fg"]);
this.mode.toggleCommentLines("start", session, 0, 1); this.mode.toggleCommentLines("start", session, 0, 1);
assert.equal([" abc", "cde", "fg"].join("\n"), session.toString()); assert.equal([" <!-- abc-->", " <!--cde-->", "fg"].join("\n"), session.toString());
}, },
"test: next line indent should be the same as the current line indent" : function() { "test: next line indent should be the same as the current line indent" : function() {