(function(g){typeof exports=="object"&&typeof module=="object"?g(require("../../lib/codemirror")):typeof define=="function"&&define.amd?define(["../../lib/codemirror"],g):g(CodeMirror)})(function(g){"use strict";var v=g.Pos;function R(r,a,f){for(var i=f.paragraphStart||r.getHelper(a,"paragraphStart"),t=a.line,e=r.firstLine();t>e;--t){var l=r.getLine(t);if(i&&i.test(l))break;if(!/\S/.test(l)){++t;break}}for(var h=f.paragraphEnd||r.getHelper(a,"paragraphEnd"),n=a.line+1,o=r.lastLine();n<=o;++n){var l=r.getLine(n);if(h&&h.test(l)){++n;break}if(!/\S/.test(l))break}return{from:t,to:n}}function A(r,a,f,i,t){for(var e=a;e<r.length&&r.charAt(e)==" ";)e++;for(;e>0&&!f.test(r.slice(e-1,e+1));--e);if(!t&&e<=r.match(/^[ \t]*/)[0].length)for(e=a+1;e<r.length-1&&!f.test(r.slice(e-1,e+1));++e);for(var l=!0;;l=!1){var h=e;if(i)for(;r.charAt(h-1)==" ";)--h;if(h==0&&l)e=a;else return{from:h,to:e}}}function m(r,a,f,i){a=r.clipPos(a),f=r.clipPos(f);var t=i.column||80,e=i.wrapOn||/\s\S|-[^\.\d]/,l=i.forceBreak!==!1,h=i.killTrailingSpace!==!1,n=[],o="",c=a.line,E=r.getRange(a,f,!1);if(!E.length)return null;var u=E[0].match(/^[ \t]*/)[0];u.length>=t&&(t=u.length+1);for(var P=0;P<E.length;++P){var s=E[P],b=o.length,p=0;o&&s&&!e.test(o.charAt(o.length-1)+s.charAt(0))&&(o+=" ",p=1);var S="";if(P&&(S=s.match(/^\s*/)[0],s=s.slice(S.length)),o+=s,P){var L=o.length>t&&u==S&&A(o,t,e,h,l);!L||L.from!=b||L.to!=b+p?n.push({text:[p?" ":""],from:v(c,b),to:v(c+1,S.length)}):(o=u+s,++c)}for(;o.length>t;){var k=A(o,t,e,h,l);if(k.from!=k.to||l&&u!==o.slice(0,k.to))n.push({text:["",u],from:v(c,k.from),to:v(c,k.to)}),o=u+o.slice(k.to),++c;else break}}return n.length&&r.operation(function(){for(var y=0;y<n.length;++y){var w=n[y];(w.text||g.cmpPos(w.from,w.to))&&r.replaceRange(w.text,w.from,w.to)}}),n.length?{from:n[0].from,to:g.changeEnd(n[n.length-1])}:null}g.defineExtension("wrapParagraph",function(r,a){a=a||{},r||(r=this.getCursor());var f=R(this,r,a);return m(this,v(f.from,0),v(f.to-1),a)}),g.commands.wrapLines=function(r){r.operation(function(){for(var a=r.listSelections(),f=r.lastLine()+1,i=a.length-1;i>=0;i--){var t=a[i],e;if(t.empty()){var l=R(r,t.head,{});e={from:v(l.from,0),to:v(l.to-1)}}else e={from:t.from(),to:t.to()};e.to.line>=f||(f=e.from.line,m(r,e.from,e.to,{}))}})},g.defineExtension("wrapRange",function(r,a,f){return m(this,r,a,f||{})}),g.defineExtension("wrapParagraphsInRange",function(r,a,f){f=f||{};for(var i=this,t=[],e=r.line;e<=a.line;){var l=R(i,v(e,0),f);t.push(l),e=l.to}var h=!1;return t.length&&i.operation(function(){for(var n=t.length-1;n>=0;--n)h=h||m(i,v(t[n].from,0),v(t[n].to-1),f)}),h})});
