Debian Codegraph @

resources/legacy/addon/matchbrackets-wmde.js

raw
1 // CodeMirror, copyright (c) by Marijn Haverbeke and others
2 // Distributed under an MIT license: https://codemirror.net/LICENSE
3
4 /**
5 * Modified by the WMDE Technical Wishes Team
6 * currently based on
7 * https://github.com/codemirror/CodeMirror/blob/4823ade863d0306371858394bc1b117aed3043bf/addon/edit/matchbrackets.js
8 * (from 2021-01-14)
9 *
10 * Modifications:
11 * - Introduced findSurroundingBrackets() along with it's `brackets` map. This is called when no
12 * `match` is found at the current cursor position.
13 * - Removed the `style` argument from the `scanForBracket` call. This fixes a compatibility issue
14 * with the "mediawiki" mode that tokenizes some brackets as `[[` or `{{{` pairs or triplets.
15 * - Changed the class name `CodeMirror-matchingbracket` to `cm-mw-matchingbracket`. This is
16 * necessary to get rid of the "default styles for common addons" from codemirror.css (T270926).
17 */
18 /* eslint-disable */
19
20 (function(mod) {
21 if (typeof exports == "object" && typeof module == "object") // CommonJS
22 mod(require("../../lib/codemirror"));
23 else if (typeof define == "function" && define.amd) // AMD
24 define(["../../lib/codemirror"], mod);
25 else // Plain browser env
26 mod(CodeMirror);
27 })(function(CodeMirror) {
28 var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
29 (document.documentMode == null || document.documentMode < 8);
30
31 var Pos = CodeMirror.Pos;
32
33 var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<", "<": ">>", ">": "<<"};
34
35 function bracketRegex(config) {
36 return config && config.bracketRegex || /[(){}[\]]/
37 }
38
39 /* eslint-enable */
40 const surroundingBrackets = {
41 '(': ')',
42 ')': false,
43 '[': ']',
44 ']': false,
45 '{': '}',
46 '}': false
47 };
48
49 function findSurroundingBrackets( cm, where, config ) {
50 let from, to, ch,
51 nestedBracketsToSkip = 0,
52 lineNo = where.line,
53 line = cm.getLine( lineNo ),
54 pos = where.ch;
55 const maxScanLen = ( config && config.maxScanLineLength ) || 10000,
56 maxScanLines = ( config && config.maxScanLines ) || 1000;
57
58 // Check the limit for the current line
59 if ( line.length > maxScanLen ) {
60 return null;
61 }
62
63 // Search forward
64 while ( true ) {
65 if ( pos >= line.length ) {
66 lineNo++;
67 // Give up when to many lines have been scanned
68 if ( lineNo > cm.lastLine() || lineNo - where.line >= maxScanLines ) {
69 break;
70 }
71 line = cm.getLine( lineNo );
72 // Give up when the next line is to long
73 if ( line.length > maxScanLen ) {
74 return null;
75 }
76 pos = 0;
77 // Continue early to make sure we don't read characters from empty lines
78 continue;
79 }
80
81 ch = line.charAt( pos );
82 if ( ch in surroundingBrackets ) {
83 // Found a closing bracket that's not part of a nested pair
84 if ( !surroundingBrackets[ch] && nestedBracketsToSkip <= 0 ) {
85 to = { pos: Pos( lineNo, pos ), char: ch };
86 break;
87 }
88 nestedBracketsToSkip += surroundingBrackets[ch] ? 1 : -1;
89 }
90
91 pos++;
92 }
93
94 nestedBracketsToSkip = 0;
95 lineNo = where.line;
96 line = cm.getLine( lineNo );
97 pos = where.ch;
98
99 // Search backwards
100 while ( true ) {
101 pos--;
102 if ( pos < 0 ) {
103 lineNo--;
104 // Give up when to many lines have been scanned
105 if ( lineNo < cm.firstLine() || where.line - lineNo >= maxScanLines ) {
106 break;
107 }
108 line = cm.getLine( lineNo );
109 // Give up when the next line is to long
110 if ( line.length > maxScanLen ) {
111 return null;
112 }
113 pos = line.length;
114 // Continue early to make sure we don't read characters from empty lines
115 continue;
116 }
117
118 ch = line.charAt( pos );
119 if ( ch in surroundingBrackets ) {
120 // Found an opening bracket that's not part of a nested pair
121 if ( surroundingBrackets[ch] && nestedBracketsToSkip <= 0 ) {
122 from = { pos: Pos( lineNo, pos ), expectedToChar: surroundingBrackets[ch] };
123 break;
124 }
125 nestedBracketsToSkip += surroundingBrackets[ch] ? -1 : 1;
126 }
127 }
128
129 if ( from && to ) {
130 return {
131 from: from.pos,
132 to: to.pos,
133 match: from.expectedToChar === to.char
134 };
135 } else if ( from || to ) {
136 return { from: ( from || to ).pos, match: false };
137 }
138
139 return null;
140 }
141
142 function stillTheSameMarks( marks, config ) {
143 const same = config.currentMarks &&
144 // No need to compare the details if it's not even the same amount
145 config.currentMarks.length === marks.length &&
146 // We need the flexibility because the order can be closing → opening bracket as well
147 marks.every( ( mark ) => {
148 // These are typically only 2 elements for the opening and closing bracket
149 for ( let i = 0; i < config.currentMarks.length; i++ ) {
150 // Ordered from "most likely to change" to "least likely" for performance
151 if ( config.currentMarks[i].from.ch === mark.from.ch &&
152 config.currentMarks[i].from.line === mark.from.line &&
153 config.currentMarks[i].match === mark.match
154 ) {
155 // This assumes all elements are unique, which should be the case
156 config.currentMarks.splice( i, 1 );
157 return true;
158 }
159 }
160 return false;
161 } ) &&
162 // Must be empty at the end, i.e. all elements must have been found and removed
163 !config.currentMarks.length;
164
165 // Restore config.currentMarks after the loop above destroyed the original. This is done for
166 // performance reasons to avoid the need for an (expensive) copy.
167 config.currentMarks = marks;
168 return same;
169 }
170 /* eslint-disable */
171
172 function findMatchingBracket(cm, where, config) {
173 var line = cm.getLineHandle(where.line), pos = where.ch - 1;
174 var afterCursor = config && config.afterCursor
175 if (afterCursor == null)
176 afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)
177 var re = bracketRegex(config)
178
179 // A cursor is defined as between two characters, but in in vim command mode
180 // (i.e. not insert mode), the cursor is visually represented as a
181 // highlighted box on top of the 2nd character. Otherwise, we allow matches
182 // from before or after the cursor.
183 var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) ||
184 re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)];
185 // Note: Modified by WMDE, was `return null` before.
186 if (!match) return findSurroundingBrackets( cm, where, config );
187 var dir = match.charAt(1) == ">" ? 1 : -1;
188 if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;
189 // Note: Disabled by WMDE for performance reasons. Not used anymore further down.
190 // var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
191
192 // Note: Modified by WMDE, used `style || null` instead of `undefined` before.
193 var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, undefined, config);
194 if (found == null) return null;
195 return {from: Pos(where.line, pos), to: found && found.pos,
196 match: found && found.ch == match.charAt(0), forward: dir > 0};
197 }
198
199 // bracketRegex is used to specify which type of bracket to scan
200 // should be a regexp, e.g. /[[\]]/
201 //
202 // Note: If "where" is on an open bracket, then this bracket is ignored.
203 //
204 // Returns false when no bracket was found, null when it reached
205 // maxScanLines and gave up
206 function scanForBracket(cm, where, dir, style, config) {
207 var maxScanLen = (config && config.maxScanLineLength) || 10000;
208 var maxScanLines = (config && config.maxScanLines) || 1000;
209
210 var stack = [];
211 var re = bracketRegex(config)
212 var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
213 : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
214 for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
215 var line = cm.getLine(lineNo);
216 if (!line) continue;
217 var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
218 if (line.length > maxScanLen) continue;
219 if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
220 for (; pos != end; pos += dir) {
221 var ch = line.charAt(pos);
222 if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
223 var match = matching[ch];
224 if (match && (match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
225 else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
226 else stack.pop();
227 }
228 }
229 }
230 return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
231 }
232
233 function matchBrackets(cm, autoclear, config) {
234 // Disable brace matching in long lines, since it'll cause hugely slow updates
235 var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000,
236 highlightNonMatching = config && config.highlightNonMatching;
237 var i, markPositions = [], marks = [], ranges = cm.listSelections();
238 for (i = 0; i < ranges.length; i++) {
239 var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
240 if (match && (match.match || highlightNonMatching !== false) && cm.getLine(match.from.line).length <= maxHighlightLen) {
241 // Note: Modified by WMDE, now uses an intermediate format to delay the actual highlighting
242 markPositions.push(match);
243 if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
244 markPositions.push({from: match.to, match: match.match});
245 }
246 }
247
248 /* eslint-enable */
249 // There is no config when autoclear is true
250 if ( config && stillTheSameMarks( markPositions, config ) ) {
251 return;
252 }
253
254 if ( !autoclear && config.currentlyHighlighted ) {
255 config.currentlyHighlighted();
256 config.currentlyHighlighted = null;
257 // Backup of the new mark positions must be done after the clear above
258 config.currentMarks = markPositions;
259 }
260
261 for ( i = 0; i < markPositions.length; i++ ) {
262 marks.push( cm.markText(
263 markPositions[i].from,
264 // Note: This assumes there is always exactly 1 character to highlight
265 Pos( markPositions[i].from.line, markPositions[i].from.ch + 1 ),
266 // Note: Modified by WMDE to get rid of the library's "default styles for common addons"
267 { className: markPositions[i].match ? 'cm-mw-matchingbracket' : 'CodeMirror-nonmatchingbracket' }
268 ) );
269 }
270 /* eslint-disable */
271
272 if (marks.length) {
273 // Kludge to work around the IE bug from issue #1193, where text
274 // input stops going to the textarea whenever this fires.
275 if (ie_lt8 && cm.state.focused) cm.focus();
276
277 var clear = function() {
278 cm.operation(function() {
279 for (var i = 0; i < marks.length; i++) marks[i].clear();
280 config.currentMarks = [];
281 });
282 };
283 if (autoclear) setTimeout(clear, 800);
284 else config.currentlyHighlighted = clear;
285 }
286 }
287
288 function doMatchBrackets(cm) {
289 cm.operation(function() {
290 matchBrackets(cm, false, cm.state.matchBrackets);
291 });
292 }
293
294 function clearHighlighted(cm) {
295 if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
296 cm.state.matchBrackets.currentlyHighlighted();
297 cm.state.matchBrackets.currentlyHighlighted = null;
298 }
299 }
300
301 CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
302 if (old && old != CodeMirror.Init) {
303 cm.off("cursorActivity", doMatchBrackets);
304 cm.off("focus", doMatchBrackets)
305 cm.off("blur", clearHighlighted)
306 clearHighlighted(cm);
307 }
308 if (val) {
309 cm.state.matchBrackets = typeof val == "object" ? val : {};
310 cm.on("cursorActivity", doMatchBrackets);
311 cm.on("focus", doMatchBrackets)
312 cm.on("blur", clearHighlighted)
313 }
314 });
315
316 CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
317 CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){
318 // Backwards-compatibility kludge
319 if (oldConfig || typeof config == "boolean") {
320 if (!oldConfig) {
321 config = config ? {strict: true} : null
322 } else {
323 oldConfig.strict = config
324 config = oldConfig
325 }
326 }
327 return findMatchingBracket(this, pos, config)
328 });
329 CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
330 return scanForBracket(this, pos, dir, style, config);
331 });
332 });