search.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. // 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. return el("", null,
  185. el("span", {className: "CodeMirror-search-label"}, cm.phrase("Search:")), " ",
  186. el("input", {type: "text", "style": "width: 10em", className: "CodeMirror-search-field"}), " ",
  187. el("span", {style: "color: #888", className: "CodeMirror-search-hint"},
  188. cm.phrase("(Use /re/ syntax for regexp search)")));
  189. }
  190. function getReplaceQueryDialog(cm) {
  191. return el("", null, " ",
  192. el("input", {type: "text", "style": "width: 10em", className: "CodeMirror-search-field"}), " ",
  193. el("span", {style: "color: #888", className: "CodeMirror-search-hint"},
  194. cm.phrase("(Use /re/ syntax for regexp search)")));
  195. }
  196. function getReplacementQueryDialog(cm) {
  197. return el("", null,
  198. el("span", {className: "CodeMirror-search-label"}, cm.phrase("With:")), " ",
  199. el("input", {type: "text", "style": "width: 10em", className: "CodeMirror-search-field"}));
  200. }
  201. function getDoReplaceConfirm(cm) {
  202. return el("", null,
  203. el("span", {className: "CodeMirror-search-label"}, cm.phrase("Replace?")), " ",
  204. el("button", {}, cm.phrase("Yes")), " ",
  205. el("button", {}, cm.phrase("No")), " ",
  206. el("button", {}, cm.phrase("All")), " ",
  207. el("button", {}, cm.phrase("Stop")));
  208. }
  209. function replaceAll(cm, query, text) {
  210. cm.operation(function() {
  211. for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
  212. if (typeof query != "string") {
  213. var match = cm.getRange(cursor.from(), cursor.to()).match(query);
  214. cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
  215. } else cursor.replace(text);
  216. }
  217. });
  218. }
  219. function replace(cm, all) {
  220. if (cm.getOption("readOnly")) return;
  221. var query = cm.getSelection() || getSearchState(cm).lastQuery;
  222. var dialogText = all ? cm.phrase("Replace all:") : cm.phrase("Replace:")
  223. var fragment = el("", null,
  224. el("span", {className: "CodeMirror-search-label"}, dialogText),
  225. getReplaceQueryDialog(cm))
  226. dialog(cm, fragment, dialogText, query, function(query) {
  227. if (!query) return;
  228. query = parseQuery(query);
  229. dialog(cm, getReplacementQueryDialog(cm), cm.phrase("Replace with:"), "", function(text) {
  230. text = parseString(text)
  231. if (all) {
  232. replaceAll(cm, query, text)
  233. } else {
  234. clearSearch(cm);
  235. var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
  236. var advance = function() {
  237. var start = cursor.from(), match;
  238. if (!(match = cursor.findNext())) {
  239. cursor = getSearchCursor(cm, query);
  240. if (!(match = cursor.findNext()) ||
  241. (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
  242. }
  243. cm.setSelection(cursor.from(), cursor.to());
  244. cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
  245. confirmDialog(cm, getDoReplaceConfirm(cm), cm.phrase("Replace?"),
  246. [function() {doReplace(match);}, advance,
  247. function() {replaceAll(cm, query, text)}]);
  248. };
  249. var doReplace = function(match) {
  250. cursor.replace(typeof query == "string" ? text :
  251. text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
  252. advance();
  253. };
  254. advance();
  255. }
  256. });
  257. });
  258. }
  259. CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
  260. CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
  261. CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
  262. CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
  263. CodeMirror.commands.findNext = doSearch;
  264. CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
  265. CodeMirror.commands.clearSearch = clearSearch;
  266. CodeMirror.commands.replace = replace;
  267. CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
  268. });