CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/codemirror/addon/smc-search.js
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
// CodeMirror, copyright (c) by Marijn Haverbeke and others
7
// Distributed under an MIT license: http://codemirror.net/LICENSE
8
9
// Define search commands. Depends on dialog.js or another
10
// implementation of the openDialog method.
11
12
// Replace works a little oddly -- it will do the replace on the next
13
// Ctrl-G (or whatever is bound to findNext) press. You prevent a
14
// replace by making sure the match is no longer selected when hitting
15
// Ctrl-G.
16
17
18
"use strict";
19
20
import * as CodeMirror from "codemirror";
21
22
function searchOverlay(query, caseInsensitive) {
23
if (typeof query == "string")
24
query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
25
else if (!query.global)
26
query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
27
28
return {token: function(stream) {
29
query.lastIndex = stream.pos;
30
var match = query.exec(stream.string);
31
if (match && match.index == stream.pos) {
32
stream.pos += match[0].length || 1;
33
return "searching";
34
} else if (match) {
35
stream.pos = match.index;
36
} else {
37
stream.skipToEnd();
38
}
39
}};
40
}
41
42
function SearchState() {
43
this.posFrom = this.posTo = this.lastQuery = this.query = null;
44
this.overlay = null;
45
}
46
47
function getSearchState(cm) {
48
return cm.state.search || (cm.state.search = new SearchState());
49
}
50
51
function queryCaseInsensitive(query) {
52
return typeof query == "string" && query == query.toLowerCase();
53
}
54
55
function getSearchCursor(cm, query, pos) {
56
// Heuristic: if the query string is all lowercase, do a case insensitive search.
57
return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));
58
}
59
60
function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {
61
cm.openDialog(text, onEnter, {
62
value: deflt,
63
selectValueOnOpen: true,
64
closeOnEnter: false,
65
onClose: function() { clearSearch(cm); },
66
onKeyDown: onKeyDown
67
});
68
}
69
70
function dialog(cm, text, shortText, deflt, f) {
71
if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
72
else f(prompt(shortText, deflt));
73
}
74
75
function confirmDialog(cm, text, shortText, fs) {
76
if (cm.openConfirm) cm.openConfirm(text, fs);
77
else if (confirm(shortText)) fs[0]();
78
}
79
80
function parseString(string) {
81
return string.replace(/\\(.)/g, function(_, ch) {
82
if (ch == "n") return "\n"
83
if (ch == "r") return "\r"
84
return ch
85
})
86
}
87
88
function parseQuery(query) {
89
var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
90
if (isRE) {
91
try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }
92
catch(e) {} // Not a regular expression after all, do a string search
93
} else {
94
query = parseString(query)
95
}
96
if (typeof query == "string" ? query == "" : query.test(""))
97
query = /x^/;
98
return query;
99
}
100
101
if(navigator.platform == "MacIntel") {
102
var queryDialog =
103
'Search: <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #666" class="CodeMirror-search-hint">Next (⌘-G) and Prev (Shift-⌘-G). Use /re/ for regular expression.';
104
} else {
105
var queryDialog =
106
'Search: <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #666" class="CodeMirror-search-hint">Next (Ctrl-G) and Prev (Shift-Ctrl-G). Use /re/ for regular expression.';
107
}
108
109
function startSearch(cm, state, query) {
110
state.queryText = query;
111
state.query = parseQuery(query);
112
cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
113
state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
114
cm.addOverlay(state.overlay);
115
if (cm.showMatchesOnScrollbar) {
116
if (state.annotate) { state.annotate.clear(); state.annotate = null; }
117
state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
118
}
119
}
120
121
function doSearch(cm, rev, persistent, immediate) {
122
var state = getSearchState(cm);
123
if (state.query) return findNext(cm, rev);
124
var q = cm.getSelection() || state.lastQuery;
125
if (persistent && cm.openDialog) {
126
var hiding = null
127
var searchNext = function(query, event) {
128
CodeMirror.e_stop(event);
129
if (!query) return;
130
if (query != state.queryText) {
131
startSearch(cm, state, query);
132
state.posFrom = state.posTo = cm.getCursor();
133
}
134
if (hiding) hiding.style.opacity = 1
135
findNext(cm, event.shiftKey, function(_, to) {
136
var dialog
137
if (to.line < 3 && document.querySelector &&
138
(dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&
139
dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
140
(hiding = dialog).style.opacity = .4
141
})
142
};
143
persistentDialog(cm, queryDialog, q, searchNext, function(event, query) {
144
var keyName = CodeMirror.keyName(event)
145
var cmd = CodeMirror.keyMap[cm.getOption("keyMap")][keyName]
146
if (!cmd) cmd = cm.getOption('extraKeys')[keyName]
147
if (cmd == "findNext" || cmd == "findPrev" ||
148
cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
149
CodeMirror.e_stop(event);
150
startSearch(cm, getSearchState(cm), query);
151
cm.execCommand(cmd);
152
} else if (cmd == "find" || cmd == "findPersistent") {
153
CodeMirror.e_stop(event);
154
searchNext(query, event);
155
}
156
});
157
if (immediate && q) {
158
startSearch(cm, state, q);
159
findNext(cm, rev);
160
}
161
} else {
162
dialog(cm, queryDialog, "Search for:", q, function(query) {
163
if (query && !state.query) cm.operation(function() {
164
startSearch(cm, state, query);
165
state.posFrom = state.posTo = cm.getCursor();
166
findNext(cm, rev);
167
});
168
});
169
}
170
}
171
172
/* Return true if the given position is part of a collapsed mark.
173
See https://github.com/sagemathinc/cocalc/issues/522
174
We need this since codemirror's own search doesn't ignore
175
collapsed ranges, e.g., the output in sage worksheets.
176
*/
177
function isCollapsedPos(cm, pos) {
178
var marks = cm.findMarksAt(pos);
179
for(var i=0; i<marks.length; i++) {
180
if(marks[i].collapsed) {
181
return true;
182
}
183
}
184
return false;
185
}
186
187
function findNext(cm, rev, callback) {cm.operation(function() {
188
var state = getSearchState(cm);
189
var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
190
if (!cursor.find(rev)) {
191
cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
192
if (!cursor.find(rev)) {
193
state.init = false;
194
return;
195
}
196
}
197
cm.setSelection(cursor.from(), cursor.to());
198
cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
199
state.posFrom = cursor.from(); state.posTo = cursor.to();
200
201
if (isCollapsedPos(cm, state.posFrom) &&
202
(!state.init || (state.init.ch != state.posFrom.ch || state.init.line != state.posFrom.line))) {
203
/* In a collapsed range -- try again. This won't lead to an infinite loop in case
204
of no , since that's handled by the "if (!cursor.find(rev))" above and only_one below. */
205
if (!state.init) {
206
state.init = {line:state.posFrom.line, ch:state.posFrom.ch};
207
}
208
findNext(cm, rev, callback);
209
return
210
}
211
state.init = false;
212
if (callback) callback(cursor.from(), cursor.to())
213
});}
214
215
216
217
function clearSearch(cm) {cm.operation(function() {
218
var state = getSearchState(cm);
219
state.lastQuery = state.query;
220
if (!state.query) return;
221
state.query = state.queryText = null;
222
cm.removeOverlay(state.overlay);
223
if (state.annotate) { state.annotate.clear(); state.annotate = null; }
224
});}
225
226
var replaceQueryDialog =
227
' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #666" class="CodeMirror-search-hint">Hit enter (use /re/ syntax for regular expression search)</span>';
228
var replacementQueryDialog = 'With: <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
229
var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>";
230
231
function replaceAll(cm, query, text) {
232
cm.operation(function() {
233
for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
234
if (isCollapsedPos(cm, cursor.from())) {
235
/* ignore when cursor starts in a collapsed range. */
236
continue;
237
}
238
if (typeof query != "string") {
239
var match = cm.getRange(cursor.from(), cursor.to()).match(query);
240
cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
241
} else cursor.replace(text);
242
}
243
});
244
}
245
246
function replace(cm, all) {
247
if (cm.getOption("readOnly")) return;
248
var query = cm.getSelection() || getSearchState(cm).lastQuery;
249
var dialogText = all ? "Replace all:" : "Replace:"
250
dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) {
251
if (!query) return;
252
query = parseQuery(query);
253
dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) {
254
text = parseString(text)
255
if (all) {
256
replaceAll(cm, query, text)
257
} else {
258
clearSearch(cm);
259
var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
260
var init = false;
261
var advance = function() {
262
var start = cursor.from(), match;
263
if (!(match = cursor.findNext())) {
264
cursor = getSearchCursor(cm, query);
265
if (!(match = cursor.findNext()) ||
266
(start && cursor.from().line == start.line && cursor.from().ch == start.ch))
267
{ init = false;
268
return; }
269
}
270
cm.setSelection(cursor.from(), cursor.to());
271
cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
272
273
/* search again when cursor is in a collapsed range. */
274
var pos = cursor.from();
275
if (isCollapsedPos(cm, pos) &&
276
(!init || (init.ch != pos.ch || init.line != pos.line))) {
277
if (!init) {
278
init = {line:pos.line, ch:pos.ch};
279
}
280
advance();
281
return;
282
}
283
284
init = false;
285
confirmDialog(cm, doReplaceConfirm, "Replace?",
286
[function() {doReplace(match);}, advance,
287
function() {replaceAll(cm, query, text)}]);
288
};
289
var doReplace = function(match) {
290
cursor.replace(typeof query == "string" ? text :
291
text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
292
advance();
293
};
294
advance();
295
}
296
});
297
});
298
}
299
300
CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
301
CodeMirror.commands.findNext = doSearch;
302
CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
303
304
CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
305
CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
306
CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
307
308
CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
309
CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
310
CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
311
312
CodeMirror.commands.clearSearch = clearSearch;
313
CodeMirror.commands.replace = replace;
314
CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
315
316
317