You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

295 lines
12 KiB

7 months ago
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/5/LICENSE
  3. // Define search commands. Depends on dialog.js or another
  4. // implementation of the openDialog method.
  5. // Replace works a little oddly -- it will do the replace on the next
  6. // Ctrl-G (or whatever is bound to findNext) press. You prevent a
  7. // replace by making sure the match is no longer selected when hitting
  8. // Ctrl-G.
  9. (function(mod) {
  10. if (typeof exports == "object" && typeof module == "object") // CommonJS
  11. mod(require("../../lib/codemirror"), require("./searchcursor"), require("../dialog/dialog"));
  12. else if (typeof define == "function" && define.amd) // AMD
  13. define(["../../lib/codemirror", "./searchcursor", "../dialog/dialog"], mod);
  14. else // Plain browser env
  15. mod(CodeMirror);
  16. })(function(CodeMirror) {
  17. "use strict";
  18. // default search panel location
  19. CodeMirror.defineOption("search", {bottom: false});
  20. function searchOverlay(query, caseInsensitive) {
  21. if (typeof query == "string")
  22. query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
  23. else if (!query.global)
  24. query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
  25. return {token: function(stream) {
  26. query.lastIndex = stream.pos;
  27. var match = query.exec(stream.string);
  28. if (match && match.index == stream.pos) {
  29. stream.pos += match[0].length || 1;
  30. return "searching";
  31. } else if (match) {
  32. stream.pos = match.index;
  33. } else {
  34. stream.skipToEnd();
  35. }
  36. }};
  37. }
  38. function SearchState() {
  39. this.posFrom = this.posTo = this.lastQuery = this.query = null;
  40. this.overlay = null;
  41. }
  42. function getSearchState(cm) {
  43. return cm.state.search || (cm.state.search = new SearchState());
  44. }
  45. function queryCaseInsensitive(query) {
  46. return typeof query == "string" && query == query.toLowerCase();
  47. }
  48. function getSearchCursor(cm, query, pos) {
  49. // Heuristic: if the query string is all lowercase, do a case insensitive search.
  50. return cm.getSearchCursor(query, pos, {caseFold: queryCaseInsensitive(query), multiline: true});
  51. }
  52. function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {
  53. cm.openDialog(text, onEnter, {
  54. value: deflt,
  55. selectValueOnOpen: true,
  56. closeOnEnter: false,
  57. onClose: function() { clearSearch(cm); },
  58. onKeyDown: onKeyDown,
  59. bottom: cm.options.search.bottom
  60. });
  61. }
  62. function dialog(cm, text, shortText, deflt, f) {
  63. if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true, bottom: cm.options.search.bottom});
  64. else f(prompt(shortText, deflt));
  65. }
  66. function confirmDialog(cm, text, shortText, fs) {
  67. if (cm.openConfirm) cm.openConfirm(text, fs);
  68. else if (confirm(shortText)) fs[0]();
  69. }
  70. function parseString(string) {
  71. return string.replace(/\\([nrt\\])/g, function(match, ch) {
  72. if (ch == "n") return "\n"
  73. if (ch == "r") return "\r"
  74. if (ch == "t") return "\t"
  75. if (ch == "\\") return "\\"
  76. return match
  77. })
  78. }
  79. function parseQuery(query) {
  80. var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
  81. if (isRE) {
  82. try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }
  83. catch(e) {} // Not a regular expression after all, do a string search
  84. } else {
  85. query = parseString(query)
  86. }
  87. if (typeof query == "string" ? query == "" : query.test(""))
  88. query = /x^/;
  89. return query;
  90. }
  91. function startSearch(cm, state, query) {
  92. state.queryText = query;
  93. state.query = parseQuery(query);
  94. cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
  95. state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
  96. cm.addOverlay(state.overlay);
  97. if (cm.showMatchesOnScrollbar) {
  98. if (state.annotate) { state.annotate.clear(); state.annotate = null; }
  99. state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
  100. }
  101. }
  102. function doSearch(cm, rev, persistent, immediate) {
  103. var state = getSearchState(cm);
  104. if (state.query) return findNext(cm, rev);
  105. var q = cm.getSelection() || state.lastQuery;
  106. if (q instanceof RegExp && q.source == "x^") q = null
  107. if (persistent && cm.openDialog) {
  108. var hiding = null
  109. var searchNext = function(query, event) {
  110. CodeMirror.e_stop(event);
  111. if (!query) return;
  112. if (query != state.queryText) {
  113. startSearch(cm, state, query);
  114. state.posFrom = state.posTo = cm.getCursor();
  115. }
  116. if (hiding) hiding.style.opacity = 1
  117. findNext(cm, event.shiftKey, function(_, to) {
  118. var dialog
  119. if (to.line < 3 && document.querySelector &&
  120. (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&
  121. dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
  122. (hiding = dialog).style.opacity = .4
  123. })
  124. };
  125. persistentDialog(cm, getQueryDialog(cm), q, searchNext, function(event, query) {
  126. var keyName = CodeMirror.keyName(event)
  127. var extra = cm.getOption('extraKeys'), cmd = (extra && extra[keyName]) || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]
  128. if (cmd == "findNext" || cmd == "findPrev" ||
  129. cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
  130. CodeMirror.e_stop(event);
  131. startSearch(cm, getSearchState(cm), query);
  132. cm.execCommand(cmd);
  133. } else if (cmd == "find" || cmd == "findPersistent") {
  134. CodeMirror.e_stop(event);
  135. searchNext(query, event);
  136. }
  137. });
  138. if (immediate && q) {
  139. startSearch(cm, state, q);
  140. findNext(cm, rev);
  141. }
  142. } else {
  143. dialog(cm, getQueryDialog(cm), "Search for:", q, function(query) {
  144. if (query && !state.query) cm.operation(function() {
  145. startSearch(cm, state, query);
  146. state.posFrom = state.posTo = cm.getCursor();
  147. findNext(cm, rev);
  148. });
  149. });
  150. }
  151. }
  152. function findNext(cm, rev, callback) {cm.operation(function() {
  153. var state = getSearchState(cm);
  154. var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
  155. if (!cursor.find(rev)) {
  156. cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
  157. if (!cursor.find(rev)) return;
  158. }
  159. cm.setSelection(cursor.from(), cursor.to());
  160. cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
  161. state.posFrom = cursor.from(); state.posTo = cursor.to();
  162. if (callback) callback(cursor.from(), cursor.to())
  163. });}
  164. function clearSearch(cm) {cm.operation(function() {
  165. var state = getSearchState(cm);
  166. state.lastQuery = state.query;
  167. if (!state.query) return;
  168. state.query = state.queryText = null;
  169. cm.removeOverlay(state.overlay);
  170. if (state.annotate) { state.annotate.clear(); state.annotate = null; }
  171. });}
  172. function el(tag, attrs) {
  173. var element = tag ? document.createElement(tag) : document.createDocumentFragment();
  174. for (var key in attrs) {
  175. element[key] = attrs[key];
  176. }
  177. for (var i = 2; i < arguments.length; i++) {
  178. var child = arguments[i]
  179. element.appendChild(typeof child == "string" ? document.createTextNode(child) : child);
  180. }
  181. return element;
  182. }
  183. function getQueryDialog(cm) {
  184. var label = el("label", {className: "CodeMirror-search-label"},
  185. cm.phrase("Search:"),
  186. el("input", {type: "text", "style": "width: 10em", className: "CodeMirror-search-field",
  187. id: "CodeMirror-search-field"}));
  188. label.setAttribute("for","CodeMirror-search-field");
  189. return el("", null, label, " ",
  190. el("span", {style: "color: #666", className: "CodeMirror-search-hint"},
  191. cm.phrase("(Use /re/ syntax for regexp search)")));
  192. }
  193. function getReplaceQueryDialog(cm) {
  194. return el("", null, " ",
  195. el("input", {type: "text", "style": "width: 10em", className: "CodeMirror-search-field"}), " ",
  196. el("span", {style: "color: #666", className: "CodeMirror-search-hint"},
  197. cm.phrase("(Use /re/ syntax for regexp search)")));
  198. }
  199. function getReplacementQueryDialog(cm) {
  200. return el("", null,
  201. el("span", {className: "CodeMirror-search-label"}, cm.phrase("With:")), " ",
  202. el("input", {type: "text", "style": "width: 10em", className: "CodeMirror-search-field"}));
  203. }
  204. function getDoReplaceConfirm(cm) {
  205. return el("", null,
  206. el("span", {className: "CodeMirror-search-label"}, cm.phrase("Replace?")), " ",
  207. el("button", {}, cm.phrase("Yes")), " ",
  208. el("button", {}, cm.phrase("No")), " ",
  209. el("button", {}, cm.phrase("All")), " ",
  210. el("button", {}, cm.phrase("Stop")));
  211. }
  212. function replaceAll(cm, query, text) {
  213. cm.operation(function() {
  214. for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
  215. if (typeof query != "string") {
  216. var match = cm.getRange(cursor.from(), cursor.to()).match(query);
  217. cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
  218. } else cursor.replace(text);
  219. }
  220. });
  221. }
  222. function replace(cm, all) {
  223. if (cm.getOption("readOnly")) return;
  224. var query = cm.getSelection() || getSearchState(cm).lastQuery;
  225. var dialogText = all ? cm.phrase("Replace all:") : cm.phrase("Replace:")
  226. var fragment = el("", null,
  227. el("span", {className: "CodeMirror-search-label"}, dialogText),
  228. getReplaceQueryDialog(cm))
  229. dialog(cm, fragment, dialogText, query, function(query) {
  230. if (!query) return;
  231. query = parseQuery(query);
  232. dialog(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function(text) {
  233. text = parseString(text)
  234. if (all) {
  235. replaceAll(cm, query, text)
  236. } else {
  237. clearSearch(cm);
  238. var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
  239. var advance = function() {
  240. var start = cursor.from(), match;
  241. if (!(match = cursor.findNext())) {
  242. cursor = getSearchCursor(cm, query);
  243. if (!(match = cursor.findNext()) ||
  244. (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
  245. }
  246. cm.setSelection(cursor.from(), cursor.to());
  247. cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
  248. confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"),
  249. [function() {doReplace(match);}, advance,
  250. function() {replaceAll(cm, query, text)}]);
  251. };
  252. var doReplace = function(match) {
  253. cursor.replace(typeof query == "string" ? text :
  254. text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
  255. advance();
  256. };
  257. advance();
  258. }
  259. });
  260. });
  261. }
  262. CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
  263. CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
  264. CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
  265. CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
  266. CodeMirror.commands.findNext = doSearch;
  267. CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
  268. CodeMirror.commands.clearSearch = clearSearch;
  269. CodeMirror.commands.replace = replace;
  270. CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
  271. });