Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/frontend/codemirror/addon/smc-search.js
Views: 687
/*1* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45// CodeMirror, copyright (c) by Marijn Haverbeke and others6// Distributed under an MIT license: http://codemirror.net/LICENSE78// Define search commands. Depends on dialog.js or another9// implementation of the openDialog method.1011// Replace works a little oddly -- it will do the replace on the next12// Ctrl-G (or whatever is bound to findNext) press. You prevent a13// replace by making sure the match is no longer selected when hitting14// Ctrl-G.151617"use strict";1819import * as CodeMirror from "codemirror";2021function searchOverlay(query, caseInsensitive) {22if (typeof query == "string")23query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");24else if (!query.global)25query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");2627return {token: function(stream) {28query.lastIndex = stream.pos;29var match = query.exec(stream.string);30if (match && match.index == stream.pos) {31stream.pos += match[0].length || 1;32return "searching";33} else if (match) {34stream.pos = match.index;35} else {36stream.skipToEnd();37}38}};39}4041function SearchState() {42this.posFrom = this.posTo = this.lastQuery = this.query = null;43this.overlay = null;44}4546function getSearchState(cm) {47return cm.state.search || (cm.state.search = new SearchState());48}4950function queryCaseInsensitive(query) {51return typeof query == "string" && query == query.toLowerCase();52}5354function getSearchCursor(cm, query, pos) {55// Heuristic: if the query string is all lowercase, do a case insensitive search.56return cm.getSearchCursor(query, pos, queryCaseInsensitive(query));57}5859function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {60cm.openDialog(text, onEnter, {61value: deflt,62selectValueOnOpen: true,63closeOnEnter: false,64onClose: function() { clearSearch(cm); },65onKeyDown: onKeyDown66});67}6869function dialog(cm, text, shortText, deflt, f) {70if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});71else f(prompt(shortText, deflt));72}7374function confirmDialog(cm, text, shortText, fs) {75if (cm.openConfirm) cm.openConfirm(text, fs);76else if (confirm(shortText)) fs[0]();77}7879function parseString(string) {80return string.replace(/\\(.)/g, function(_, ch) {81if (ch == "n") return "\n"82if (ch == "r") return "\r"83return ch84})85}8687function parseQuery(query) {88var isRE = query.match(/^\/(.*)\/([a-z]*)$/);89if (isRE) {90try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }91catch(e) {} // Not a regular expression after all, do a string search92} else {93query = parseString(query)94}95if (typeof query == "string" ? query == "" : query.test(""))96query = /x^/;97return query;98}99100if(navigator.platform == "MacIntel") {101var queryDialog =102'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.';103} else {104var queryDialog =105'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.';106}107108function startSearch(cm, state, query) {109state.queryText = query;110state.query = parseQuery(query);111cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));112state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));113cm.addOverlay(state.overlay);114if (cm.showMatchesOnScrollbar) {115if (state.annotate) { state.annotate.clear(); state.annotate = null; }116state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));117}118}119120function doSearch(cm, rev, persistent, immediate) {121var state = getSearchState(cm);122if (state.query) return findNext(cm, rev);123var q = cm.getSelection() || state.lastQuery;124if (persistent && cm.openDialog) {125var hiding = null126var searchNext = function(query, event) {127CodeMirror.e_stop(event);128if (!query) return;129if (query != state.queryText) {130startSearch(cm, state, query);131state.posFrom = state.posTo = cm.getCursor();132}133if (hiding) hiding.style.opacity = 1134findNext(cm, event.shiftKey, function(_, to) {135var dialog136if (to.line < 3 && document.querySelector &&137(dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&138dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)139(hiding = dialog).style.opacity = .4140})141};142persistentDialog(cm, queryDialog, q, searchNext, function(event, query) {143var keyName = CodeMirror.keyName(event)144var cmd = CodeMirror.keyMap[cm.getOption("keyMap")][keyName]145if (!cmd) cmd = cm.getOption('extraKeys')[keyName]146if (cmd == "findNext" || cmd == "findPrev" ||147cmd == "findPersistentNext" || cmd == "findPersistentPrev") {148CodeMirror.e_stop(event);149startSearch(cm, getSearchState(cm), query);150cm.execCommand(cmd);151} else if (cmd == "find" || cmd == "findPersistent") {152CodeMirror.e_stop(event);153searchNext(query, event);154}155});156if (immediate && q) {157startSearch(cm, state, q);158findNext(cm, rev);159}160} else {161dialog(cm, queryDialog, "Search for:", q, function(query) {162if (query && !state.query) cm.operation(function() {163startSearch(cm, state, query);164state.posFrom = state.posTo = cm.getCursor();165findNext(cm, rev);166});167});168}169}170171/* Return true if the given position is part of a collapsed mark.172See https://github.com/sagemathinc/cocalc/issues/522173We need this since codemirror's own search doesn't ignore174collapsed ranges, e.g., the output in sage worksheets.175*/176function isCollapsedPos(cm, pos) {177var marks = cm.findMarksAt(pos);178for(var i=0; i<marks.length; i++) {179if(marks[i].collapsed) {180return true;181}182}183return false;184}185186function findNext(cm, rev, callback) {cm.operation(function() {187var state = getSearchState(cm);188var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);189if (!cursor.find(rev)) {190cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));191if (!cursor.find(rev)) {192state.init = false;193return;194}195}196cm.setSelection(cursor.from(), cursor.to());197cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);198state.posFrom = cursor.from(); state.posTo = cursor.to();199200if (isCollapsedPos(cm, state.posFrom) &&201(!state.init || (state.init.ch != state.posFrom.ch || state.init.line != state.posFrom.line))) {202/* In a collapsed range -- try again. This won't lead to an infinite loop in case203of no , since that's handled by the "if (!cursor.find(rev))" above and only_one below. */204if (!state.init) {205state.init = {line:state.posFrom.line, ch:state.posFrom.ch};206}207findNext(cm, rev, callback);208return209}210state.init = false;211if (callback) callback(cursor.from(), cursor.to())212});}213214215216function clearSearch(cm) {cm.operation(function() {217var state = getSearchState(cm);218state.lastQuery = state.query;219if (!state.query) return;220state.query = state.queryText = null;221cm.removeOverlay(state.overlay);222if (state.annotate) { state.annotate.clear(); state.annotate = null; }223});}224225var replaceQueryDialog =226' <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>';227var replacementQueryDialog = 'With: <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';228var doReplaceConfirm = "Replace? <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>";229230function replaceAll(cm, query, text) {231cm.operation(function() {232for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {233if (isCollapsedPos(cm, cursor.from())) {234/* ignore when cursor starts in a collapsed range. */235continue;236}237if (typeof query != "string") {238var match = cm.getRange(cursor.from(), cursor.to()).match(query);239cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));240} else cursor.replace(text);241}242});243}244245function replace(cm, all) {246if (cm.getOption("readOnly")) return;247var query = cm.getSelection() || getSearchState(cm).lastQuery;248var dialogText = all ? "Replace all:" : "Replace:"249dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) {250if (!query) return;251query = parseQuery(query);252dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) {253text = parseString(text)254if (all) {255replaceAll(cm, query, text)256} else {257clearSearch(cm);258var cursor = getSearchCursor(cm, query, cm.getCursor("from"));259var init = false;260var advance = function() {261var start = cursor.from(), match;262if (!(match = cursor.findNext())) {263cursor = getSearchCursor(cm, query);264if (!(match = cursor.findNext()) ||265(start && cursor.from().line == start.line && cursor.from().ch == start.ch))266{ init = false;267return; }268}269cm.setSelection(cursor.from(), cursor.to());270cm.scrollIntoView({from: cursor.from(), to: cursor.to()});271272/* search again when cursor is in a collapsed range. */273var pos = cursor.from();274if (isCollapsedPos(cm, pos) &&275(!init || (init.ch != pos.ch || init.line != pos.line))) {276if (!init) {277init = {line:pos.line, ch:pos.ch};278}279advance();280return;281}282283init = false;284confirmDialog(cm, doReplaceConfirm, "Replace?",285[function() {doReplace(match);}, advance,286function() {replaceAll(cm, query, text)}]);287};288var doReplace = function(match) {289cursor.replace(typeof query == "string" ? text :290text.replace(/\$(\d)/g, function(_, i) {return match[i];}));291advance();292};293advance();294}295});296});297}298299CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};300CodeMirror.commands.findNext = doSearch;301CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};302303CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};304CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};305CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};306307CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};308CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};309CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};310311CodeMirror.commands.clearSearch = clearSearch;312CodeMirror.commands.replace = replace;313CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};314315316317