mark.js (1562B)
1 'use strict'; 2 3 4 var common = require('./common'); 5 6 7 function Mark(name, buffer, position, line, column) { 8 this.name = name; 9 this.buffer = buffer; 10 this.position = position; 11 this.line = line; 12 this.column = column; 13 } 14 15 16 Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { 17 var head, start, tail, end, snippet; 18 19 if (!this.buffer) return null; 20 21 indent = indent || 4; 22 maxLength = maxLength || 75; 23 24 head = ''; 25 start = this.position; 26 27 while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { 28 start -= 1; 29 if (this.position - start > (maxLength / 2 - 1)) { 30 head = ' ... '; 31 start += 5; 32 break; 33 } 34 } 35 36 tail = ''; 37 end = this.position; 38 39 while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { 40 end += 1; 41 if (end - this.position > (maxLength / 2 - 1)) { 42 tail = ' ... '; 43 end -= 5; 44 break; 45 } 46 } 47 48 snippet = this.buffer.slice(start, end); 49 50 return common.repeat(' ', indent) + head + snippet + tail + '\n' + 51 common.repeat(' ', indent + this.position - start + head.length) + '^'; 52 }; 53 54 55 Mark.prototype.toString = function toString(compact) { 56 var snippet, where = ''; 57 58 if (this.name) { 59 where += 'in "' + this.name + '" '; 60 } 61 62 where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); 63 64 if (!compact) { 65 snippet = this.getSnippet(); 66 67 if (snippet) { 68 where += ':\n' + snippet; 69 } 70 } 71 72 return where; 73 }; 74 75 76 module.exports = Mark;