search.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/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. function searchOverlay(query, caseInsensitive) {
  19. if (typeof query == "string")
  20. query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
  21. else if (!query.global)
  22. query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
  23. return {token: function(stream) {
  24. query.lastIndex = stream.pos;
  25. var match = query.exec(stream.string);
  26. if (match && match.index == stream.pos) {
  27. stream.pos += match[0].length || 1;
  28. return "searching";
  29. } else if (match) {
  30. stream.pos = match.index;
  31. } else {
  32. stream.skipToEnd();
  33. }
  34. }};
  35. }
  36. function SearchState() {
  37. this.posFrom = this.posTo = this.lastQuery = this.query = null;
  38. this.overlay = null;
  39. }
  40. function getSearchState(cm) {
  41. return cm.state.search || (cm.state.search = new SearchState());
  42. }
  43. function queryCaseInsensitive(query) {
  44. return typeof query == "string" && query == query.toLowerCase();
  45. }
  46. function getSearchCursor(cm, query, pos) {
  47. // Heuristic: if the query string is all lowercase, do a case insensitive search.
  48. return cm.getSearchCursor(query, pos, {caseFold: queryCaseInsensitive(query), multiline: true});
  49. }
  50. function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {
  51. cm.openDialog(text, onEnter, {
  52. value: deflt,
  53. selectValueOnOpen: true,
  54. closeOnEnter: false,
  55. onClose: function() { clearSearch(cm); },
  56. onKeyDown: onKeyDown
  57. });
  58. }
  59. function dialog(cm, text, shortText, deflt, f) {
  60. if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
  61. else f(prompt(shortText, deflt));
  62. }
  63. function confirmDialog(cm, text, shortText, fs) {
  64. if (cm.openConfirm) cm.openConfirm(text, fs);
  65. else if (confirm(shortText)) fs[0]();
  66. }
  67. function parseString(string) {
  68. return string.replace(/\\(.)/g, function(_, ch) {
  69. if (ch == "n") return "\n"
  70. if (ch == "r") return "\r"
  71. return ch
  72. })
  73. }
  74. function parseQuery(query) {
  75. var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
  76. if (isRE) {
  77. try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }
  78. catch(e) {} // Not a regular expression after all, do a string search
  79. } else {
  80. query = parseString(query)
  81. }
  82. if (typeof query == "string" ? query == "" : query.test(""))
  83. query = /x^/;
  84. return query;
  85. }
  86. function startSearch(cm, state, query) {
  87. state.queryText = query;
  88. state.query = parseQuery(query);
  89. cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
  90. state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
  91. cm.addOverlay(state.overlay);
  92. if (cm.showMatchesOnScrollbar) {
  93. if (state.annotate) { state.annotate.clear(); state.annotate = null; }
  94. state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
  95. }
  96. }
  97. function doSearch(cm, rev, persistent, immediate) {
  98. var state = getSearchState(cm);
  99. if (state.query) return findNext(cm, rev);
  100. var q = cm.getSelection() || state.lastQuery;
  101. if (q instanceof RegExp && q.source == "x^") q = null
  102. if (persistent && cm.openDialog) {
  103. var hiding = null
  104. var searchNext = function(query, event) {
  105. CodeMirror.e_stop(event);
  106. if (!query) return;
  107. if (query != state.queryText) {
  108. startSearch(cm, state, query);
  109. state.posFrom = state.posTo = cm.getCursor();
  110. }
  111. if (hiding) hiding.style.opacity = 1
  112. findNext(cm, event.shiftKey, function(_, to) {
  113. var dialog
  114. if (to.line < 3 && document.querySelector &&
  115. (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&
  116. dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
  117. (hiding = dialog).style.opacity = .4
  118. })
  119. };
  120. persistentDialog(cm, getQueryDialog(cm), q, searchNext, function(event, query) {
  121. var keyName = CodeMirror.keyName(event)
  122. var extra = cm.getOption('extraKeys'), cmd = (extra && extra[keyName]) || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]
  123. if (cmd == "findNext" || cmd == "findPrev" ||
  124. cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
  125. CodeMirror.e_stop(event);
  126. startSearch(cm, getSearchState(cm), query);
  127. cm.execCommand(cmd);
  128. } else if (cmd == "find" || cmd == "findPersistent") {
  129. CodeMirror.e_stop(event);
  130. searchNext(query, event);
  131. }
  132. });
  133. if (immediate && q) {
  134. startSearch(cm, state, q);
  135. findNext(cm, rev);
  136. }
  137. } else {
  138. dialog(cm, getQueryDialog(cm), "Search for:", q, function(query) {
  139. if (query && !state.query) cm.operation(function() {
  140. startSearch(cm, state, query);
  141. state.posFrom = state.posTo = cm.getCursor();
  142. findNext(cm, rev);
  143. });
  144. });
  145. }
  146. }
  147. function findNext(cm, rev, callback) {cm.operation(function() {
  148. var state = getSearchState(cm);
  149. var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
  150. if (!cursor.find(rev)) {
  151. cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
  152. if (!cursor.find(rev)) return;
  153. }
  154. cm.setSelection(cursor.from(), cursor.to());
  155. cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
  156. state.posFrom = cursor.from(); state.posTo = cursor.to();
  157. if (callback) callback(cursor.from(), cursor.to())
  158. });}
  159. function clearSearch(cm) {cm.operation(function() {
  160. var state = getSearchState(cm);
  161. state.lastQuery = state.query;
  162. if (!state.query) return;
  163. state.query = state.queryText = null;
  164. cm.removeOverlay(state.overlay);
  165. if (state.annotate) { state.annotate.clear(); state.annotate = null; }
  166. });}
  167. function getQueryDialog(cm) {
  168. return '<span class="CodeMirror-search-label">' + cm.phrase("Search:") + '</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">' + cm.phrase("(Use /re/ syntax for regexp search)") + '</span>';
  169. }
  170. function getReplaceQueryDialog(cm) {
  171. return ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">' + cm.phrase("(Use /re/ syntax for regexp search)") + '</span>';
  172. }
  173. function getReplacementQueryDialog(cm) {
  174. return '<span class="CodeMirror-search-label">' + cm.phrase("With:") + '</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
  175. }
  176. function getDoReplaceConfirm(cm) {
  177. return '<span class="CodeMirror-search-label">' + cm.phrase("Replace?") + '</span> <button>' + cm.phrase("Yes") + '</button> <button>' + cm.phrase("No") + '</button> <button>' + cm.phrase("All") + '</button> <button>' + cm.phrase("Stop") + '</button> ';
  178. }
  179. function replaceAll(cm, query, text) {
  180. cm.operation(function() {
  181. for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
  182. if (typeof query != "string") {
  183. var match = cm.getRange(cursor.from(), cursor.to()).match(query);
  184. cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
  185. } else cursor.replace(text);
  186. }
  187. });
  188. }
  189. function replace(cm, all) {
  190. if (cm.getOption("readOnly")) return;
  191. var query = cm.getSelection() || getSearchState(cm).lastQuery;
  192. var dialogText = '<span class="CodeMirror-search-label">' + (all ? cm.phrase("Replace all:") : cm.phrase("Replace:")) + '</span>';
  193. dialog(cm, dialogText + getReplaceQueryDialog(cm), dialogText, query, function(query) {
  194. if (!query) return;
  195. query = parseQuery(query);
  196. dialog(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function(text) {
  197. text = parseString(text)
  198. if (all) {
  199. replaceAll(cm, query, text)
  200. } else {
  201. clearSearch(cm);
  202. var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
  203. var advance = function() {
  204. var start = cursor.from(), match;
  205. if (!(match = cursor.findNext())) {
  206. cursor = getSearchCursor(cm, query);
  207. if (!(match = cursor.findNext()) ||
  208. (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
  209. }
  210. cm.setSelection(cursor.from(), cursor.to());
  211. cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
  212. confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"),
  213. [function() {doReplace(match);}, advance,
  214. function() {replaceAll(cm, query, text)}]);
  215. };
  216. var doReplace = function(match) {
  217. cursor.replace(typeof query == "string" ? text :
  218. text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
  219. advance();
  220. };
  221. advance();
  222. }
  223. });
  224. });
  225. }
  226. CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
  227. CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
  228. CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
  229. CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
  230. CodeMirror.commands.findNext = doSearch;
  231. CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
  232. CodeMirror.commands.clearSearch = clearSearch;
  233. CodeMirror.commands.replace = replace;
  234. CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
  235. });