2 Copyright (c) 2012, Yahoo! Inc. All rights reserved.
3 Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
6 function InsertionText(text, consumeBlanks) {
8 this.origLength = text.length;
10 this.consumeBlanks = consumeBlanks;
11 this.startPos = this.findFirstNonBlank();
12 this.endPos = this.findLastNonBlank();
15 var WHITE_RE = /[ \f\n\r\t\v\u00A0\u2028\u2029]/;
17 InsertionText.prototype = {
19 findFirstNonBlank: function () {
24 for (i = 0; i < len; i += 1) {
25 if (!text.charAt(i).match(WHITE_RE)) {
32 findLastNonBlank: function () {
35 pos = text.length + 1,
37 for (i = len - 1; i >= 0; i -= 1) {
38 if (!text.charAt(i).match(WHITE_RE)) {
45 originalLength: function () {
46 return this.origLength;
49 insertAt: function (col, str, insertBefore, consumeBlanks) {
50 consumeBlanks = typeof consumeBlanks === 'undefined' ? this.consumeBlanks : consumeBlanks;
51 col = col > this.originalLength() ? this.originalLength() : col;
52 col = col < 0 ? 0 : col;
55 if (col <= this.startPos) {
58 if (col > this.endPos) {
59 col = this.origLength;
64 offset = this.findOffset(col, len, insertBefore),
65 realPos = col + offset,
67 this.text = text.substring(0, realPos) + str + text.substring(realPos);
71 findOffset: function (pos, len, insertBefore) {
72 var offsets = this.offsets,
77 for (i = 0; i < offsets.length; i += 1) {
78 offsetObj = offsets[i];
79 if (offsetObj.pos < pos || (offsetObj.pos === pos && !insertBefore)) {
80 cumulativeOffset += offsetObj.len;
82 if (offsetObj.pos >= pos) {
86 if (offsetObj && offsetObj.pos === pos) {
89 offsets.splice(i, 0, { pos: pos, len: len });
91 return cumulativeOffset;
94 wrap: function (startPos, startText, endPos, endText, consumeBlanks) {
95 this.insertAt(startPos, startText, true, consumeBlanks);
96 this.insertAt(endPos, endText, false, consumeBlanks);
100 wrapLine: function (startText, endText) {
101 this.wrap(0, startText, this.originalLength(), endText);
104 toString: function () {
109 module.exports = InsertionText;