// Define search commands. Depends on dialog.js or another
// implementation of the openDialog method.
// Replace works a little oddly -- it will do the replace on the next
// Ctrl-G (or whatever is bound to findNext) press. You prevent a
// replace by making sure the match is no longer selected when hitting
// Ctrl-G.
(function(){function e(e){return typeof e=="string"?{token:function(t){if(t.match(e))return"searching";t.next(),t.skipTo(e.charAt(0))||t.skipToEnd()}}:{token:function(t){if(t.match(e))return"searching";while(!t.eol()){t.next();if(t.match(e,!1))break}}}}function t(){this.posFrom=this.posTo=this.query=null,this.overlay=null}function n(e){return e.state.search||(e.state.search=new t)}function r(e,t,n){return e.getSearchCursor(t,n,typeof t=="string"&&t==t.toLowerCase())}function i(e,t,n,r){e.openDialog?e.openDialog(t,r):r(prompt(n,""))}function s(e,t,n,r){e.openConfirm?e.openConfirm(t,r):confirm(n)&&r[0]()}function o(e){var t=e.match(/^\/(.*)\/([a-z]*)$/);return t?new RegExp(t[1],t[2].indexOf("i")==-1?"":"i"):e}function a(t,r){var s=n(t);if(s.query)return f(t,r);i(t,u,"Search for:",function(n){t.operation(function(){if(!n||s.query)return;s.query=o(n),t.removeOverlay(s.overlay),s.overlay=e(s.query),t.addOverlay(s.overlay),s.posFrom=s.posTo=t.getCursor(),f(t,r)})})}function f(e,t){e.operation(function(){var i=n(e),s=r(e,i.query,t?i.posFrom:i.posTo);if(!s.find(t)){s=r(e,i.query,t?CodeMirror.Pos(e.lastLine()):CodeMirror.Pos(e.firstLine(),0));if(!s.find(t))return}e.setSelection(s.from(),s.to()),i.posFrom=s.from(),i.posTo=s.to()})}function l(e){e.operation(function(){var t=n(e);if(!t.query)return;t.query=null,e.removeOverlay(t.overlay)})}function d(e,t){i(e,c,"Replace:",function(n){if(!n)return;n=o(n),i(e,h,"Replace with:",function(i){if(t)e.operation(function(){for(var t=r(e,n);t.findNext();)if(typeof n!="string"){var s=e.getRange(t.from(),t.to()).match(n);t.replace(i.replace(/\$(\d)/,function(e,t){return s[t]}))}else t.replace(i)});else{l(e);var o=r(e,n,e.getCursor()),u=function(){var t=o.from(),i;if(!(i=o.findNext())){o=r(e,n);if(!(i=o.findNext())||t&&o.from().line==t.line&&o.from().ch==t.ch)return}e.setSelection(o.from(),o.to()),s(e,p,"Replace?",[function(){a(i)},u])},a=function(e){o.replace(typeof n=="string"?i:i.replace(/\$(\d)/,function(t,n){return e[n]})),u()};u()}})})}var u='Search: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>',c='Replace: <input type="text" style="width: 10em"/> <span style="color: #888">(Use /re/ syntax for regexp search)</span>',h='With: <input type="text" style="width: 10em"/>',p="Replace? <button>Yes</button> <button>No</button> <button>Stop</button>";CodeMirror.commands.find=function(e){l(e),a(e)},CodeMirror.commands.findNext=a,CodeMirror.commands.findPrev=function(e){a(e,!0)},CodeMirror.commands.clearSearch=l,CodeMirror.commands.replace=d,CodeMirror.commands.replaceAll=function(e){d(e,!0)}})();