Support code that is all indented #59

Closed
wants to merge 2 commits into
from
Jump to file or symbol
Failed to load files and symbols.
+40 −5
Split
View
@@ -40,8 +40,10 @@ exports.parseComments = function(js, options){
if (buf.trim().length) {
comment = comments[comments.length - 1];
if(comment) {
- comment.code = code = buf.trim();
- comment.ctx = exports.parseCodeContext(code);
+ code = exports.parseCode(buf);
+ comment.code = code.code;
+ comment.codeIndent = code.indent;
+ comment.ctx = exports.parseCodeContext(buf.trim());
}
buf = '';
}
@@ -74,9 +76,10 @@ exports.parseComments = function(js, options){
// trailing code
if (buf.trim().length) {
comment = comments[comments.length - 1];
- code = buf.trim();
- comment.code = code;
- comment.ctx = exports.parseCodeContext(code);
+ code = exports.parseCode(buf);
+ comment.code = code.code;
+ comment.codeIndent = code.indent;
+ comment.ctx = exports.parseCodeContext(buf.trim());
}
return comments;
@@ -203,6 +206,38 @@ exports.parseTagTypes = function(str) {
.split(/ *[|,\/] */);
};
+/**
+ * Trim whitespace correctly and remove excess indentation.
+ *
+ * @param {String} str Untrimmed source code
+ * @return {Object}
+ * @api public
+ */
+exports.parseCode = function(str) {
+ var lines = str.split(/\n/g);
+ var minIndent = Infinity;
+ var lastLine = 0;
+ var firstLine = Infinity;
+ var code = '';
+ for (var i = 0; i < lines.length; i++) {
+ if (lines[i].trim().length > 0) {
+ var lineIndent = /^ */.exec(lines[i])[0].length;
+ minIndent = Math.min(minIndent, lineIndent);
+ firstLine = Math.min(i, firstLine);
+ lastLine = i;
+ }
+ }
+ for (var i = firstLine; i <= lastLine; i++) {
+ if(i!==firstLine){
+ code += '\n';
+ }
+ if (lines[i].trim().length > 0) {
+ code += lines[i].substr(minIndent);
+ }
+ }
+ return {code:code, indent:minIndent};
+};
+
/**
* Parse the context from the given `str` of js.
*