mark.js 1.5 KB

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