OSDN Git Service

https://github.com/rahuldottech/Dabr
[embrj/master.git] / i / js / twitter-text.js
1 (function() {
2   if (typeof twttr === "undefined" || twttr === null) {
3     var twttr = {};
4   }
5
6   twttr.txt = {};
7   twttr.txt.regexen = {};
8
9   var HTML_ENTITIES = {
10     '&': '&',
11     '>': '>',
12     '<': '&lt;',
13     '"': '&quot;',
14     "'": '&#39;'
15   };
16
17   // HTML escaping
18   twttr.txt.htmlEscape = function(text) {
19     return text && text.replace(/[&"'><]/g, function(character) {
20       return HTML_ENTITIES[character];
21     });
22   };
23
24   // Builds a RegExp
25   function regexSupplant(regex, flags) {
26     flags = flags || "";
27     if (typeof regex !== "string") {
28       if (regex.global && flags.indexOf("g") < 0) {
29         flags += "g";
30       }
31       if (regex.ignoreCase && flags.indexOf("i") < 0) {
32         flags += "i";
33       }
34       if (regex.multiline && flags.indexOf("m") < 0) {
35         flags += "m";
36       }
37
38       regex = regex.source;
39     }
40
41     return new RegExp(regex.replace(/#\{(\w+)\}/g, function(match, name) {
42       var newRegex = twttr.txt.regexen[name] || "";
43       if (typeof newRegex !== "string") {
44         newRegex = newRegex.source;
45       }
46       return newRegex;
47     }), flags);
48   }
49
50   twttr.txt.regexSupplant = regexSupplant;
51
52   // simple string interpolation
53   function stringSupplant(str, values) {
54     return str.replace(/#\{(\w+)\}/g, function(match, name) {
55       return values[name] || "";
56     });
57   }
58
59   twttr.txt.stringSupplant = stringSupplant;
60
61   function addCharsToCharClass(charClass, start, end) {
62     var s = String.fromCharCode(start);
63     if (end !== start) {
64       s += "-" + String.fromCharCode(end);
65     }
66     charClass.push(s);
67     return charClass;
68   }
69
70   twttr.txt.addCharsToCharClass = addCharsToCharClass;
71
72   // Space is more than %20, U+3000 for example is the full-width space used with Kanji. Provide a short-hand
73   // to access both the list of characters and a pattern suitible for use with String#split
74   // Taken from: ActiveSupport::Multibyte::Handlers::UTF8Handler::UNICODE_WHITESPACE
75   var fromCode = String.fromCharCode;
76   var UNICODE_SPACES = [
77     fromCode(0x0020), // White_Space # Zs       SPACE
78     fromCode(0x0085), // White_Space # Cc       <control-0085>
79     fromCode(0x00A0), // White_Space # Zs       NO-BREAK SPACE
80     fromCode(0x1680), // White_Space # Zs       OGHAM SPACE MARK
81     fromCode(0x180E), // White_Space # Zs       MONGOLIAN VOWEL SEPARATOR
82     fromCode(0x2028), // White_Space # Zl       LINE SEPARATOR
83     fromCode(0x2029), // White_Space # Zp       PARAGRAPH SEPARATOR
84     fromCode(0x202F), // White_Space # Zs       NARROW NO-BREAK SPACE
85     fromCode(0x205F), // White_Space # Zs       MEDIUM MATHEMATICAL SPACE
86     fromCode(0x3000)  // White_Space # Zs       IDEOGRAPHIC SPACE
87   ];
88   addCharsToCharClass(UNICODE_SPACES, 0x009, 0x00D); // White_Space # Cc   [5] <control-0009>..<control-000D>
89   addCharsToCharClass(UNICODE_SPACES, 0x2000, 0x200A); // White_Space # Zs  [11] EN QUAD..HAIR SPACE
90
91   var INVALID_CHARS = [
92     fromCode(0xFFFE),
93     fromCode(0xFEFF), // BOM
94     fromCode(0xFFFF) // Special
95   ];
96   addCharsToCharClass(INVALID_CHARS, 0x202A, 0x202E); // Directional change
97
98   twttr.txt.regexen.spaces_group = regexSupplant(UNICODE_SPACES.join(""));
99   twttr.txt.regexen.spaces = regexSupplant("[" + UNICODE_SPACES.join("") + "]");
100   twttr.txt.regexen.invalid_chars_group = regexSupplant(INVALID_CHARS.join(""));
101   twttr.txt.regexen.punct = /\!'#%&'\(\)*\+,\\\-\.\/:;<=>\?@\[\]\^_{|}~\$/;
102   twttr.txt.regexen.rtl_chars = /[\u0600-\u06FF]|[\u0750-\u077F]|[\u0590-\u05FF]|[\uFE70-\uFEFF]/mg;
103   twttr.txt.regexen.non_bmp_code_pairs = /[\uD800-\uDBFF][\uDC00-\uDFFF]/mg;
104
105   var latinAccentChars = [];
106   // Latin accented characters (subtracted 0xD7 from the range, it's a confusable multiplication sign. Looks like "x")
107   addCharsToCharClass(latinAccentChars, 0x00c0, 0x00d6);
108   addCharsToCharClass(latinAccentChars, 0x00d8, 0x00f6);
109   addCharsToCharClass(latinAccentChars, 0x00f8, 0x00ff);
110   // Latin Extended A and B
111   addCharsToCharClass(latinAccentChars, 0x0100, 0x024f);
112   // assorted IPA Extensions
113   addCharsToCharClass(latinAccentChars, 0x0253, 0x0254);
114   addCharsToCharClass(latinAccentChars, 0x0256, 0x0257);
115   addCharsToCharClass(latinAccentChars, 0x0259, 0x0259);
116   addCharsToCharClass(latinAccentChars, 0x025b, 0x025b);
117   addCharsToCharClass(latinAccentChars, 0x0263, 0x0263);
118   addCharsToCharClass(latinAccentChars, 0x0268, 0x0268);
119   addCharsToCharClass(latinAccentChars, 0x026f, 0x026f);
120   addCharsToCharClass(latinAccentChars, 0x0272, 0x0272);
121   addCharsToCharClass(latinAccentChars, 0x0289, 0x0289);
122   addCharsToCharClass(latinAccentChars, 0x028b, 0x028b);
123   // Okina for Hawaiian (it *is* a letter character)
124   addCharsToCharClass(latinAccentChars, 0x02bb, 0x02bb);
125   // Combining diacritics
126   addCharsToCharClass(latinAccentChars, 0x0300, 0x036f);
127   // Latin Extended Additional
128   addCharsToCharClass(latinAccentChars, 0x1e00, 0x1eff);
129   twttr.txt.regexen.latinAccentChars = regexSupplant(latinAccentChars.join(""));
130
131   var unicodeLettersAndMarks = "A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08E4-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C03\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D01-\u0D03\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u18A9\u1920-\u192B\u1930-\u193B\u19B0-\u19C0\u19C8\u19C9\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF5\u1DFC-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C4\uA8E0-\uA8F1\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2D";
132   var unicodeNumbers = "0-9\u0660-\u0669\u06F0-\u06F9\u07C0-\u07C9\u0966-\u096F\u09E6-\u09EF\u0A66-\u0A6F\u0AE6-\u0AEF\u0B66-\u0B6F\u0BE6-\u0BEF\u0C66-\u0C6F\u0CE6-\u0CEF\u0D66-\u0D6F\u0DE6-\u0DEF\u0E50-\u0E59\u0ED0-\u0ED9\u0F20-\u0F29\u1040-\u1049\u1090-\u1099\u17E0-\u17E9\u1810-\u1819\u1946-\u194F\u19D0-\u19D9\u1A80-\u1A89\u1A90-\u1A99\u1B50-\u1B59\u1BB0-\u1BB9\u1C40-\u1C49\u1C50-\u1C59\uA620-\uA629\uA8D0-\uA8D9\uA900-\uA909\uA9D0-\uA9D9\uA9F0-\uA9F9\uAA50-\uAA59\uABF0-\uABF9\uFF10-\uFF19";
133   var hashtagSpecialChars = "_\u200c\u200d\ua67e\u05be\u05f3\u05f4\u309b\u309c\u30a0\u30fb\u3003\u0f0b\u0f0c\u00b7";
134
135   // A hashtag must contain at least one unicode letter or mark, as well as numbers, underscores, and select special characters.
136   twttr.txt.regexen.hashSigns = /[##]/;
137   twttr.txt.regexen.hashtagAlpha = new RegExp("[" + unicodeLettersAndMarks + "]");
138   twttr.txt.regexen.hashtagAlphaNumeric = new RegExp("[" + unicodeLettersAndMarks + unicodeNumbers + hashtagSpecialChars + "]");
139   twttr.txt.regexen.endHashtagMatch = regexSupplant(/^(?:#{hashSigns}|:\/\/)/);
140   twttr.txt.regexen.hashtagBoundary = new RegExp("(?:^|$|[^&" + unicodeLettersAndMarks + unicodeNumbers + hashtagSpecialChars + "])");
141   twttr.txt.regexen.validHashtag = regexSupplant(/(#{hashtagBoundary})(#{hashSigns})(?!\ufe0f|\u20e3)(#{hashtagAlphaNumeric}*#{hashtagAlpha}#{hashtagAlphaNumeric}*)/gi);
142
143   // Mention related regex collection
144   twttr.txt.regexen.validMentionPrecedingChars = /(?:^|[^a-zA-Z0-9_!#$%&*@@]|(?:^|[^a-zA-Z0-9_+~.-])(?:rt|RT|rT|Rt):?)/;
145   twttr.txt.regexen.atSigns = /[@@]/;
146   twttr.txt.regexen.validMentionOrList = regexSupplant(
147     '(#{validMentionPrecedingChars})' +  // $1: Preceding character
148     '(#{atSigns})' +                     // $2: At mark
149     '([a-zA-Z0-9_]{1,20})' +             // $3: Screen name
150     '(\/[a-zA-Z][a-zA-Z0-9_\-]{0,24})?'  // $4: List (optional)
151   , 'g');
152   twttr.txt.regexen.validReply = regexSupplant(/^(?:#{spaces})*#{atSigns}([a-zA-Z0-9_]{1,20})/);
153   twttr.txt.regexen.endMentionMatch = regexSupplant(/^(?:#{atSigns}|[#{latinAccentChars}]|:\/\/)/);
154
155   // URL related regex collection
156   twttr.txt.regexen.validUrlPrecedingChars = regexSupplant(/(?:[^A-Za-z0-9@@$###{invalid_chars_group}]|^)/);
157   twttr.txt.regexen.invalidUrlWithoutProtocolPrecedingChars = /[-_.\/]$/;
158   twttr.txt.regexen.invalidDomainChars = stringSupplant("#{punct}#{spaces_group}#{invalid_chars_group}", twttr.txt.regexen);
159   twttr.txt.regexen.validDomainChars = regexSupplant(/[^#{invalidDomainChars}]/);
160   twttr.txt.regexen.validSubdomain = regexSupplant(/(?:(?:#{validDomainChars}(?:[_-]|#{validDomainChars})*)?#{validDomainChars}\.)/);
161   twttr.txt.regexen.validDomainName = regexSupplant(/(?:(?:#{validDomainChars}(?:-|#{validDomainChars})*)?#{validDomainChars}\.)/);
162   twttr.txt.regexen.validGTLD = regexSupplant(RegExp(
163     '(?:(?:' +
164     'abb|abbott|abogado|academy|accenture|accountant|accountants|aco|active|actor|ads|adult|aeg|aero|' +
165     'afl|agency|aig|airforce|airtel|allfinanz|alsace|amsterdam|android|apartments|app|aquarelle|' +
166     'archi|army|arpa|asia|associates|attorney|auction|audio|auto|autos|axa|azure|band|bank|bar|' +
167     'barcelona|barclaycard|barclays|bargains|bauhaus|bayern|bbc|bbva|bcn|beer|bentley|berlin|best|' +
168     'bet|bharti|bible|bid|bike|bing|bingo|bio|biz|black|blackfriday|bloomberg|blue|bmw|bnl|' +
169     'bnpparibas|boats|bond|boo|boots|boutique|bradesco|bridgestone|broker|brother|brussels|budapest|' +
170     'build|builders|business|buzz|bzh|cab|cafe|cal|camera|camp|cancerresearch|canon|capetown|capital|' +
171     'caravan|cards|care|career|careers|cars|cartier|casa|cash|casino|cat|catering|cba|cbn|ceb|center|' +
172     'ceo|cern|cfa|cfd|chanel|channel|chat|cheap|chloe|christmas|chrome|church|cisco|citic|city|' +
173     'claims|cleaning|click|clinic|clothing|cloud|club|coach|codes|coffee|college|cologne|com|' +
174     'commbank|community|company|computer|condos|construction|consulting|contractors|cooking|cool|' +
175     'coop|corsica|country|coupons|courses|credit|creditcard|cricket|crown|crs|cruises|cuisinella|' +
176     'cymru|cyou|dabur|dad|dance|date|dating|datsun|day|dclk|deals|degree|delivery|delta|democrat|' +
177     'dental|dentist|desi|design|dev|diamonds|diet|digital|direct|directory|discount|dnp|docs|dog|' +
178     'doha|domains|doosan|download|drive|durban|dvag|earth|eat|edu|education|email|emerck|energy|' +
179     'engineer|engineering|enterprises|epson|equipment|erni|esq|estate|eurovision|eus|events|everbank|' +
180     'exchange|expert|exposed|express|fage|fail|faith|family|fan|fans|farm|fashion|feedback|film|' +
181     'finance|financial|firmdale|fish|fishing|fit|fitness|flights|florist|flowers|flsmidth|fly|foo|' +
182     'football|forex|forsale|forum|foundation|frl|frogans|fund|furniture|futbol|fyi|gal|gallery|game|' +
183     'garden|gbiz|gdn|gent|genting|ggee|gift|gifts|gives|giving|glass|gle|global|globo|gmail|gmo|gmx|' +
184     'gold|goldpoint|golf|goo|goog|google|gop|gov|graphics|gratis|green|gripe|group|guge|guide|' +
185     'guitars|guru|hamburg|hangout|haus|healthcare|help|here|hermes|hiphop|hitachi|hiv|hockey|' +
186     'holdings|holiday|homedepot|homes|honda|horse|host|hosting|hoteles|hotmail|house|how|hsbc|ibm|' +
187     'icbc|ice|icu|ifm|iinet|immo|immobilien|industries|infiniti|info|ing|ink|institute|insure|int|' +
188     'international|investments|ipiranga|irish|ist|istanbul|itau|iwc|java|jcb|jetzt|jewelry|jlc|jll|' +
189     'jobs|joburg|jprs|juegos|kaufen|kddi|kim|kitchen|kiwi|koeln|komatsu|krd|kred|kyoto|lacaixa|' +
190     'lancaster|land|lasalle|lat|latrobe|law|lawyer|lds|lease|leclerc|legal|lexus|lgbt|liaison|lidl|' +
191     'life|lighting|limited|limo|link|live|lixil|loan|loans|lol|london|lotte|lotto|love|ltda|lupin|' +
192     'luxe|luxury|madrid|maif|maison|man|management|mango|market|marketing|markets|marriott|mba|media|' +
193     'meet|melbourne|meme|memorial|men|menu|miami|microsoft|mil|mini|mma|mobi|moda|moe|mom|monash|' +
194     'money|montblanc|mormon|mortgage|moscow|motorcycles|mov|movie|movistar|mtn|mtpc|museum|nadex|' +
195     'nagoya|name|navy|nec|net|netbank|network|neustar|new|news|nexus|ngo|nhk|nico|ninja|nissan|nokia|' +
196     'nra|nrw|ntt|nyc|office|okinawa|omega|one|ong|onl|online|ooo|oracle|orange|org|organic|osaka|' +
197     'otsuka|ovh|page|panerai|paris|partners|parts|party|pet|pharmacy|philips|photo|photography|' +
198     'photos|physio|piaget|pics|pictet|pictures|pink|pizza|place|play|plumbing|plus|pohl|poker|porn|' +
199     'post|praxi|press|pro|prod|productions|prof|properties|property|pub|qpon|quebec|racing|realtor|' +
200     'realty|recipes|red|redstone|rehab|reise|reisen|reit|ren|rent|rentals|repair|report|republican|' +
201     'rest|restaurant|review|reviews|rich|ricoh|rio|rip|rocks|rodeo|rsvp|ruhr|run|ryukyu|saarland|' +
202     'sakura|sale|samsung|sandvik|sandvikcoromant|sanofi|sap|sarl|saxo|sca|scb|schmidt|scholarships|' +
203     'school|schule|schwarz|science|scor|scot|seat|seek|sener|services|sew|sex|sexy|shiksha|shoes|' +
204     'show|shriram|singles|site|ski|sky|skype|sncf|soccer|social|software|sohu|solar|solutions|sony|' +
205     'soy|space|spiegel|spreadbetting|srl|starhub|statoil|studio|study|style|sucks|supplies|supply|' +
206     'support|surf|surgery|suzuki|swatch|swiss|sydney|systems|taipei|tatamotors|tatar|tattoo|tax|taxi|' +
207     'team|tech|technology|tel|telefonica|temasek|tennis|thd|theater|tickets|tienda|tips|tires|tirol|' +
208     'today|tokyo|tools|top|toray|toshiba|tours|town|toyota|toys|trade|trading|training|travel|trust|' +
209     'tui|ubs|university|uno|uol|vacations|vegas|ventures|vermögensberater|vermögensberatung|' +
210     'versicherung|vet|viajes|video|villas|vin|vision|vista|vistaprint|vlaanderen|vodka|vote|voting|' +
211     'voto|voyage|wales|walter|wang|watch|webcam|website|wed|wedding|weir|whoswho|wien|wiki|' +
212     'williamhill|win|windows|wine|wme|work|works|world|wtc|wtf|xbox|xerox|xin|xperia|xxx|xyz|yachts|' +
213     'yandex|yodobashi|yoga|yokohama|youtube|zip|zone|zuerich|дети|ком|москва|онлайн|орг|рус|сайт|קום|' +
214     'بازار|شبكة|كوم|موقع|कॉम|नेट|संगठन|คอม|みんな|グーグル|コム|世界|中信|中文网|企业|佛山|信息|健康|八卦|公司|公益|商城|商店|商标|在线|大拿|' +
215     '娱乐|工行|广东|慈善|我爱你|手机|政务|政府|新闻|时尚|机构|淡马锡|游戏|点看|移动|组织机构|网址|网店|网络|谷歌|集团|飞利浦|餐厅|닷넷|닷컴|삼성|onion' +
216     ')(?=[^0-9a-zA-Z@]|$))'));
217   twttr.txt.regexen.validCCTLD = regexSupplant(RegExp(
218     '(?:(?:' +
219     'ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bl|bm|bn|bo|bq|' +
220     'br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cu|cv|cw|cx|cy|cz|de|dj|dk|dm|do|dz|' +
221     'ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|' +
222     'gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|' +
223     'la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mf|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|' +
224     'my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|' +
225     'rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|' +
226     'tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|za|zm|zw|ελ|' +
227     'бел|мкд|мон|рф|срб|укр|қаз|հայ|الاردن|الجزائر|السعودية|المغرب|امارات|ایران|بھارت|تونس|سودان|' +
228     'سورية|عراق|عمان|فلسطين|قطر|مصر|مليسيا|پاکستان|भारत|বাংলা|ভারত|ਭਾਰਤ|ભારત|இந்தியா|இலங்கை|' +
229     'சிங்கப்பூர்|భారత్|ලංකා|ไทย|გე|中国|中國|台湾|台灣|新加坡|澳門|香港|한국' +
230     ')(?=[^0-9a-zA-Z@]|$))'));
231   twttr.txt.regexen.validPunycode = regexSupplant(/(?:xn--[0-9a-z]+)/);
232   twttr.txt.regexen.validSpecialCCTLD = regexSupplant(RegExp(
233     '(?:(?:co|tv)(?=[^0-9a-zA-Z@]|$))'));
234   twttr.txt.regexen.validDomain = regexSupplant(/(?:#{validSubdomain}*#{validDomainName}(?:#{validGTLD}|#{validCCTLD}|#{validPunycode}))/);
235   twttr.txt.regexen.validAsciiDomain = regexSupplant(/(?:(?:[\-a-z0-9#{latinAccentChars}]+)\.)+(?:#{validGTLD}|#{validCCTLD}|#{validPunycode})/gi);
236   twttr.txt.regexen.invalidShortDomain = regexSupplant(/^#{validDomainName}#{validCCTLD}$/i);
237   twttr.txt.regexen.validSpecialShortDomain = regexSupplant(/^#{validDomainName}#{validSpecialCCTLD}$/i);
238
239   twttr.txt.regexen.validPortNumber = regexSupplant(/[0-9]+/);
240
241   twttr.txt.regexen.cyrillicLettersAndMarks = regexSupplant("\u0400-\u04FF");
242   twttr.txt.regexen.validGeneralUrlPathChars = regexSupplant(/[a-z#{cyrillicLettersAndMarks}0-9!\*';:=\+,\.\$\/%#\[\]\-_~@\|&#{latinAccentChars}]/i);
243   // Allow URL paths to contain up to two nested levels of balanced parens
244   //  1. Used in Wikipedia URLs like /Primer_(film)
245   //  2. Used in IIS sessions like /S(dfd346)/
246   //  3. Used in Rdio URLs like /track/We_Up_(Album_Version_(Edited))/
247   twttr.txt.regexen.validUrlBalancedParens = regexSupplant(
248     '\\('                                   +
249       '(?:'                                 +
250         '#{validGeneralUrlPathChars}+'      +
251         '|'                                 +
252         // allow one nested level of balanced parentheses
253         '(?:'                               +
254           '#{validGeneralUrlPathChars}*'    +
255           '\\('                             +
256             '#{validGeneralUrlPathChars}+'  +
257           '\\)'                             +
258           '#{validGeneralUrlPathChars}*'    +
259         ')'                                 +
260       ')'                                   +
261     '\\)'
262   , 'i');
263   // Valid end-of-path chracters (so /foo. does not gobble the period).
264   // 1. Allow =&# for empty URL parameters and other URL-join artifacts
265   twttr.txt.regexen.validUrlPathEndingChars = regexSupplant(/[\+\-a-z#{cyrillicLettersAndMarks}0-9=_#\/#{latinAccentChars}]|(?:#{validUrlBalancedParens})/i);
266   // Allow @ in a url, but only in the middle. Catch things like http://example.com/@user/
267   twttr.txt.regexen.validUrlPath = regexSupplant('(?:' +
268     '(?:' +
269       '#{validGeneralUrlPathChars}*' +
270         '(?:#{validUrlBalancedParens}#{validGeneralUrlPathChars}*)*' +
271         '#{validUrlPathEndingChars}'+
272       ')|(?:@#{validGeneralUrlPathChars}+\/)'+
273     ')', 'i');
274
275   twttr.txt.regexen.validUrlQueryChars = /[a-z0-9!?\*'@\(\);:&=\+\$\/%#\[\]\-_\.,~|]/i;
276   twttr.txt.regexen.validUrlQueryEndingChars = /[a-z0-9_&=#\/]/i;
277   twttr.txt.regexen.extractUrl = regexSupplant(
278     '('                                                            + // $1 total match
279       '(#{validUrlPrecedingChars})'                                + // $2 Preceeding chracter
280       '('                                                          + // $3 URL
281         '(https?:\\/\\/)?'                                         + // $4 Protocol (optional)
282         '(#{validDomain})'                                         + // $5 Domain(s)
283         '(?::(#{validPortNumber}))?'                               + // $6 Port number (optional)
284         '(\\/#{validUrlPath}*)?'                                   + // $7 URL Path
285         '(\\?#{validUrlQueryChars}*#{validUrlQueryEndingChars})?'  + // $8 Query String
286       ')'                                                          +
287     ')'
288   , 'gi');
289
290   twttr.txt.regexen.validTcoUrl = /^https?:\/\/t\.co\/[a-z0-9]+/i;
291   twttr.txt.regexen.urlHasProtocol = /^https?:\/\//i;
292   twttr.txt.regexen.urlHasHttps = /^https:\/\//i;
293
294   // cashtag related regex
295   twttr.txt.regexen.cashtag = /[a-z]{1,6}(?:[._][a-z]{1,2})?/i;
296   twttr.txt.regexen.validCashtag = regexSupplant('(^|#{spaces})(\\$)(#{cashtag})(?=$|\\s|[#{punct}])', 'gi');
297
298   // These URL validation pattern strings are based on the ABNF from RFC 3986
299   twttr.txt.regexen.validateUrlUnreserved = /[a-z\u0400-\u04FF0-9\-._~]/i;
300   twttr.txt.regexen.validateUrlPctEncoded = /(?:%[0-9a-f]{2})/i;
301   twttr.txt.regexen.validateUrlSubDelims = /[!$&'()*+,;=]/i;
302   twttr.txt.regexen.validateUrlPchar = regexSupplant('(?:' +
303     '#{validateUrlUnreserved}|' +
304     '#{validateUrlPctEncoded}|' +
305     '#{validateUrlSubDelims}|' +
306     '[:|@]' +
307   ')', 'i');
308
309   twttr.txt.regexen.validateUrlScheme = /(?:[a-z][a-z0-9+\-.]*)/i;
310   twttr.txt.regexen.validateUrlUserinfo = regexSupplant('(?:' +
311     '#{validateUrlUnreserved}|' +
312     '#{validateUrlPctEncoded}|' +
313     '#{validateUrlSubDelims}|' +
314     ':' +
315   ')*', 'i');
316
317   twttr.txt.regexen.validateUrlDecOctet = /(?:[0-9]|(?:[1-9][0-9])|(?:1[0-9]{2})|(?:2[0-4][0-9])|(?:25[0-5]))/i;
318   twttr.txt.regexen.validateUrlIpv4 = regexSupplant(/(?:#{validateUrlDecOctet}(?:\.#{validateUrlDecOctet}){3})/i);
319
320   // Punting on real IPv6 validation for now
321   twttr.txt.regexen.validateUrlIpv6 = /(?:\[[a-f0-9:\.]+\])/i;
322
323   // Also punting on IPvFuture for now
324   twttr.txt.regexen.validateUrlIp = regexSupplant('(?:' +
325     '#{validateUrlIpv4}|' +
326     '#{validateUrlIpv6}' +
327   ')', 'i');
328
329   // This is more strict than the rfc specifies
330   twttr.txt.regexen.validateUrlSubDomainSegment = /(?:[a-z0-9](?:[a-z0-9_\-]*[a-z0-9])?)/i;
331   twttr.txt.regexen.validateUrlDomainSegment = /(?:[a-z0-9](?:[a-z0-9\-]*[a-z0-9])?)/i;
332   twttr.txt.regexen.validateUrlDomainTld = /(?:[a-z](?:[a-z0-9\-]*[a-z0-9])?)/i;
333   twttr.txt.regexen.validateUrlDomain = regexSupplant(/(?:(?:#{validateUrlSubDomainSegment]}\.)*(?:#{validateUrlDomainSegment]}\.)#{validateUrlDomainTld})/i);
334
335   twttr.txt.regexen.validateUrlHost = regexSupplant('(?:' +
336     '#{validateUrlIp}|' +
337     '#{validateUrlDomain}' +
338   ')', 'i');
339
340   // Unencoded internationalized domains - this doesn't check for invalid UTF-8 sequences
341   twttr.txt.regexen.validateUrlUnicodeSubDomainSegment = /(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9_\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i;
342   twttr.txt.regexen.validateUrlUnicodeDomainSegment = /(?:(?:[a-z0-9]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i;
343   twttr.txt.regexen.validateUrlUnicodeDomainTld = /(?:(?:[a-z]|[^\u0000-\u007f])(?:(?:[a-z0-9\-]|[^\u0000-\u007f])*(?:[a-z0-9]|[^\u0000-\u007f]))?)/i;
344   twttr.txt.regexen.validateUrlUnicodeDomain = regexSupplant(/(?:(?:#{validateUrlUnicodeSubDomainSegment}\.)*(?:#{validateUrlUnicodeDomainSegment}\.)#{validateUrlUnicodeDomainTld})/i);
345
346   twttr.txt.regexen.validateUrlUnicodeHost = regexSupplant('(?:' +
347     '#{validateUrlIp}|' +
348     '#{validateUrlUnicodeDomain}' +
349   ')', 'i');
350
351   twttr.txt.regexen.validateUrlPort = /[0-9]{1,5}/;
352
353   twttr.txt.regexen.validateUrlUnicodeAuthority = regexSupplant(
354     '(?:(#{validateUrlUserinfo})@)?'  + // $1 userinfo
355     '(#{validateUrlUnicodeHost})'     + // $2 host
356     '(?::(#{validateUrlPort}))?'        //$3 port
357   , "i");
358
359   twttr.txt.regexen.validateUrlAuthority = regexSupplant(
360     '(?:(#{validateUrlUserinfo})@)?' + // $1 userinfo
361     '(#{validateUrlHost})'           + // $2 host
362     '(?::(#{validateUrlPort}))?'       // $3 port
363   , "i");
364
365   twttr.txt.regexen.validateUrlPath = regexSupplant(/(\/#{validateUrlPchar}*)*/i);
366   twttr.txt.regexen.validateUrlQuery = regexSupplant(/(#{validateUrlPchar}|\/|\?)*/i);
367   twttr.txt.regexen.validateUrlFragment = regexSupplant(/(#{validateUrlPchar}|\/|\?)*/i);
368
369   // Modified version of RFC 3986 Appendix B
370   twttr.txt.regexen.validateUrlUnencoded = regexSupplant(
371     '^'                               + // Full URL
372     '(?:'                             +
373       '([^:/?#]+):\\/\\/'             + // $1 Scheme
374     ')?'                              +
375     '([^/?#]*)'                       + // $2 Authority
376     '([^?#]*)'                        + // $3 Path
377     '(?:'                             +
378       '\\?([^#]*)'                    + // $4 Query
379     ')?'                              +
380     '(?:'                             +
381       '#(.*)'                         + // $5 Fragment
382     ')?$'
383   , "i");
384
385
386   // Default CSS class for auto-linked lists (along with the url class)
387   var DEFAULT_LIST_CLASS = "tweet-url list-slug";
388   // Default CSS class for auto-linked usernames (along with the url class)
389   var DEFAULT_USERNAME_CLASS = "tweet-url username";
390   // Default CSS class for auto-linked hashtags (along with the url class)
391   var DEFAULT_HASHTAG_CLASS = "tweet-url hashtag";
392   // Default CSS class for auto-linked cashtags (along with the url class)
393   var DEFAULT_CASHTAG_CLASS = "tweet-url cashtag";
394   // Options which should not be passed as HTML attributes
395   var OPTIONS_NOT_ATTRIBUTES = {'urlClass':true, 'listClass':true, 'usernameClass':true, 'hashtagClass':true, 'cashtagClass':true,
396                             'usernameUrlBase':true, 'listUrlBase':true, 'hashtagUrlBase':true, 'cashtagUrlBase':true,
397                             'usernameUrlBlock':true, 'listUrlBlock':true, 'hashtagUrlBlock':true, 'linkUrlBlock':true,
398                             'usernameIncludeSymbol':true, 'suppressLists':true, 'suppressNoFollow':true, 'targetBlank':true,
399                             'suppressDataScreenName':true, 'urlEntities':true, 'symbolTag':true, 'textWithSymbolTag':true, 'urlTarget':true,
400                             'invisibleTagAttrs':true, 'linkAttributeBlock':true, 'linkTextBlock': true, 'htmlEscapeNonEntities': true
401                             };
402
403   var BOOLEAN_ATTRIBUTES = {'disabled':true, 'readonly':true, 'multiple':true, 'checked':true};
404
405   // Simple object cloning function for simple objects
406   function clone(o) {
407     var r = {};
408     for (var k in o) {
409       if (o.hasOwnProperty(k)) {
410         r[k] = o[k];
411       }
412     }
413
414     return r;
415   }
416
417   twttr.txt.tagAttrs = function(attributes) {
418     var htmlAttrs = "";
419     for (var k in attributes) {
420       var v = attributes[k];
421       if (BOOLEAN_ATTRIBUTES[k]) {
422         v = v ? k : null;
423       }
424       if (v == null) continue;
425       htmlAttrs += " " + twttr.txt.htmlEscape(k) + "=\"" + twttr.txt.htmlEscape(v.toString()) + "\"";
426     }
427     return htmlAttrs;
428   };
429
430   twttr.txt.linkToText = function(entity, text, attributes, options) {
431     if (!options.suppressNoFollow) {
432       attributes.rel = "nofollow";
433     }
434     // if linkAttributeBlock is specified, call it to modify the attributes
435     if (options.linkAttributeBlock) {
436       options.linkAttributeBlock(entity, attributes);
437     }
438     // if linkTextBlock is specified, call it to get a new/modified link text
439     if (options.linkTextBlock) {
440       text = options.linkTextBlock(entity, text);
441     }
442     var d = {
443       text: text,
444       attr: twttr.txt.tagAttrs(attributes)
445     };
446     return stringSupplant("<a#{attr}>#{text}</a>", d);
447   };
448
449   twttr.txt.linkToTextWithSymbol = function(entity, symbol, text, attributes, options) {
450     var taggedSymbol = options.symbolTag ? "<" + options.symbolTag + ">" + symbol + "</"+ options.symbolTag + ">" : symbol;
451     text = twttr.txt.htmlEscape(text);
452     var taggedText = options.textWithSymbolTag ? "<" + options.textWithSymbolTag + ">" + text + "</"+ options.textWithSymbolTag + ">" : text;
453
454     if (options.usernameIncludeSymbol || !symbol.match(twttr.txt.regexen.atSigns)) {
455       return twttr.txt.linkToText(entity, taggedSymbol + taggedText, attributes, options);
456     } else {
457       return taggedSymbol + twttr.txt.linkToText(entity, taggedText, attributes, options);
458     }
459   };
460
461   twttr.txt.linkToHashtag = function(entity, text, options) {
462     var hash = text.substring(entity.indices[0], entity.indices[0] + 1);
463     var hashtag = twttr.txt.htmlEscape(entity.hashtag);
464     var attrs = clone(options.htmlAttrs || {});
465     attrs.href = options.hashtagUrlBase + hashtag;
466     attrs.title = "#" + hashtag;
467     attrs["class"] = options.hashtagClass;
468     if (hashtag.charAt(0).match(twttr.txt.regexen.rtl_chars)){
469       attrs["class"] += " rtl";
470     }
471     if (options.targetBlank) {
472       attrs.target = '_blank';
473     }
474
475     return twttr.txt.linkToTextWithSymbol(entity, hash, hashtag, attrs, options);
476   };
477
478   twttr.txt.linkToCashtag = function(entity, text, options) {
479     var cashtag = twttr.txt.htmlEscape(entity.cashtag);
480     var attrs = clone(options.htmlAttrs || {});
481     attrs.href = options.cashtagUrlBase + cashtag;
482     attrs.title = "$" + cashtag;
483     attrs["class"] =  options.cashtagClass;
484     if (options.targetBlank) {
485       attrs.target = '_blank';
486     }
487
488     return twttr.txt.linkToTextWithSymbol(entity, "$", cashtag, attrs, options);
489   };
490
491   twttr.txt.linkToMentionAndList = function(entity, text, options) {
492     var at = text.substring(entity.indices[0], entity.indices[0] + 1);
493     var user = twttr.txt.htmlEscape(entity.screenName);
494     var slashListname = twttr.txt.htmlEscape(entity.listSlug);
495     var isList = entity.listSlug && !options.suppressLists;
496     var attrs = clone(options.htmlAttrs || {});
497     attrs["class"] = (isList ? options.listClass : options.usernameClass);
498     attrs.href = isList ? options.listUrlBase + user + slashListname : options.usernameUrlBase + user;
499     if (!isList && !options.suppressDataScreenName) {
500       attrs['data-screen-name'] = user;
501     }
502     if (options.targetBlank) {
503       attrs.target = '_blank';
504     }
505
506     return twttr.txt.linkToTextWithSymbol(entity, at, isList ? user + slashListname : user, attrs, options);
507   };
508
509   twttr.txt.linkToUrl = function(entity, text, options) {
510     var url = entity.url;
511     var displayUrl = url;
512     var linkText = twttr.txt.htmlEscape(displayUrl);
513
514     // If the caller passed a urlEntities object (provided by a Twitter API
515     // response with include_entities=true), we use that to render the display_url
516     // for each URL instead of it's underlying t.co URL.
517     var urlEntity = (options.urlEntities && options.urlEntities[url]) || entity;
518     if (urlEntity.display_url) {
519       linkText = twttr.txt.linkTextWithEntity(urlEntity, options);
520     }
521
522     var attrs = clone(options.htmlAttrs || {});
523
524     if (!url.match(twttr.txt.regexen.urlHasProtocol)) {
525       url = "http://" + url;
526     }
527     attrs.href = url;
528
529     if (options.targetBlank) {
530       attrs.target = '_blank';
531     }
532
533     // set class only if urlClass is specified.
534     if (options.urlClass) {
535       attrs["class"] = options.urlClass;
536     }
537
538     // set target only if urlTarget is specified.
539     if (options.urlTarget) {
540       attrs.target = options.urlTarget;
541     }
542
543     if (!options.title && urlEntity.display_url) {
544       attrs.title = urlEntity.expanded_url;
545     }
546
547     return twttr.txt.linkToText(entity, linkText, attrs, options);
548   };
549
550   twttr.txt.linkTextWithEntity = function (entity, options) {
551     var displayUrl = entity.display_url;
552     var expandedUrl = entity.expanded_url;
553
554     // Goal: If a user copies and pastes a tweet containing t.co'ed link, the resulting paste
555     // should contain the full original URL (expanded_url), not the display URL.
556     //
557     // Method: Whenever possible, we actually emit HTML that contains expanded_url, and use
558     // font-size:0 to hide those parts that should not be displayed (because they are not part of display_url).
559     // Elements with font-size:0 get copied even though they are not visible.
560     // Note that display:none doesn't work here. Elements with display:none don't get copied.
561     //
562     // Additionally, we want to *display* ellipses, but we don't want them copied.  To make this happen we
563     // wrap the ellipses in a tco-ellipsis class and provide an onCopy handler that sets display:none on
564     // everything with the tco-ellipsis class.
565     //
566     // Exception: pic.twitter.com images, for which expandedUrl = "https://twitter.com/#!/username/status/1234/photo/1
567     // For those URLs, display_url is not a substring of expanded_url, so we don't do anything special to render the elided parts.
568     // For a pic.twitter.com URL, the only elided part will be the "https://", so this is fine.
569
570     var displayUrlSansEllipses = displayUrl.replace(/…/g, ""); // We have to disregard ellipses for matching
571     // Note: we currently only support eliding parts of the URL at the beginning or the end.
572     // Eventually we may want to elide parts of the URL in the *middle*.  If so, this code will
573     // become more complicated.  We will probably want to create a regexp out of display URL,
574     // replacing every ellipsis with a ".*".
575     if (expandedUrl.indexOf(displayUrlSansEllipses) != -1) {
576       var displayUrlIndex = expandedUrl.indexOf(displayUrlSansEllipses);
577       var v = {
578         displayUrlSansEllipses: displayUrlSansEllipses,
579         // Portion of expandedUrl that precedes the displayUrl substring
580         beforeDisplayUrl: expandedUrl.substr(0, displayUrlIndex),
581         // Portion of expandedUrl that comes after displayUrl
582         afterDisplayUrl: expandedUrl.substr(displayUrlIndex + displayUrlSansEllipses.length),
583         precedingEllipsis: displayUrl.match(/^…/) ? "…" : "",
584         followingEllipsis: displayUrl.match(/…$/) ? "…" : ""
585       };
586       for (var k in v) {
587         if (v.hasOwnProperty(k)) {
588           v[k] = twttr.txt.htmlEscape(v[k]);
589         }
590       }
591       // As an example: The user tweets "hi http://longdomainname.com/foo"
592       // This gets shortened to "hi http://t.co/xyzabc", with display_url = "…nname.com/foo"
593       // This will get rendered as:
594       // <span class='tco-ellipsis'> <!-- This stuff should get displayed but not copied -->
595       //   …
596       //   <!-- There's a chance the onCopy event handler might not fire. In case that happens,
597       //        we include an &nbsp; here so that the … doesn't bump up against the URL and ruin it.
598       //        The &nbsp; is inside the tco-ellipsis span so that when the onCopy handler *does*
599       //        fire, it doesn't get copied.  Otherwise the copied text would have two spaces in a row,
600       //        e.g. "hi  http://longdomainname.com/foo".
601       //   <span style='font-size:0'>&nbsp;</span>
602       // </span>
603       // <span style='font-size:0'>  <!-- This stuff should get copied but not displayed -->
604       //   http://longdomai
605       // </span>
606       // <span class='js-display-url'> <!-- This stuff should get displayed *and* copied -->
607       //   nname.com/foo
608       // </span>
609       // <span class='tco-ellipsis'> <!-- This stuff should get displayed but not copied -->
610       //   <span style='font-size:0'>&nbsp;</span>
611       //   …
612       // </span>
613       v['invisible'] = options.invisibleTagAttrs;
614       return stringSupplant("<span class='tco-ellipsis'>#{precedingEllipsis}<span #{invisible}>&nbsp;</span></span><span #{invisible}>#{beforeDisplayUrl}</span><span class='js-display-url'>#{displayUrlSansEllipses}</span><span #{invisible}>#{afterDisplayUrl}</span><span class='tco-ellipsis'><span #{invisible}>&nbsp;</span>#{followingEllipsis}</span>", v);
615     }
616     return displayUrl;
617   };
618
619   twttr.txt.autoLinkEntities = function(text, entities, options) {
620     options = clone(options || {});
621
622     options.hashtagClass = options.hashtagClass || DEFAULT_HASHTAG_CLASS;
623     options.hashtagUrlBase = options.hashtagUrlBase || "https://twitter.com/#!/search?q=%23";
624     options.cashtagClass = options.cashtagClass || DEFAULT_CASHTAG_CLASS;
625     options.cashtagUrlBase = options.cashtagUrlBase || "https://twitter.com/#!/search?q=%24";
626     options.listClass = options.listClass || DEFAULT_LIST_CLASS;
627     options.usernameClass = options.usernameClass || DEFAULT_USERNAME_CLASS;
628     options.usernameUrlBase = options.usernameUrlBase || "https://twitter.com/";
629     options.listUrlBase = options.listUrlBase || "https://twitter.com/";
630     options.htmlAttrs = twttr.txt.extractHtmlAttrsFromOptions(options);
631     options.invisibleTagAttrs = options.invisibleTagAttrs || "style='position:absolute;left:-9999px;'";
632
633     // remap url entities to hash
634     var urlEntities, i, len;
635     if(options.urlEntities) {
636       urlEntities = {};
637       for(i = 0, len = options.urlEntities.length; i < len; i++) {
638         urlEntities[options.urlEntities[i].url] = options.urlEntities[i];
639       }
640       options.urlEntities = urlEntities;
641     }
642
643     var result = "";
644     var beginIndex = 0;
645
646     // sort entities by start index
647     entities.sort(function(a,b){ return a.indices[0] - b.indices[0]; });
648
649     var nonEntity = options.htmlEscapeNonEntities ? twttr.txt.htmlEscape : function(text) {
650       return text;
651     };
652
653     for (var i = 0; i < entities.length; i++) {
654       var entity = entities[i];
655       result += nonEntity(text.substring(beginIndex, entity.indices[0]));
656
657       if (entity.url) {
658         result += twttr.txt.linkToUrl(entity, text, options);
659       } else if (entity.hashtag) {
660         result += twttr.txt.linkToHashtag(entity, text, options);
661       } else if (entity.screenName) {
662         result += twttr.txt.linkToMentionAndList(entity, text, options);
663       } else if (entity.cashtag) {
664         result += twttr.txt.linkToCashtag(entity, text, options);
665       }
666       beginIndex = entity.indices[1];
667     }
668     result += nonEntity(text.substring(beginIndex, text.length));
669     return result;
670   };
671
672   twttr.txt.autoLinkWithJSON = function(text, json, options) {
673     // map JSON entity to twitter-text entity
674     if (json.user_mentions) {
675       for (var i = 0; i < json.user_mentions.length; i++) {
676         // this is a @mention
677         json.user_mentions[i].screenName = json.user_mentions[i].screen_name;
678       }
679     }
680
681     if (json.hashtags) {
682       for (var i = 0; i < json.hashtags.length; i++) {
683         // this is a #hashtag
684         json.hashtags[i].hashtag = json.hashtags[i].text;
685       }
686     }
687
688     if (json.symbols) {
689       for (var i = 0; i < json.symbols.length; i++) {
690         // this is a $CASH tag
691         json.symbols[i].cashtag = json.symbols[i].text;
692       }
693     }
694
695     // concatenate all entities
696     var entities = [];
697     for (var key in json) {
698       entities = entities.concat(json[key]);
699     }
700
701     // modify indices to UTF-16
702     twttr.txt.modifyIndicesFromUnicodeToUTF16(text, entities);
703
704     return twttr.txt.autoLinkEntities(text, entities, options);
705   };
706
707   twttr.txt.extractHtmlAttrsFromOptions = function(options) {
708     var htmlAttrs = {};
709     for (var k in options) {
710       var v = options[k];
711       if (OPTIONS_NOT_ATTRIBUTES[k]) continue;
712       if (BOOLEAN_ATTRIBUTES[k]) {
713         v = v ? k : null;
714       }
715       if (v == null) continue;
716       htmlAttrs[k] = v;
717     }
718     return htmlAttrs;
719   };
720
721   twttr.txt.autoLink = function(text, options) {
722     var entities = twttr.txt.extractEntitiesWithIndices(text, {extractUrlsWithoutProtocol: false});
723     return twttr.txt.autoLinkEntities(text, entities, options);
724   };
725
726   twttr.txt.autoLinkUsernamesOrLists = function(text, options) {
727     var entities = twttr.txt.extractMentionsOrListsWithIndices(text);
728     return twttr.txt.autoLinkEntities(text, entities, options);
729   };
730
731   twttr.txt.autoLinkHashtags = function(text, options) {
732     var entities = twttr.txt.extractHashtagsWithIndices(text);
733     return twttr.txt.autoLinkEntities(text, entities, options);
734   };
735
736   twttr.txt.autoLinkCashtags = function(text, options) {
737     var entities = twttr.txt.extractCashtagsWithIndices(text);
738     return twttr.txt.autoLinkEntities(text, entities, options);
739   };
740
741   twttr.txt.autoLinkUrlsCustom = function(text, options) {
742     var entities = twttr.txt.extractUrlsWithIndices(text, {extractUrlsWithoutProtocol: false});
743     return twttr.txt.autoLinkEntities(text, entities, options);
744   };
745
746   twttr.txt.removeOverlappingEntities = function(entities) {
747     entities.sort(function(a,b){ return a.indices[0] - b.indices[0]; });
748
749     var prev = entities[0];
750     for (var i = 1; i < entities.length; i++) {
751       if (prev.indices[1] > entities[i].indices[0]) {
752         entities.splice(i, 1);
753         i--;
754       } else {
755         prev = entities[i];
756       }
757     }
758   };
759
760   twttr.txt.extractEntitiesWithIndices = function(text, options) {
761     var entities = twttr.txt.extractUrlsWithIndices(text, options)
762                     .concat(twttr.txt.extractMentionsOrListsWithIndices(text))
763                     .concat(twttr.txt.extractHashtagsWithIndices(text, {checkUrlOverlap: false}))
764                     .concat(twttr.txt.extractCashtagsWithIndices(text));
765
766     if (entities.length == 0) {
767       return [];
768     }
769
770     twttr.txt.removeOverlappingEntities(entities);
771     return entities;
772   };
773
774   twttr.txt.extractMentions = function(text) {
775     var screenNamesOnly = [],
776         screenNamesWithIndices = twttr.txt.extractMentionsWithIndices(text);
777
778     for (var i = 0; i < screenNamesWithIndices.length; i++) {
779       var screenName = screenNamesWithIndices[i].screenName;
780       screenNamesOnly.push(screenName);
781     }
782
783     return screenNamesOnly;
784   };
785
786   twttr.txt.extractMentionsWithIndices = function(text) {
787     var mentions = [],
788         mentionOrList,
789         mentionsOrLists = twttr.txt.extractMentionsOrListsWithIndices(text);
790
791     for (var i = 0 ; i < mentionsOrLists.length; i++) {
792       mentionOrList = mentionsOrLists[i];
793       if (mentionOrList.listSlug == '') {
794         mentions.push({
795           screenName: mentionOrList.screenName,
796           indices: mentionOrList.indices
797         });
798       }
799     }
800
801     return mentions;
802   };
803
804   /**
805    * Extract list or user mentions.
806    * (Presence of listSlug indicates a list)
807    */
808   twttr.txt.extractMentionsOrListsWithIndices = function(text) {
809     if (!text || !text.match(twttr.txt.regexen.atSigns)) {
810       return [];
811     }
812
813     var possibleNames = [],
814         slashListname;
815
816     text.replace(twttr.txt.regexen.validMentionOrList, function(match, before, atSign, screenName, slashListname, offset, chunk) {
817       var after = chunk.slice(offset + match.length);
818       if (!after.match(twttr.txt.regexen.endMentionMatch)) {
819         slashListname = slashListname || '';
820         var startPosition = offset + before.length;
821         var endPosition = startPosition + screenName.length + slashListname.length + 1;
822         possibleNames.push({
823           screenName: screenName,
824           listSlug: slashListname,
825           indices: [startPosition, endPosition]
826         });
827       }
828     });
829
830     return possibleNames;
831   };
832
833
834   twttr.txt.extractReplies = function(text) {
835     if (!text) {
836       return null;
837     }
838
839     var possibleScreenName = text.match(twttr.txt.regexen.validReply);
840     if (!possibleScreenName ||
841         RegExp.rightContext.match(twttr.txt.regexen.endMentionMatch)) {
842       return null;
843     }
844
845     return possibleScreenName[1];
846   };
847
848   twttr.txt.extractUrls = function(text, options) {
849     var urlsOnly = [],
850         urlsWithIndices = twttr.txt.extractUrlsWithIndices(text, options);
851
852     for (var i = 0; i < urlsWithIndices.length; i++) {
853       urlsOnly.push(urlsWithIndices[i].url);
854     }
855
856     return urlsOnly;
857   };
858
859   twttr.txt.extractUrlsWithIndices = function(text, options) {
860     if (!options) {
861       options = {extractUrlsWithoutProtocol: true};
862     }
863     if (!text || (options.extractUrlsWithoutProtocol ? !text.match(/\./) : !text.match(/:/))) {
864       return [];
865     }
866
867     var urls = [];
868
869     while (twttr.txt.regexen.extractUrl.exec(text)) {
870       var before = RegExp.$2, url = RegExp.$3, protocol = RegExp.$4, domain = RegExp.$5, path = RegExp.$7;
871       var endPosition = twttr.txt.regexen.extractUrl.lastIndex,
872           startPosition = endPosition - url.length;
873
874       // if protocol is missing and domain contains non-ASCII characters,
875       // extract ASCII-only domains.
876       if (!protocol) {
877         if (!options.extractUrlsWithoutProtocol
878             || before.match(twttr.txt.regexen.invalidUrlWithoutProtocolPrecedingChars)) {
879           continue;
880         }
881         var lastUrl = null,
882             asciiEndPosition = 0;
883         domain.replace(twttr.txt.regexen.validAsciiDomain, function(asciiDomain) {
884           var asciiStartPosition = domain.indexOf(asciiDomain, asciiEndPosition);
885           asciiEndPosition = asciiStartPosition + asciiDomain.length;
886           lastUrl = {
887             url: asciiDomain,
888             indices: [startPosition + asciiStartPosition, startPosition + asciiEndPosition]
889           };
890           if (path
891               || asciiDomain.match(twttr.txt.regexen.validSpecialShortDomain)
892               || !asciiDomain.match(twttr.txt.regexen.invalidShortDomain)) {
893             urls.push(lastUrl);
894           }
895         });
896
897         // no ASCII-only domain found. Skip the entire URL.
898         if (lastUrl == null) {
899           continue;
900         }
901
902         // lastUrl only contains domain. Need to add path and query if they exist.
903         if (path) {
904           lastUrl.url = url.replace(domain, lastUrl.url);
905           lastUrl.indices[1] = endPosition;
906         }
907       } else {
908         // In the case of t.co URLs, don't allow additional path characters.
909         if (url.match(twttr.txt.regexen.validTcoUrl)) {
910           url = RegExp.lastMatch;
911           endPosition = startPosition + url.length;
912         }
913         urls.push({
914           url: url,
915           indices: [startPosition, endPosition]
916         });
917       }
918     }
919
920     return urls;
921   };
922
923   twttr.txt.extractHashtags = function(text) {
924     var hashtagsOnly = [],
925         hashtagsWithIndices = twttr.txt.extractHashtagsWithIndices(text);
926
927     for (var i = 0; i < hashtagsWithIndices.length; i++) {
928       hashtagsOnly.push(hashtagsWithIndices[i].hashtag);
929     }
930
931     return hashtagsOnly;
932   };
933
934   twttr.txt.extractHashtagsWithIndices = function(text, options) {
935     if (!options) {
936       options = {checkUrlOverlap: true};
937     }
938
939     if (!text || !text.match(twttr.txt.regexen.hashSigns)) {
940       return [];
941     }
942
943     var tags = [];
944
945     text.replace(twttr.txt.regexen.validHashtag, function(match, before, hash, hashText, offset, chunk) {
946       var after = chunk.slice(offset + match.length);
947       if (after.match(twttr.txt.regexen.endHashtagMatch))
948         return;
949       var startPosition = offset + before.length;
950       var endPosition = startPosition + hashText.length + 1;
951       tags.push({
952         hashtag: hashText,
953         indices: [startPosition, endPosition]
954       });
955     });
956
957     if (options.checkUrlOverlap) {
958       // also extract URL entities
959       var urls = twttr.txt.extractUrlsWithIndices(text);
960       if (urls.length > 0) {
961         var entities = tags.concat(urls);
962         // remove overlap
963         twttr.txt.removeOverlappingEntities(entities);
964         // only push back hashtags
965         tags = [];
966         for (var i = 0; i < entities.length; i++) {
967           if (entities[i].hashtag) {
968             tags.push(entities[i]);
969           }
970         }
971       }
972     }
973
974     return tags;
975   };
976
977   twttr.txt.extractCashtags = function(text) {
978     var cashtagsOnly = [],
979         cashtagsWithIndices = twttr.txt.extractCashtagsWithIndices(text);
980
981     for (var i = 0; i < cashtagsWithIndices.length; i++) {
982       cashtagsOnly.push(cashtagsWithIndices[i].cashtag);
983     }
984
985     return cashtagsOnly;
986   };
987
988   twttr.txt.extractCashtagsWithIndices = function(text) {
989     if (!text || text.indexOf("$") == -1) {
990       return [];
991     }
992
993     var tags = [];
994
995     text.replace(twttr.txt.regexen.validCashtag, function(match, before, dollar, cashtag, offset, chunk) {
996       var startPosition = offset + before.length;
997       var endPosition = startPosition + cashtag.length + 1;
998       tags.push({
999         cashtag: cashtag,
1000         indices: [startPosition, endPosition]
1001       });
1002     });
1003
1004     return tags;
1005   };
1006
1007   twttr.txt.modifyIndicesFromUnicodeToUTF16 = function(text, entities) {
1008     twttr.txt.convertUnicodeIndices(text, entities, false);
1009   };
1010
1011   twttr.txt.modifyIndicesFromUTF16ToUnicode = function(text, entities) {
1012     twttr.txt.convertUnicodeIndices(text, entities, true);
1013   };
1014
1015   twttr.txt.getUnicodeTextLength = function(text) {
1016     return text.replace(twttr.txt.regexen.non_bmp_code_pairs, ' ').length;
1017   };
1018
1019   twttr.txt.convertUnicodeIndices = function(text, entities, indicesInUTF16) {
1020     if (entities.length == 0) {
1021       return;
1022     }
1023
1024     var charIndex = 0;
1025     var codePointIndex = 0;
1026
1027     // sort entities by start index
1028     entities.sort(function(a,b){ return a.indices[0] - b.indices[0]; });
1029     var entityIndex = 0;
1030     var entity = entities[0];
1031
1032     while (charIndex < text.length) {
1033       if (entity.indices[0] == (indicesInUTF16 ? charIndex : codePointIndex)) {
1034         var len = entity.indices[1] - entity.indices[0];
1035         entity.indices[0] = indicesInUTF16 ? codePointIndex : charIndex;
1036         entity.indices[1] = entity.indices[0] + len;
1037
1038         entityIndex++;
1039         if (entityIndex == entities.length) {
1040           // no more entity
1041           break;
1042         }
1043         entity = entities[entityIndex];
1044       }
1045
1046       var c = text.charCodeAt(charIndex);
1047       if (0xD800 <= c && c <= 0xDBFF && charIndex < text.length - 1) {
1048         // Found high surrogate char
1049         c = text.charCodeAt(charIndex + 1);
1050         if (0xDC00 <= c && c <= 0xDFFF) {
1051           // Found surrogate pair
1052           charIndex++;
1053         }
1054       }
1055       codePointIndex++;
1056       charIndex++;
1057     }
1058   };
1059
1060   // this essentially does text.split(/<|>/)
1061   // except that won't work in IE, where empty strings are ommitted
1062   // so "<>".split(/<|>/) => [] in IE, but is ["", "", ""] in all others
1063   // but "<<".split("<") => ["", "", ""]
1064   twttr.txt.splitTags = function(text) {
1065     var firstSplits = text.split("<"),
1066         secondSplits,
1067         allSplits = [],
1068         split;
1069
1070     for (var i = 0; i < firstSplits.length; i += 1) {
1071       split = firstSplits[i];
1072       if (!split) {
1073         allSplits.push("");
1074       } else {
1075         secondSplits = split.split(">");
1076         for (var j = 0; j < secondSplits.length; j += 1) {
1077           allSplits.push(secondSplits[j]);
1078         }
1079       }
1080     }
1081
1082     return allSplits;
1083   };
1084
1085   twttr.txt.hitHighlight = function(text, hits, options) {
1086     var defaultHighlightTag = "em";
1087
1088     hits = hits || [];
1089     options = options || {};
1090
1091     if (hits.length === 0) {
1092       return text;
1093     }
1094
1095     var tagName = options.tag || defaultHighlightTag,
1096         tags = ["<" + tagName + ">", "</" + tagName + ">"],
1097         chunks = twttr.txt.splitTags(text),
1098         i,
1099         j,
1100         result = "",
1101         chunkIndex = 0,
1102         chunk = chunks[0],
1103         prevChunksLen = 0,
1104         chunkCursor = 0,
1105         startInChunk = false,
1106         chunkChars = chunk,
1107         flatHits = [],
1108         index,
1109         hit,
1110         tag,
1111         placed,
1112         hitSpot;
1113
1114     for (i = 0; i < hits.length; i += 1) {
1115       for (j = 0; j < hits[i].length; j += 1) {
1116         flatHits.push(hits[i][j]);
1117       }
1118     }
1119
1120     for (index = 0; index < flatHits.length; index += 1) {
1121       hit = flatHits[index];
1122       tag = tags[index % 2];
1123       placed = false;
1124
1125       while (chunk != null && hit >= prevChunksLen + chunk.length) {
1126         result += chunkChars.slice(chunkCursor);
1127         if (startInChunk && hit === prevChunksLen + chunkChars.length) {
1128           result += tag;
1129           placed = true;
1130         }
1131
1132         if (chunks[chunkIndex + 1]) {
1133           result += "<" + chunks[chunkIndex + 1] + ">";
1134         }
1135
1136         prevChunksLen += chunkChars.length;
1137         chunkCursor = 0;
1138         chunkIndex += 2;
1139         chunk = chunks[chunkIndex];
1140         chunkChars = chunk;
1141         startInChunk = false;
1142       }
1143
1144       if (!placed && chunk != null) {
1145         hitSpot = hit - prevChunksLen;
1146         result += chunkChars.slice(chunkCursor, hitSpot) + tag;
1147         chunkCursor = hitSpot;
1148         if (index % 2 === 0) {
1149           startInChunk = true;
1150         } else {
1151           startInChunk = false;
1152         }
1153       } else if(!placed) {
1154         placed = true;
1155         result += tag;
1156       }
1157     }
1158
1159     if (chunk != null) {
1160       if (chunkCursor < chunkChars.length) {
1161         result += chunkChars.slice(chunkCursor);
1162       }
1163       for (index = chunkIndex + 1; index < chunks.length; index += 1) {
1164         result += (index % 2 === 0 ? chunks[index] : "<" + chunks[index] + ">");
1165       }
1166     }
1167
1168     return result;
1169   };
1170
1171   var MAX_LENGTH = 280;
1172
1173   // Characters not allowed in Tweets
1174   var INVALID_CHARACTERS = [
1175     // BOM
1176     fromCode(0xFFFE),
1177     fromCode(0xFEFF),
1178
1179     // Special
1180     fromCode(0xFFFF),
1181
1182     // Directional Change
1183     fromCode(0x202A),
1184     fromCode(0x202B),
1185     fromCode(0x202C),
1186     fromCode(0x202D),
1187     fromCode(0x202E)
1188   ];
1189
1190   // Returns the length of Tweet text with consideration to t.co URL replacement
1191   // and chars outside the basic multilingual plane that use 2 UTF16 code points
1192   twttr.txt.getTweetLength = function(text, options) {
1193     if (!options) {
1194       options = {
1195           // These come from https://api.twitter.com/1/help/configuration.json
1196           // described by https://dev.twitter.com/docs/api/1/get/help/configuration
1197           short_url_length: 23,
1198           short_url_length_https: 23
1199       };
1200     }
1201     var textLength = twttr.txt.getUnicodeTextLength(text),
1202         urlsWithIndices = twttr.txt.extractUrlsWithIndices(text);
1203     twttr.txt.modifyIndicesFromUTF16ToUnicode(text, urlsWithIndices);
1204
1205     for (var i = 0; i < urlsWithIndices.length; i++) {
1206       // Subtract the length of the original URL
1207       textLength += urlsWithIndices[i].indices[0] - urlsWithIndices[i].indices[1];
1208
1209       // Add 23 characters for URL starting with https://
1210       // http:// URLs still use https://t.co so they are 23 characters as well
1211       if (urlsWithIndices[i].url.toLowerCase().match(twttr.txt.regexen.urlHasHttps)) {
1212          textLength += options.short_url_length_https;
1213       } else {
1214         textLength += options.short_url_length;
1215       }
1216     }
1217
1218     return textLength;
1219   };
1220
1221   // Check the text for any reason that it may not be valid as a Tweet. This is meant as a pre-validation
1222   // before posting to api.twitter.com. There are several server-side reasons for Tweets to fail but this pre-validation
1223   // will allow quicker feedback.
1224   //
1225   // Returns false if this text is valid. Otherwise one of the following strings will be returned:
1226   //
1227   //   "too_long": if the text is too long
1228   //   "empty": if the text is nil or empty
1229   //   "invalid_characters": if the text contains non-Unicode or any of the disallowed Unicode characters
1230   twttr.txt.isInvalidTweet = function(text) {
1231     if (!text) {
1232       return "empty";
1233     }
1234
1235     // Determine max length independent of URL length
1236     if (twttr.txt.getTweetLength(text) > MAX_LENGTH) {
1237       return "too_long";
1238     }
1239
1240     if (twttr.txt.hasInvalidCharacters(text)) {
1241       return "invalid_characters";
1242     }
1243
1244     return false;
1245   };
1246
1247   twttr.txt.hasInvalidCharacters = function(text) {
1248     for (var i = 0; i < INVALID_CHARACTERS.length; i++) {
1249       if (text.indexOf(INVALID_CHARACTERS[i]) >= 0) {
1250         return true;
1251       }
1252     }
1253     return false;
1254   };
1255
1256   twttr.txt.isValidTweetText = function(text) {
1257     return !twttr.txt.isInvalidTweet(text);
1258   };
1259
1260   twttr.txt.isValidUsername = function(username) {
1261     if (!username) {
1262       return false;
1263     }
1264
1265     var extracted = twttr.txt.extractMentions(username);
1266
1267     // Should extract the username minus the @ sign, hence the .slice(1)
1268     return extracted.length === 1 && extracted[0] === username.slice(1);
1269   };
1270
1271   var VALID_LIST_RE = regexSupplant(/^#{validMentionOrList}$/);
1272
1273   twttr.txt.isValidList = function(usernameList) {
1274     var match = usernameList.match(VALID_LIST_RE);
1275
1276     // Must have matched and had nothing before or after
1277     return !!(match && match[1] == "" && match[4]);
1278   };
1279
1280   twttr.txt.isValidHashtag = function(hashtag) {
1281     if (!hashtag) {
1282       return false;
1283     }
1284
1285     var extracted = twttr.txt.extractHashtags(hashtag);
1286
1287     // Should extract the hashtag minus the # sign, hence the .slice(1)
1288     return extracted.length === 1 && extracted[0] === hashtag.slice(1);
1289   };
1290
1291   twttr.txt.isValidUrl = function(url, unicodeDomains, requireProtocol) {
1292     if (unicodeDomains == null) {
1293       unicodeDomains = true;
1294     }
1295
1296     if (requireProtocol == null) {
1297       requireProtocol = true;
1298     }
1299
1300     if (!url) {
1301       return false;
1302     }
1303
1304     var urlParts = url.match(twttr.txt.regexen.validateUrlUnencoded);
1305
1306     if (!urlParts || urlParts[0] !== url) {
1307       return false;
1308     }
1309
1310     var scheme = urlParts[1],
1311         authority = urlParts[2],
1312         path = urlParts[3],
1313         query = urlParts[4],
1314         fragment = urlParts[5];
1315
1316     if (!(
1317       (!requireProtocol || (isValidMatch(scheme, twttr.txt.regexen.validateUrlScheme) && scheme.match(/^https?$/i))) &&
1318       isValidMatch(path, twttr.txt.regexen.validateUrlPath) &&
1319       isValidMatch(query, twttr.txt.regexen.validateUrlQuery, true) &&
1320       isValidMatch(fragment, twttr.txt.regexen.validateUrlFragment, true)
1321     )) {
1322       return false;
1323     }
1324
1325     return (unicodeDomains && isValidMatch(authority, twttr.txt.regexen.validateUrlUnicodeAuthority)) ||
1326            (!unicodeDomains && isValidMatch(authority, twttr.txt.regexen.validateUrlAuthority));
1327   };
1328
1329   function isValidMatch(string, regex, optional) {
1330     if (!optional) {
1331       // RegExp["$&"] is the text of the last match
1332       // blank strings are ok, but are falsy, so we check stringiness instead of truthiness
1333       return ((typeof string === "string") && string.match(regex) && RegExp["$&"] === string);
1334     }
1335
1336     // RegExp["$&"] is the text of the last match
1337     return (!string || (string.match(regex) && RegExp["$&"] === string));
1338   }
1339
1340   if (typeof module != 'undefined' && module.exports) {
1341     module.exports = twttr.txt;
1342   }
1343
1344   if (typeof define == 'function' && define.amd) {
1345     define([], twttr.txt);
1346   }
1347
1348   if (typeof window != 'undefined') {
1349     if (window.twttr) {
1350       for (var prop in twttr) {
1351         window.twttr[prop] = twttr[prop];
1352       }
1353     } else {
1354       window.twttr = twttr;
1355     }
1356   }
1357 })();